Python 1208.py
class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
result = 0
diffs = [ abs(ord(s[i]) - ord(t[i])) for i in range(len(s)) ]
cost = 0
left = 0
for right in range(len(diffs)):
# make string longer
cost += diffs[right]
# make string shorter
while cost > maxCost:
cost -= diffs[left]
left += 1
result = max(result, right - left + 1)
return result
Difficulty
and has an acceptance rate of about 60% (300k+ submissions).
Typical patterns to solve this problem:
- Binary Search
- Prefix Sum
- Sliding Window
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of finding the longest substring that can be transformed from one string to another without exceeding a given total cost. It does this by first converting the character-wise differences into a numeric array and then applying a sliding-window technique to maintain a contiguous segment whose cumulative cost stays within the allowed budget. The length of the widest feasible window is returned as the answer.
Key Steps
Compute character differences
The algorithm begins by translating the two input strings into an array of absolute differences between corresponding characters. This preprocessing step reduces the subsequent logic to simple integer arithmetic.
diffs = [abs(ord(s[i]) - ord(t[i])) for i in range(len(s))]
Expand window
A right pointer iterates over the diffs array, progressively adding each new difference to a running total called cost. This represents the expense of converting the current window from the left pointer up to the right pointer.
for right in range(len(diffs)):
cost += diffs[right]
Shrink window when cost exceeds limit
Whenever the accumulated cost surpasses maxCost, the left side of the window is moved forward. The difference at the former left index is subtracted from cost, and the left pointer is incremented. This loop continues until the window’s total cost is again within the permitted budget.
while cost > maxCost:
cost -= diffs[left]
left += 1
Update result
After each adjustment, the algorithm computes the current window size as right - left + 1 and updates the best length found so far. The max function ensures that the longest valid window observed during the scan is retained.
result = max(result, right - left + 1)
Finally, the function returns the recorded maximum length.
return result
Edge Cases Handled
The sliding-window structure naturally accommodates several boundary conditions. When both input strings are empty, the diffs list is empty, the loop body never executes, and result remains zero, which correctly reflects that no substring can be formed. If maxCost is zero, the inner while loop forces the window to shrink whenever any non-zero difference appears, effectively limiting the result to stretches of identical characters. When all character differences are zero, the cost never exceeds maxCost, allowing the window to expand across the entire length of the strings, and the function returns the full length. Conversely, if every difference exceeds maxCost, the window collapses to size one at each position, and the result becomes either zero (if the single-character cost is also too high) or one (if a single conversion fits within the budget). The algorithm also works correctly when the two strings have the same length but contain a mixture of cheap and expensive conversions, dynamically adjusting the window to capture the longest affordable segment.
Performance Optimizations
The solution achieves linear time performance by traversing the input exactly once with the right pointer while the left pointer only moves forward as needed. Precomputing the absolute differences into the diffs list eliminates repeated character-wise calculations inside the main loop, turning each step into a constant-time integer addition or subtraction. The use of simple scalar variables (cost, left, right, result) avoids the overhead of more complex data structures, keeping memory usage minimal and cache-friendly. By updating the result in place rather than storing intermediate windows, the algorithm maintains a low memory footprint while still delivering the correct maximum length.
ELI5 - Simplified Explanation
Imagine you have two rows of colorful building blocks, and each block has a special number hidden inside it. You want to see how many matching blocks you can line up next to each other, but there is a rule about how much work it takes to make them match. The work is just the difference between the hidden numbers of the two blocks you are looking at.
Think of a sliding window that moves across these rows. At the start, the window is empty. You begin adding blocks one by one to the right side of your window. Every time a block enters the window, you add the work it takes to match it to your total cost. If the cost gets too high and goes over your budget, the window needs to shrink from the left side. You take away the first block in the window and subtract its work cost from your total until you are back under budget again.
As the window moves across the rows, you keep track of the biggest window you have managed to make. You keep trying to stretch it as far to the right as you can and then trimming the left side when the cost gets too big. By the time the window finishes traveling across all the blocks, the size of the biggest window found is the answer.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python |
Videos
Solved On The Same Day
- problem 2465: Number of Distinct Averages
- problem 2566: Maximum Difference by Remapping a Digit
- problem 2855: Minimum Right Shifts to Sort the Array
- problem 1277: Count Square Submatrices with All Ones
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality