Get Equal Substrings Within Budget — LeetCode 1208 Python Solution
MediumStringBinary SearchPrefix SumSliding Window
- Problem
- #1208
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
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 lComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(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
LeetCode 2024Maximize the Confusion of an ExamMediumLeetCode 1044Longest Duplicate SubstringHardLeetCode 1871Jump Game VIIMediumLeetCode 1234Replace the Substring for Balanced StringMediumLeetCode 1456Maximum Number of Vowels in a Substring of Given LengthMediumLeetCode 1839Longest Substring Of All Vowels in OrderMedium
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.