1208. Get Equal Substrings Within Budget - Explanation
Description
The lowercase strings s and t have equal length. Changing s[i] to t[i] costs the absolute difference between their character codes; for example, changing a to d costs 3. Choose one contiguous interval and change its characters in s to match the characters at the same positions in t. Return the greatest interval length whose total cost is at most maxCost. Return 0 if no nonempty interval fits the budget.
Example 1:
Input: s = "abc"
t = "bcd"
maxCost = 2
Output: 2Explanation: Each position costs 1 to change. Any two consecutive positions cost 2 and fit the budget, but all three cost 3. The maximum length is 2.
Example 2:
Input: s = "aaz"
t = "abz"
maxCost = 0
Output: 1Explanation: The middle position costs 1, while the first and last positions already match. With a zero budget, either matching position can be chosen alone. They are not consecutive, so the maximum length is 1.
Example 3:
Input: s = "az"
t = "za"
maxCost = 24
Output: 0Explanation: Each position costs 25 to change between a and z. The budget is only 24, so no nonempty interval is affordable and the answer is 0.
Constraints:
1 <= s.length <= 100000t.length == s.lengthsandtcontain only lowercase English letters.0 <= maxCost <= 1000000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Sliding Window - Maintaining a dynamic window over an array to find optimal subarrays
- Two Pointers - Using left and right pointers to efficiently traverse and adjust window boundaries
- ASCII Character Operations - Computing differences between character codes
1. Brute Force
Intuition
We want to find the longest substring where the total transformation cost stays within the budget. The transformation cost at each position is the absolute difference between the ASCII values of the corresponding characters. By checking every possible substring and tracking its cost, we can find the maximum valid length.
Algorithm
- For each starting index
i, try extending the substring to the right. - Maintain a running cost by adding
|s[j] - t[j]|for each new character. - If the cost exceeds
maxCost, stop extending from this start. - Track the maximum valid substring length found.
- Return the maximum length.
Time & Space Complexity
- Time complexity:
- Space complexity:
2. Sliding Window
Intuition
Since we want the longest contiguous substring within a cost budget, a sliding window is ideal. We expand the window by moving the right pointer and shrink it from the left when the cost exceeds the budget. This efficiently explores all valid windows in linear time.
Algorithm
- Initialize two pointers
landrat the start, and a runningcurCostof0. - Expand the window by moving
rand adding|s[r] - t[r]|tocurCost. - While
curCostexceedsmaxCost, shrink the window by subtracting|s[l] - t[l]|and incrementingl. - Update the result with the current window size
r - l + 1. - Return the maximum window size found.
class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
curCost = 0
l = 0
res = 0
for r in range(len(s)):
curCost += abs(ord(s[r]) - ord(t[r]))
while curCost > maxCost:
curCost -= abs(ord(s[l]) - ord(t[l]))
l += 1
res = max(res, r - l + 1)
return resTime & Space Complexity
- Time complexity:
- Space complexity:
3. Sliding Window (Optimal)
Intuition
We can simplify the sliding window by never shrinking it more than one position at a time. Once we find a valid window of size k, we only care about finding windows of size k+1 or larger. If the current window is invalid, we slide both pointers together, maintaining the window size. The final answer is derived from the position of the left pointer l.
Algorithm
- Start with
l = 0and iteraterfrom0ton-1. - Subtract
|s[r] - t[r]|frommaxCost. - If
maxCostgoes negative, add back|s[l] - t[l]|and incrementlby one. - The window never shrinks below its maximum valid size.
- Return
n - las the result.
Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Forgetting to Use Absolute Value for Cost Calculation
When computing the transformation cost between characters, you must use the absolute difference |s[i] - t[i]|. Forgetting to take the absolute value will produce negative costs when t[i] < s[i], leading to incorrect results. Always wrap the difference in abs() or Math.abs().
Shrinking the Window Too Aggressively
In the standard sliding window approach, when the cost exceeds the budget, you should shrink the window from the left one step at a time while updating the running cost. A common mistake is resetting the left pointer to right + 1 or incorrectly jumping the left pointer, which skips valid substrings and produces suboptimal answers.
Returning Window Size Instead of Maximum Length
The problem asks for the maximum length found across all valid windows, not the final window size. Make sure to track and update a separate result variable with max(result, r - l + 1) after each expansion, rather than just returning r - l + 1 at the end of the loop.
Sign in to join the discussion