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

Problem: Check whether s2 contains a permutation of s1 as a substring.

Problem: Check whether s2 contains a permutation of s1 as a substring.
def has_perm(s1, s2):
    k = len(s1)
    need = [0] * 26; win = [0] * 26
    for c in s1: need[ord(c) - 97] += 1
    for i, c in enumerate(s2):
        win[ord(c) - 97] += 1
        if i >= k: win[ord(s2[i - k]) - 97] -= 1
        if win == need: return i - k + 1
    return -1
print(has_perm("abc", "ccbbacab"), has_perm("ab", "eidboaoo"))
What is printed?
  1. A. 2 -1
  2. B. 3 -1
  3. C. 4 -1
  4. D. 3 0

Correct answer: B. 3 -1

Slide a window of length 3 over s2 and compare 26-letter counts. Windows ccb, cbb, bba fail; "bac" starting at index 3 matches the counts of "abc". No length-2 window of "eidboaoo" has one a and one b, so −1. Each step is O(26), so O(26·n) overall instead of generating all k! permutations.

More Coding Interview Problems questions

Exams that ask this topic