Get Equal Substrings Within Budget — LeetCode 1208 Python Solution

MediumStringBinary SearchPrefix SumSliding Window
Problem
#1208
Reading time
3 min

The problem

You are given two strings s and t of the same length and an integer maxCost. You want to change s to t.

Example

Input
s = "abcd", t = "bcdf", maxCost = 3
Output
3
Explanation
"abc" of s can change to "bcd".

Python solution

Python
class Solution:
    def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
        def check(x):
            for i in range(n):
                j = i + mid - 1
                if j < n and f[j + 1] - f[i] <= maxCost:
                    return True
            return False

        n = len(s)
        f = list(accumulate((abs(ord(a) - ord(b)) for a, b in zip(s, t)), initial=0))
        l, r = 0, n
        while l < r:
            mid = (l + r + 1) >> 1
            if check(mid):
                l = mid
            else:
                r = mid - 1
        return l

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1208. Get Equal Substrings Within Budget is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1208. Get Equal Substrings Within Budget?
LeetCode 1208. Get Equal Substrings Within Budget is rated Medium on LeetCode.
What is the time complexity of LeetCode 1208. Get Equal Substrings Within Budget?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1208. Get Equal Substrings Within Budget?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1208. Get Equal Substrings Within Budget cover?
LeetCode 1208. Get Equal Substrings Within Budget is tagged String, Binary Search, Prefix Sum and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview