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?- A. 2 -1
- B. 3 -1
- C. 4 -1
- 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
- Problem: Return the longest common prefix of a list of file paths. python def lcp(words): if not words: return "" p = words[0] for w in…
- Problem: Compute the minimum number of characters to add at the end of s so that it becomes a palindrome, using the KMP prefix function…
- Problem: Search a pattern of length m in a text of length n = 10⁶ (m up to 10⁵) and report all match positions. Which method guarantees…
- Problem: Return the longest palindromic substring of s (first one if there is a tie). python def lps(s): best = "" for c in range(len(s))…
- Problem: Check whether a string of brackets ()[]{} is balanced. python def balanced(s): pair = {')': '(', ']': '[', '}': '{'} st = [] for…
- Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never). python def wait(t): res, st = [0]…