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?
  1. A. [5, 3, 1, 0, 4, 2] [0, 1, 3, 0, 2]
  2. B. [0, 1, 2, 3, 4, 5] [1, 3, 0, 0, 2]
  3. C. [5, 3, 1, 0, 4, 2] [1, 3, 0, 0, 2]
  4. 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

Exams that ask this topic