Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Return all start indices of anagrams of p inside s using a fixed-size window of letter counts.
Problem: Return all start indices of anagrams of p inside s using a fixed-size window of letter counts.
from collections import Counter
def anagrams(s, p):
k, need, win, out = len(p), Counter(p), Counter(), []
for i, c in enumerate(s):
win[c] += 1
if i >= k:
win[s[i-k]] -= 1
if win[s[i-k]] == 0: del win[s[i-k]]
if win == need: out.append(i - k + 1)
return out
print(anagrams("abaabaab", "aab"))What is printed?- A. [0, 1, 2, 3, 4, 5]
- B. [0, 3]
- C. [0, 2, 3, 5]
- D. [1, 2, 4, 5]
Correct answer: A. [0, 1, 2, 3, 4, 5]
Windows of length 3: aba, baa, aab, aba, baa, aab — every one has two a's and one b, so all six start indices 0–5 qualify. Deleting zero counts matters: Counter equality would otherwise compare a stored 0 with a missing key (Python's Counter ignores zeros in == since 3.10, but deleting is portable).
More Coding Interview Problems questions
- Problem: Intersect two lists of disjoint, sorted closed intervals. python def inter(A, B): i = j = 0; out = [] while i < len(A) and j <…
- Problem: Cars drive toward a target on a one-lane road. A car that catches a slower car ahead joins it as a fleet (moving at the slower…
- Problem: Return the minimum number of parentheses to insert to make a string valid. python def minadd(s): open, add = 0, 0 for c in s: if…
- Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left…
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…
- Design a set supporting insert, delete and getRandom (uniform) all in O(1) average time. Which design works?