Get Equal Substrings Within Budget (LeetCode 1208): Solution and Explanation

Medium
String
Binary search
Sliding window
Prefix sum

Each position has a fixed cost |s[i] - t[i]|, so the strings reduce to an array of non-negative costs. The answer is the longest window of that array whose sum stays within maxCost, found with a classic grow and shrink window.

Intuition

The letters themselves stop mattering once you compute cost[i] = |s[i] - t[i]|. Changing a substring costs the sum of its positions, and the positions must be the same in both strings.

So the question becomes: what is the longest contiguous run of cost with sum at most maxCost?

Every cost is zero or more. Adding a position never lowers the sum and removing one never raises it, which is exactly the property a sliding window needs. Grow on the right, and shrink from the left only when the budget is exceeded.

Approach: Variable-size sliding window

  1. Set left = 0, cost = 0, best = 0.
  2. For each right, add |s[right] - t[right]| to cost.
  3. While cost > maxCost, subtract the cost at left and increment left.
  4. Update best = max(best, right - left + 1).
  5. Return best.

Step-by-step example

s = "abcd", t = "bcdf", maxCost = 3
  1. Costs per position: a to b is 1, b to c is 1, c to d is 1, d to f is 2.
  2. right = 0: cost 1, window 0..0, best = 1.
  3. right = 1: cost 2, window 0..1, best = 2.
  4. right = 2: cost 3, window 0..2, best = 3.
  5. right = 3: cost 5 > 3. Drop index 0 (cost 4), still over, drop index 1 (cost 3). Window 2..3 has length 2, best stays 3.
  6. Answer: 3.

Code: Python, Java, C++

1class Solution:
2    def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
3        left = 0
4        cost = 0
5        best = 0
6        for right in range(len(s)):
7            cost += abs(ord(s[right]) - ord(t[right]))
8            while cost > maxCost:
9                cost -= abs(ord(s[left]) - ord(t[left]))
10                left += 1
11            best = max(best, right - left + 1)
12        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Variable-size sliding window O(n)
Non-shrinking window O(n)
Prefix sums with binary search O(n log n)
Time

O(n)

Both pointers only move forward, so each position is added once and removed at most once.

Space

O(1)

Costs are computed on the fly; only a few integers are stored.

Other approaches

Prefix sums with binary search (time O(n log n), space O(n))

Build prefix sums of the costs. For each right end, binary search the smallest left with prefix[right + 1] - prefix[left] <= maxCost. Works because the prefix is non-decreasing.

Non-shrinking window (time O(n), space O(1))

Move left by at most one per step instead of using a while loop. The window never shrinks, so its final size is the answer. Same O(n), slightly less obvious.

Common mistakes

  • Comparing with >= instead of > when shrinking. A window that spends exactly maxCost is allowed.
  • Assuming the answer is at least 1. If every position costs more than maxCost, the window is empty and the answer is 0.
  • Treating the problem as matching characters inside the strings. Positions are fixed: s[i] can only become t[i].

Frequently asked questions

Why does a sliding window work here?

All costs are non-negative, so extending the window can only increase its cost and shrinking it can only decrease it. That monotonic behaviour lets each pointer move one way.

Can the answer be 0?

Yes. With maxCost = 0 and no position where s and t already match, no substring is affordable.

Which problem is this most similar to?

Max Consecutive Ones III and Minimum Size Subarray Sum use the same grow and shrink window on a non-negative quantity.

What is the time and space complexity?

O(n) time and O(1) extra space.