Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Find the longest proper prefix of s that is also a suffix (the 'happy prefix').
Problem: Find the longest proper prefix of s that is also a suffix (the 'happy prefix').
def happy(s):
p = [0] * len(s); k = 0
for i in range(1, len(s)):
while k and s[i] != s[k]: k = p[k-1]
if s[i] == s[k]: k += 1
p[i] = k
return s[:p[-1]]
print(happy("ababab"), happy("aabcaa"))What is printed?- A. abab aa
- B. ab aa
- C. abab a
- D. ababa aab
Correct answer: A. abab aa
The last KMP prefix-function value is the answer. 'ababab' has border 'abab' (overlapping is allowed); 'aabcaa' has border 'aa'.
More Coding Interview Problems questions
- Problem: Generate the 'look-and-say' sequence starting from '1'. python def nxt(s): out, i = [], 0 while i < len(s): j = i while j <…
- Problem: Print a matrix in spiral order. python def spiral(m): res = [] while m: res += m.pop(0) m = [list(r) for r in zip(m)][::-1]…
- Problem: Run Conway's Game of Life on an unbounded board (a live cell survives with 2 or 3 live neighbours; a dead cell becomes live with…
- In the Tower of Hanoi with 5 discs and 3 pegs A, B, C in a row, moves are allowed only between ADJACENT pegs (A↔B, B↔C, never A↔C…
- Problem: Count the integers in [1, 1000] that are coprime to 1000. python from math import gcd print(sum(1 for i in range(1, 1001) if…
- Reservoir sampling keeps k = 2 items from a stream of n = 10 items: the first 2 fill the reservoir, and item i (i > 2) is admitted with…