Get Equal Substrings Within Budget
Master this topic with zero to advance depth.
Get Equal Substrings Within Budget
Find the maximum length of a substring that can be transformed from s to t without exceeding maxCost.
Visual Representation
s = "abcd", t = "bcdf", maxCost = 3
Costs: |a-b|=1, |b-c|=1, |c-d|=1, |d-f|=2
Window [abc] -> [bcd]: Cost = 1+1+1 = 3 (<= 3) Len 3
Window [bcd] -> [cdf]: Cost = 1+1+2 = 4 (> 3) XExamples
Level I: Brute Force
Intuition
Iterate through all possible substrings s[i...j]. For each substring, calculate the transformation cost by summing the absolute differences between s[k] and t[k] for all k in the range. If the cost , track the length.
Thought Process
- Outer loop
ifrom0ton-1. - Inner loop
jfromiton-1. - Calculate
currentCost = sum(abs(s[k] - t[k]))forkfromitoj. - If
currentCost <= maxCost,maxLen = max(maxLen, j - i + 1).
Detailed Dry Run
| i | j | Substrings | Cost | Max Len |
|---|---|---|---|---|
| 0 | 0 | 'a'->'b' | 1 | 1 |
| 0 | 1 | 'ab'->'bc' | 1+1=2 | 2 |
| 0 | 2 | 'abc'->'bcd' | 1+1+1=3 | 3 |
| 0 | 3 | 'abcd'->'bcdf' | 3+2=5 | 3 |
Level II: Binary Search on Answer (O(N log N))
Intuition
We can binary search for the maximum possible length L of a valid substring. For a fixed length L, we use a sliding window of size L to check if at least one window satisfies the maxCost constraint.
Thought Process
- Search range for
Lis[0, n]. - In each step of binary search (length
mid):- Slide a window of size
midacross the strings. - Calculate the total cost of the window.
- If
totalCost <= maxCostfor any window, thenmidis possible.
- Slide a window of size
- Adjust the search range accordingly.
Pattern: Search on Answer Space
Level III: Optimal (Sliding Window)
Intuition
Thought Process
This is a standard variable-size sliding window problem on the array of transformation costs. We expand the window as long as the total cost is within the budget, and shrink from the left when it exceeds.
Patterns
- Rolling Cost Sum: Add cost of element at
Right. - Constraint Boundary: Move
Leftas long asSum > Budget. - Max Length Utility: Result is
max(Result, Right - Left + 1).
Detailed Dry Run
| Right | Cost | Total Cost | Left | Max Len |
|---|---|---|---|---|
| 0 | 1 | 1 | 0 | 1 |
| 1 | 1 | 2 | 0 | 2 |
| 2 | 1 | 3 | 0 | 3 |
| 3 | 2 | 5 -> 4 | 1 | 3 |
⚠️ Common Pitfalls & Tips
Be mindful of binary characters vs ASCII values. Use abs(ord(s[i]) - ord(t[i])) in Python or Math.abs(s.charCodeAt(i) - t.charCodeAt(i)) in JS.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.