Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Find every start index in s of a substring that is a concatenation of all the given words (each exactly once, any order; all words have the same length).
Problem: Find every start index in s of a substring that is a concatenation of all the given words (each exactly once, any order; all words have the same length).
from collections import Counter
def find(s, words):
w, k = len(words[0]), len(words); need = Counter(words); out = []
for i in range(len(s) - w * k + 1):
seen = Counter(s[i + j * w: i + (j + 1) * w] for j in range(k))
if seen == need: out.append(i)
return out
print(find("catdogdogcatbirdcatdog", ["cat", "dog"]))What is printed?- A. [0, 6, 16]
- B. [0, 6]
- C. [0, 3, 6, 16]
- D. [0, 6, 13, 16]
Correct answer: A. [0, 6, 16]
Windows of length 6 must split into one 'cat' and one 'dog'. Index 0 'catdog' ✓, 3 'dogdog' ✗, 6 'dogcat' ✓, 16 'catdog' ✓. Windows that start mid-word (like 1 or 2) never split into dictionary words.
More Coding Interview Problems questions
- Problem: Find the shortest contiguous substring of S that contains T as a SUBSEQUENCE (leftmost on ties). Scan forward to complete T, then…
- Problem: Find the longest substring that occurs at least twice (occurrences may overlap): binary search on the length with a set of…
- Problem: Count how many words are subsequences of s, by bucketing words by the next character they are waiting for. python from…
- Problem: Roads are one-way (a → b). Reorient the fewest roads so every city can reach city 0 (the roads form a tree). python def…
- Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island)…
- Problem: Return the city that can reach the FEWEST other cities within a distance threshold (largest index on ties), using Floyd–Warshall…