Get Equal Substrings Within Budget - Problem

Imagine you're a text editor developer working on a smart autocorrect feature. You have two strings: s (the current text) and t (the target text), both of the same length. You want to transform s into t, but each character change has a cost.

The cost of changing the i-th character of s to the i-th character of t is |s[i] - t[i]| (the absolute difference between their ASCII values). For example, changing 'a' to 'c' costs |97 - 99| = 2.

Given a budget of maxCost, find the maximum length of a contiguous substring that you can completely transform from s to match the corresponding substring in t.

Think of it as finding the longest segment of text you can autocorrect within your computational budget!

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "abcd", t = "bcdf", maxCost = 3
โ€บ Output: 3
๐Ÿ’ก Note: We can change "abc" to "bcd" with costs |a-b| + |b-c| + |c-d| = 1 + 1 + 1 = 3, which equals maxCost. Length = 3.
example_2.py โ€” Larger Budget
$ Input: s = "abcd", t = "cdef", maxCost = 3
โ€บ Output: 1
๐Ÿ’ก Note: Each character change costs 2, so with maxCost=3, we can change at most 1 character. Any single character can be changed within budget.
example_3.py โ€” Zero Budget
$ Input: s = "abcd", t = "acde", maxCost = 0
โ€บ Output: 1
๐Ÿ’ก Note: With maxCost=0, we can only include characters that don't need changing. The first character 'a' matches, so length = 1.

Constraints

  • 1 โ‰ค s.length, t.length โ‰ค 105
  • 0 โ‰ค maxCost โ‰ค 106
  • s and t consist of only lowercase English letters
  • s.length == t.length

Visualization

Tap to expand
๐Ÿ“ Smart Text Editor with Budget ManagementBudget: 5 units | Current Selection CostOriginal:a b c d e fTarget: a e c g h iCosts: 0 3 0 3 3 3Selected: "abc"โœ“ Cost: 3 โ‰ค Budget: 53/5 Budget Used๐Ÿ’ก Sliding Window: Expand selection when budget allows, shrink when exceededTime: O(n) | Space: O(1) | Each character visited at most twice
Understanding the Visualization
1
Start Editing
Begin with an empty selection and gradually expand to include more characters
2
Check Budget
As you include each character, add its correction cost to your total
3
Manage Resources
When your budget is exceeded, remove characters from the beginning of your selection
4
Find Optimum
Keep track of the largest selection you could afford throughout the process
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window technique is perfect for finding the optimal contiguous subarray with a sum constraint, achieving linear time complexity by avoiding redundant calculations.
Asked in
Amazon 42 Google 38 Meta 24 Microsoft 18
52.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen