MediumNo. 1208
Get Equal Substrings Within Budget — LeetCode 1208 Python Solution
- Pattern
- Sliding Window
- Topics
- String, Binary Search, Prefix Sum, 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
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
- Time
- O(n × log n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 2024 | Maximize the Confusion of an Exam | Medium |
| 1044 | Longest Duplicate Substring | Hard |
| 1871 | Jump Game VII | Medium |
| 1234 | Replace the Substring for Balanced String | Medium |
| 1456 | Maximum Number of Vowels in a Substring of Given Length | Medium |
| 1839 | Longest Substring Of All Vowels in Order | Medium |
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 × 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.