Get Equal Substrings Within Budget (LeetCode 1208): Solution and Explanation
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
- Set
left = 0,cost = 0,best = 0. - For each
right, add|s[right] - t[right]|tocost. - While
cost > maxCost, subtract the cost atleftand incrementleft. - Update
best = max(best, right - left + 1). - Return
best.
Step-by-step example
s = "abcd", t = "bcdf", maxCost = 3
- Costs per position: a to b is 1, b to c is 1, c to d is 1, d to f is 2.
- right = 0: cost 1, window 0..0, best = 1.
- right = 1: cost 2, window 0..1, best = 2.
- right = 2: cost 3, window 0..2, best = 3.
- 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.
- 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 best1class Solution {
2 public int equalSubstring(String s, String t, int maxCost) {
3 int left = 0;
4 int cost = 0;
5 int best = 0;
6 for (int right = 0; right < s.length(); right++) {
7 cost += Math.abs(s.charAt(right) - t.charAt(right));
8 while (cost > maxCost) {
9 cost -= Math.abs(s.charAt(left) - t.charAt(left));
10 left++;
11 }
12 best = Math.max(best, right - left + 1);
13 }
14 return best;
15 }
16}1class Solution {
2public:
3 int equalSubstring(string s, string t, int maxCost) {
4 int left = 0;
5 int cost = 0;
6 int best = 0;
7 for (int right = 0; right < (int)s.size(); right++) {
8 cost += abs(s[right] - t[right]);
9 while (cost > maxCost) {
10 cost -= abs(s[left] - t[left]);
11 left++;
12 }
13 best = max(best, right - left + 1);
14 }
15 return best;
16 }
17};Time and space complexity
O(n)
Both pointers only move forward, so each position is added once and removed at most once.
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 exactlymaxCostis 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 becomet[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.