Get Equal Substrings Within Budget solution explained

Get Equal Substrings Within Budget becomes a plain sliding window once you turn the two strings into one list of costs, the distance between the letters at each position. Grow the window to the right, shrink it from the left while its total cost is over budget, and record the longest window seen. Every position enters and leaves once, so it runs in O(n) time and O(1) space.

By Published 6 min read

The problem in plain words

You are given strings s and t of the same length and a whole-number budget. Turning the character at position i of s into the character at position i of t costs |code(s[i]) - code(t[i])|, where code is the character's numeric value. Pick a contiguous stretch of positions; you must convert every character in it. Return the length of the longest stretch whose total cost does not exceed the budget. If not even one position fits, return 0.

Pairs made up for this page; answers from the code below
stBudgetCosts per positionLongest
brickclock71, 6, 6, 0, 03 (the last three letters)
brickclock131, 6, 6, 0, 05 (the whole word costs 13)
sandwind54, 8, 0, 02 ("nd" is free)
aaaazzzz1025, 25, 25, 250
lamplamp00, 0, 0, 04
Pairs made up for this page; answers from the code below. Scroll sideways on a small screen.

What it is really asking

Strip away the strings and you have a list of non-negative numbers and a limit: find the longest contiguous run whose sum is at most the limit. Saying that translation out loud is most of the interview. After it, the interviewer mainly checks that you can justify shrinking from the left and that you handle the zero-length answer.

Brute force

def longest_within_budget_slow(s, t, budget):
    best = 0
    for i in range(len(s)):
        spent = 0
        for j in range(i, len(s)):
            spent += abs(ord(s[j]) - ord(t[j]))
            if spent > budget:
                break
            best = max(best, j - i + 1)
    return best
Extend from each start until the budget breaks: O(n²).

Each new start throws away the sums the previous start already knew. A window keeps them: when the left edge moves right by one, the sum just loses one cost.

Sliding window

Keep a window [left, right] and its total cost. For each new right position, add its cost. While the total is over budget, remove the cost at left and move left forward. Now the window is affordable, so compare its length with the best so far. Shrinking never loses a better answer: if [left, right] is over budget, any window that starts at left and ends later is also over budget, because costs only add.

def longest_within_budget(s, t, budget):
    left = 0
    spent = 0
    best = 0
    for right in range(len(s)):
        spent += abs(ord(s[right]) - ord(t[right]))
        while spent > budget:              # shrink until affordable again
            spent -= abs(ord(s[left]) - ord(t[left]))
            left += 1
        best = max(best, right - left + 1)
    return best
Python: O(n) time, O(1) space.
function longestWithinBudget(s, t, budget) {
  const cost = (i) => Math.abs(s.charCodeAt(i) - t.charCodeAt(i));
  let left = 0, spent = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    spent += cost(right);
    while (spent > budget) spent -= cost(left++);
    best = Math.max(best, right - left + 1);
  }
  return best;
}
JavaScript: cost computed on demand with charCodeAt.

When a single position costs more than the whole budget, the loop shrinks past it and left ends up at right + 1, an empty window of length 0. That is why best starting at 0 handles the "nothing fits" case with no extra code.

Trace: brick to clock, budget 7

Costs 1, 6, 6, 0, 0. Right at 0: spent 1, length 1. Right at 1: spent 7, length 2. Right at 2: spent 13, too much; drop the 1 (12), still too much; drop a 6 (6), now left is 2 and the length is 1. Right at 3: spent 6, length 2. Right at 4: spent 6, length 3. The answer is 3.

Complexity

n is the string length
ApproachTimeExtra space
Extend from each startO(n²)O(1)
Prefix sums and binary search per startO(n log n)O(n)
Sliding windowO(n)O(1)
n is the string length. Scroll sideways on a small screen.

The middle row works because prefix sums of non-negative costs only increase, so for each start you can binary search the farthest affordable end. It is a fair stepping stone if the window does not come to mind at once.

Edge cases

  • Budget 0: only runs of positions where the letters already match count.
  • Identical strings: every cost is 0, so the whole length fits any budget.
  • Every single cost above the budget: the answer is 0.
  • Uppercase or other characters: the cost is still the difference of character codes; nothing in the code assumes lowercase.

Mistakes to avoid

  • Switching while to if without understanding why it still works. With if, the window can stay over budget and only its length is right, so code that needs the actual window (to return the substring, say) breaks. Use while unless you mean the never-shrinking variant.
  • Recording the length before shrinking, which counts an over-budget window.
  • Forgetting the absolute value, so a cheaper letter in t looks like a refund.
  • Precomputing a costs array and then mixing up its index with the string's; computing on the fly avoids that.

Follow-ups

  • A window that never shrinks. Move left forward by at most one each step (an if instead of a while) and never record lengths; the window's size only grows when a longer affordable run appears, and the answer is n - left at the end. Same O(n), slightly less code, harder to explain.
  • Return the substring itself. Store the left and right positions whenever best improves.
  • Costs can be negative. The shrinking argument breaks; you would need prefix sums with a sorted structure instead.

How to explain it out loud

Fictional example

A clean verbal answer
Candidate
First I'll turn the two strings into a list of costs, the distance between the letters at each position. Now it's: longest subarray with sum at most the budget.
Candidate
Costs are non-negative, so if a window is over budget, extending it further can't help. I'll grow on the right and shrink on the left while it's over, and track the longest valid window.
Candidate
Each index is added once and removed at most once, so it's linear time and constant space.

Binary Subarrays With Sum uses this same "at most a limit" window as a building block. Maximum Points You Can Obtain from Cards and Grumpy Bookstore Owner use windows of a fixed size instead. For a variable window keyed on letters, see Longest Substring Without Repeating Characters. The full list is on the coding problems hub.

Practice support from Natively

On macOS or Windows, Natively can read this prompt from a screenshot during practice and help you phrase the cost-array translation, or check that your shrinking loop leaves the window affordable. Afterward the saved transcript of your mock shows whether you explained why shrinking is safe. Learn more on the AI interview assistant page.

Questions people ask

How do you solve Get Equal Substrings Within Budget?

Treat the absolute difference of the letters at each position as a cost. Slide a window: add the cost on the right, shrink from the left while the total exceeds the budget, and track the longest window.

Why can you shrink the window in Get Equal Substrings Within Budget?

Costs are never negative, so a window that is over budget stays over budget if you extend it. Moving the left edge forward is the only way to become affordable again.

What is the time complexity of Get Equal Substrings Within Budget?

O(n) time and O(1) extra space. Each position enters the window once and leaves at most once.

What if no single character can be changed within the budget?

The window shrinks to length 0 at every step, so the answer is 0. Starting the best length at 0 covers this case.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP