#1208
Get Equal Substrings Within Budget
MediumStringBinary SearchSliding WindowPrefix SumSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a sliding window technique to efficiently find the longest valid substring. By maintaining a window that expands and contracts based on the cost, we can achieve linear time complexity.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers (left and right) and a variable to keep track of the total cost.
- 2Step 2: Expand the right pointer to include characters until the total cost exceeds maxCost.
- 3Step 3: If the cost exceeds maxCost, move the left pointer to reduce the cost.
- 4Step 4: Update the maximum length of the substring whenever the cost is within the allowed budget.
- 5Step 5: Return the maximum length found.
solution.py13 lines
1# Full working Python code
2
3def equalSubstring(s, t, maxCost):
4 left = 0
5 total_cost = 0
6 max_length = 0
7 for right in range(len(s)):
8 total_cost += abs(ord(s[right]) - ord(t[right]))
9 while total_cost > maxCost:
10 total_cost -= abs(ord(s[left]) - ord(t[left]))
11 left += 1
12 max_length = max(max_length, right - left + 1)
13 return max_lengthℹ
Complexity note: This complexity is linear because each character is processed at most twice (once by the right pointer and once by the left pointer), leading to efficient traversal of the string.
- 1Using a sliding window allows us to efficiently manage the cost without recalculating for every substring.
- 2The absolute difference in ASCII values directly translates to the cost of changing characters, making calculations straightforward.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.