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?- A. (3, 11998)
- B. (2, 11998)
- C. (2, 144000000)
- 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
- Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it…
- Problem: Find the bug: binary search for the LAST x in [lo, hi] with ok(x) true (here the largest x with x² ≤ 30). The first version uses…
- Problem: n ≤ 2·10⁵ meetings [s, e); choose the maximum number of non-overlapping ones. Compare three greedy orders: by end time, by start…
- Problem: A road network has weights 1..5 (n, m ≤ 2·10⁵). A candidate solution runs plain BFS and sets dist[v] = dist[u] + w the first time…
- Problem: Each link succeeds with a probability; find the most reliable path from 0 to 3 (maximise the product). Dijkstra works with a…
- Problem: Board game on squares 1..n: roll a die (1–6); landing on the foot of a ladder or the head of a snake moves you to its other end…