Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Count the distinct non-empty substrings of a short string.
Problem: Count the distinct non-empty substrings of a short string.
s = "ababa"
print(len({s[i:j] for i in range(len(s)) for j in range(i + 1, len(s) + 1)}))What is printed?- A. 15
- B. 10
- C. 8
- D. 9
Correct answer: D. 9
There are 15 substrings in total, but repeats collapse: the distinct ones are a, b, ab, ba, aba, bab, abab, baba, ababa, i.e. 9. For large n, a suffix automaton or suffix array does this in O(n) or O(n log n).
More Coding Interview Problems questions
- Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix). python def…
- Problem: Compute the Z-array (z[i] = length of the longest substring starting at i that matches a prefix of s; z[0] is set to 0). python…
- Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet…
- Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be…
- Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have…
- Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by…