Problem 1208

Abstract / Summary

Find the longest substring in two given strings that can be made equal by changing characters within a given cost limit.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
18 lines | 536 bytes | submitted January 8, 2024 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (300k+ submissions).

Typical patterns to solve this problem:
  • Binary Search
  • Prefix Sum
  • Sliding Window
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.15 | σ = 1.01

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
22 links | 11 authors | 7 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   January 8, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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