Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: A sliding-window routine has a while loop nested inside a for loop. For a 12 000-character string, how many inner (left-pointer) moves happen, and what is the complexity?

Problem: A sliding-window routine has a while loop nested inside a for loop. For a 12 000-character string, how many inner (left-pointer) moves happen, and what is the complexity?
from collections import Counter
def longest_k_distinct(s, k):
    c = Counter(); l = best = moves = 0
    for r, ch in enumerate(s):
        c[ch] += 1
        while len(c) > k:
            c[s[l]] -= 1
            if c[s[l]] == 0: del c[s[l]]
            l += 1; moves += 1
        best = max(best, r - l + 1)
    return best, moves
print(longest_k_distinct("abc" * 4000, 2))
What is printed?
  1. A. (3, 11998)
  2. B. (2, 11998)
  3. C. (2, 144000000)
  4. D. (2, 6000)

Correct answer: B. (2, 11998)

The left pointer only moves forward and never passes the right pointer, so across the whole run it moves at most n times: here 11 998 moves for n = 12 000, i.e. amortised O(1) per step and O(n) overall – not O(n²) despite the nesting. In "abcabc…" any three consecutive letters are distinct, so the best window with ≤ 2 distinct letters has length 2.

More Coding Interview Problems questions

Exams that ask this topic