Get Equal Substrings Within Budget

MediumSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given two strings s and t of the same length and an integer max_cost. Changing s[i] into t[i] costs |ord(s[i]) - ord(t[i])|, the absolute difference of their character codes. Find the longest substring of s that can be changed into the substring of t at the **same indices** with total cost at most max_cost. Return its length, or 0 if no non-empty substring fits the budget.

Examples

Input: s = "abcd", t = "bcdf", max_cost = 3
Output: 3
"abc" -> "bcd" costs 1 + 1 + 1 = 3.
Input: s = "abcd", t = "cdef", max_cost = 3
Output: 1
Every position costs 2, so only one character fits.
Input: s = "abcd", t = "acde", max_cost = 0
Output: 1
Index 0 already matches for free.

Constraints

  • 1 <= s.length <= 10^5
  • t.length == s.length
  • 0 <= max_cost <= 10^6
  • `s` and `t` consist of lowercase English letters

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems