The Get Equal Substrings Within Budget interview question gives you two strings, s and t, of the same length. You also have a maxCost. The cost of changing a character in s to the corresponding character in t is the absolute difference of their ASCII values. You want to find the maximum length of a substring of s that can be transformed into the corresponding substring of t without exceeding maxCost.
Microsoft and Meta ask this Sliding Window coding problem to evaluate your ability to optimize contiguous subarray searches. It tests whether you can translate character differences into an array of "costs" and then find the longest subarray whose sum is less than or equal to a target. It's a classic application of the two-pointer technique.
This problem is perfectly suited for the Sliding Window interview pattern.
cost[i] = abs(s[i] - t[i]).left and right, to define a window.right forward, adding cost[right] to a running current_cost.current_cost > maxCost, move left forward and subtract cost[left] from current_cost until current_cost <= maxCost.right - left + 1) during the process.s = "abcd", t = "bcdf", maxCost = 3
|'a'-'b'| = 1, |'b'-'c'| = 1, |'c'-'d'| = 1, |'d'-'f'| = 2. Cost array = [1, 1, 1, 2].right = 0: cost is 1. Max length = 1.right = 1: cost is 1+1=2. Max length = 2.right = 2: cost is 2+1=3. Max length = 3.right = 3: cost is 3+2=5. Exceeds maxCost (3).
left to 1. Cost is 5-1=4.left to 2. Cost is 4-1=3.
Max length remains 3.if statement instead of a while loop when shrinking the window. A single step of right might require multiple steps of left to get back under budget.The phrase "maximum length of a substring/subarray with sum " is the ultimate signal to use a sliding window. Practice the standard while (cost > maxCost) { ... left++ } template.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximize the Confusion of an Exam | Medium | Solve | |
| Max Consecutive Ones III | Medium | Solve | |
| Subarray Product Less Than K | Medium | Solve | |
| Minimum Size Subarray Sum | Medium | Solve | |
| Jump Game VII | Medium | Solve |