Get Equal Substrings Within Budget - Problem

You are given two strings s and t of the same length and an integer maxCost. You want to change s to t. Changing the i-th character of s to the i-th character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).

Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost.

If there is no substring from s that can be changed to its corresponding substring from t, return 0.

Input & Output

Example 1 — Basic Transformation
$ Input: s = "abcd", t = "bcdf", maxCost = 3
Output: 3
💡 Note: We can change "abc" to "bcd" with cost |a-b| + |b-c| + |c-d| = 1 + 1 + 1 = 3, giving us a substring of length 3.
Example 2 — Single Character
$ Input: s = "abcd", t = "cdef", maxCost = 3
Output: 1
💡 Note: Each character transformation costs 2, so with maxCost = 3, we can only transform 1 character at a time.
Example 3 — No Budget
$ Input: s = "abcd", t = "acde", maxCost = 0
Output: 1
💡 Note: Characters 'a' at position 0 match (cost 0), so we can have a substring of length 1 with no cost.

Constraints

  • 1 ≤ s.length, t.length ≤ 105
  • 0 ≤ maxCost ≤ 106
  • s and t contain only lowercase English letters

Visualization

Tap to expand
Get Equal Substrings Within Budget INPUT String s: a b c d String t: b c d f Cost Array |s[i]-t[i]|: 1 1 1 2 maxCost = 3 i=0 i=1 i=2 i=3 ALGORITHM STEPS 1 Sliding Window Use two pointers: left, right 2 Expand Right Add cost[right] to window sum 3 Shrink if Over Budget While sum > maxCost: left++ 4 Track Max Length maxLen = max(maxLen, r-l+1) Window Trace: 1 1 1 2 sum=3 Window [0,2]: cost=1+1+1=3 Window [0,3]: cost=5 > 3 Shrink --> [1,3]: cost=4 > 3 Shrink --> [2,3]: cost=3 Max length found: 3 FINAL RESULT Optimal Substring: a b c d "abc" changes to "bcd" Cost Breakdown: a --> b: |97-98| = 1 b --> c: |98-99| = 1 c --> d: |99-100| = 1 Total Cost: 3 <= maxCost OUTPUT 3 [OK] Max length = 3 Key Insight: The Sliding Window technique efficiently finds the maximum substring length in O(n) time. By maintaining a running sum of costs and shrinking from the left when budget is exceeded, we avoid recalculating costs for overlapping windows. Each element is visited at most twice. TutorialsPoint - Get Equal Substrings Within Budget | Sliding Window Approach
Asked in
Facebook 25 Amazon 20 Google 15
32.0K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen