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 ith character of s to ith 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.
Example 1:
Input: s = "abcd", t = "bcdf", maxCost = 3 Output: 3 Explanation: "abc" of s can change to "bcd". That costs 3, so the maximum length is 3.
Example 2:
Input: s = "abcd", t = "cdef", maxCost = 3 Output: 1 Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.
Example 3:
Input: s = "abcd", t = "acde", maxCost = 0 Output: 1 Explanation: You cannot make any change, so the maximum length is 1.
Constraints:
1 <= s.length <= 105t.length == s.length0 <= maxCost <= 106s and t consist of only lowercase English letters.Problem Overview: You are given two equal-length strings s and t and an integer maxCost. Changing s[i] to t[i] costs abs(s[i] - t[i]). The goal is to find the maximum length substring you can convert without the total cost exceeding maxCost.
Approach 1: Sliding Window (O(n) time, O(1) space)
The optimal solution uses the sliding window technique. Treat the cost of transforming each character as a running sum while expanding a window with two pointers. Move the right pointer forward and add the cost abs(s[i] - t[i]). If the total cost exceeds maxCost, shrink the window from the left and subtract those costs until the budget is valid again. At every step, update the maximum window length. Each character enters and leaves the window at most once, giving O(n) time complexity and O(1) extra space. This works because substring costs are additive and the constraint only cares about the total within the current window.
Approach 2: Prefix Sum with Binary Search (O(n log n) time, O(n) space)
This approach precomputes the cost difference between s[i] and t[i] and stores cumulative values in a prefix array. Using prefix sums, the cost of any substring [l, r] becomes prefix[r+1] - prefix[l]. For each starting index, perform a binary search to find the farthest ending index whose cost stays within maxCost. This reduces repeated summation and leverages the monotonic nature of prefix sums. The outer loop runs n times and each search takes O(log n), resulting in O(n log n) time and O(n) space. It’s useful when you want a more general framework for cost queries across many substrings.
Recommended for interviews: The sliding window approach is the expected solution. Interviewers want to see that you recognize the problem as a classic variable-length window where the constraint is a running sum bounded by a budget. Demonstrating the prefix-sum + binary-search approach still shows solid problem solving, but the O(n) sliding window solution highlights stronger algorithmic intuition.
This approach uses the sliding window technique to efficiently determine the maximum substring length that can be changed within the given cost. We maintain a window of characters from the strings s and t and slide it over the strings. We continuously calculate the cost for converting the current window substring from s to t. Whenever the cost exceeds maxCost, we shrink the window from the left to keep the cost under control. The maximum width of this window during traversal is the answer.
The implementation starts by initializing pointers for the start, end of the current window, and an integer for tracking the current cost. We iterate through each character, calculating the cost of changing one character to the other. If the accumulated cost exceeds maxCost, we shrink the window from the left by incrementing the start pointer and updating the cost accordingly. We track the maximum window length for which the cost is within the allowed limit. Finally, the function returns this maximum length.
Time Complexity: O(n), where n is the length of the string s.
Space Complexity: O(1), as the solution uses only a fixed amount of extra space.
This approach makes use of the prefix sum array to store accumulated costs and binary search to find the furthest valid endpoint for every starting point. First, calculate the prefix sum that stores the total cost from the beginning to any character index. Then, for each start point, use binary search to find the furthest valid end point where the total transformation cost still doesn't exceed maxCost.
In this C implementation, we first calculate a prefix sum array that helps to track cumulative costs. The binary search function is used to find the maximum valid substring end starting from any specific index, adjusting based on the total permissible cost. The largest detected substring length is returned.
Time Complexity: O(n log n), where n is the length of the string s due to the binary search iterations for each starting point.
Space Complexity: O(n), as it requires space for the prefix sum array.
We can create an array f of length n + 1, where f[i] represents the sum of the absolute differences of ASCII values between the first i characters of string s and the first i characters of string t. Thus, we can calculate the sum of the absolute differences of ASCII values from the i-th character to the j-th character of string s by f[j + 1] - f[i], where 0 leq i leq j < n.
Note that the length has monotonicity, i.e., if there exists a substring of length x that satisfies the condition, then a substring of length x - 1 must also satisfy the condition. Therefore, we can use binary search to find the maximum length.
We define a function check(x), which indicates whether there exists a substring of length x that satisfies the condition. In this function, we only need to enumerate all substrings of length x and check whether they satisfy the condition. If there exists a substring that satisfies the condition, the function returns true, otherwise it returns false.
Next, we define the left boundary l of binary search as 0 and the right boundary r as n. In each step, we let mid = \lfloor \frac{l + r + 1}{2} \rfloor. If the return value of check(mid) is true, we update the left boundary to mid, otherwise we update the right boundary to mid - 1. After the binary search, the left boundary we get is the answer.
The time complexity is O(n times log n), and the space complexity is O(n). Here, n is the length of string s.
Python
Java
C++
Go
TypeScript
We can maintain two pointers l and r, initially l = r = 0; maintain a variable cost, which represents the sum of the absolute values of the ASCII code differences in the index interval [l,..r]. In each step, we move r to the right by one position, then update cost = cost + |s[r] - t[r]|. If cost \gt maxCost, then we loop to move l to the right by one position, and decrease the value of cost, until cost leq maxCost. Then we update the answer, that is, ans = max(ans, r - l + 1).
Finally, return the answer.
The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).
Python
Java
C++
Go
TypeScript
In Solution 2, the interval maintained by the two pointers may become shorter or longer. Since the problem only requires the maximum length, we can maintain a monotonically increasing interval.
Specifically, we use two pointers l and r to point to the left and right endpoints of the interval, initially l = r = 0. In each step, we move r to the right by one position, then update cost = cost + |s[r] - t[r]|. If cost \gt maxCost, then we move l to the right by one position, and decrease the value of cost.
Finally, return n - l.
The time complexity is O(n), and the space complexity is O(1). Where n is the length of the string s.
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Sliding Window Approach | Time Complexity: O(n), where n is the length of the string s. |
| Prefix Sum with Binary Search | Time Complexity: O(n log n), where n is the length of the string s due to the binary search iterations for each starting point. |
| Prefix Sum + Binary Search | — |
| Two Pointers | — |
| Another Way of Using Two Pointers | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sliding Window | O(n) | O(1) | Best choice for contiguous substring problems with a running constraint like cost or sum |
| Prefix Sum + Binary Search | O(n log n) | O(n) | Useful when prefix sums are already available or when answering multiple substring cost queries |
Get Equal Substrings Within Budget - Leetcode 1208 - Python • NeetCodeIO • 9,625 views views
Watch 9 more video solutions →Practice Get Equal Substrings Within Budget with our built-in code editor and test cases.
Practice on FleetCode