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?
  1. A. [0, 6, 16]
  2. B. [0, 6]
  3. C. [0, 3, 6, 16]
  4. 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

Exams that ask this topic