Problem Statement
You are given two strings s and t of equal length n, consisting only of lowercase English letters, and an integer K — the maximum allowed total transformation cost.
For any index i, changing s[i] into t[i] costs the absolute difference of their ASCII values: |s[i] - t[i]|.
Find the maximum length of a contiguous substring of s that can be transformed into the corresponding substring of t such that the total transformation cost is ≤ K. Return 0 if no such substring exists.
Constraints
1 <= n <= 2 * 10^50 <= K <= 10^6sandtcontain only lowercase English letterssandthave equal length
Example
Input:
s = "adpgkl"
t = "cdmxki"
K = 6
Output: 3
Explanation:
- Transform
s[0]'a'→'c': cost|a-c| = 2 - Transform
s[1]'d'→'d': cost0 - Transform
s[2]'p'→'m': cost3 - Total for
s[0..2]=2 + 0 + 3 = 5 ≤ 6✓ - Adding
s[3]'g'→'x' costs17, blowing the budget.
Maximum valid substring length = 3.
What the Interviewer Expects
- Reframe the problem — build a cost array
cost[i] = |s[i] - t[i]|. Now the question becomes: "find the longest contiguous subarray ofcostwhose sum is ≤ K." - Recognize the sliding window — because all costs are non-negative, a classic variable-size sliding window works perfectly:
- Expand the right pointer, adding
cost[right]to a running sum. - While the sum exceeds
K, shrink from the left. - Track the maximum window size seen.
- Expand the right pointer, adding
- Why sliding window works here — non-negative costs mean the window sum is monotonic as you expand/shrink. (If costs could be negative, you'd need a different approach.)
- Complexity — O(n) time, O(1) extra space. Each pointer moves at most n times.
Follow-ups
- Why does the sliding window approach rely on costs being non-negative?
- What if you were allowed to SKIP up to
mcharacters (not count their cost)? How does the approach change? - What if
sandthad different lengths and you needed to align them optimally? - Could you answer multiple queries with different K values efficiently? (prefix sums + binary search)
- This is essentially "Longest Subarray with Sum ≤ K" — where else does that pattern appear?