Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Build the suffix array of a string (start indices of suffixes in sorted order) and its LCP array (Kasai's algorithm).
Problem: Build the suffix array of a string (start indices of suffixes in sorted order) and its LCP array (Kasai's algorithm).
def sa_lcp(s):
sa = sorted(range(len(s)), key=lambda i: s[i:])
rank = [0] * len(s)
for i, p in enumerate(sa): rank[p] = i
lcp, k = [0] * (len(s) - 1), 0
for i in range(len(s)):
if rank[i] == len(s) - 1: k = 0; continue
j = sa[rank[i] + 1]
while i + k < len(s) and j + k < len(s) and s[i+k] == s[j+k]: k += 1
lcp[rank[i]] = k
if k: k -= 1
return sa, lcp
print(*sa_lcp("banana"))What is printed?- A. [5, 3, 1, 0, 4, 2] [0, 1, 3, 0, 2]
- B. [0, 1, 2, 3, 4, 5] [1, 3, 0, 0, 2]
- C. [5, 3, 1, 0, 4, 2] [1, 3, 0, 0, 2]
- D. [5, 3, 1, 0, 4, 2] [1, 2, 3, 0, 0]
Correct answer: C. [5, 3, 1, 0, 4, 2] [1, 3, 0, 0, 2]
Sorted suffixes: a (5), ana (3), anana (1), banana (0), na (4), nana (2). Adjacent common prefixes: a/ana = 1, ana/anana = 3, anana/banana = 0, banana/na = 0, na/nana = 2. Kasai's k decreases by at most 1 per step, giving O(n).
More Coding Interview Problems questions
- Problem: A Fenwick tree over a DIFFERENCE array supports 'add v to a[l..r]' and 'read a[i]' in O(log n) (1-indexed, all zeros initially)…
- Problem: Point-update / range-maximum segment tree (iterative, size n = 8). python n = 8; t = [0] (2 n) def upd(i, v): i += n; t[i] = v…
- Mo's algorithm answers q offline range queries on an array of n elements by sorting queries into √n-sized blocks of their left ends. If…
- Problem: Edges arrive one by one; report the first edge that creates an ODD cycle (making the graph non-bipartite), using union-find with…
- Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order). python edges =…
- Find the bug: Dijkstra (finalising a node when first popped) is run on a graph with a NEGATIVE edge. Compare with Bellman–Ford. python…