TRT
Sign in
hardAdvancedconcept

When would you build a suffix array, and what does it give you?

Explain suffix arrays and LCP arrays, the queries they answer, how they are built, and simpler alternatives.

TRT practice prompt — not a verified question from a named employer.

The Runtime Theory Team1 min read
Learn it firstSuffix arrays in practicePro — members onlyA suffix array lists the starting positions of a text's suffixes in sorted order. With the LCP array beside it, it answers substring search, repeated substrings and distinct-substring counts, and it underlies genome search tools.

A strong answer

A suffix array is the list of a text's suffix starting positions, sorted by the suffixes. It uses one integer per character, and with the LCP array, the common-prefix length of each pair of neighbors, it answers many substring questions.

Pattern search: suffixes that start with the pattern form one contiguous block in sorted order, found by two binary searches in O(m log n), and the block's size counts the occurrences. Longest repeated substring: the largest LCP value. Distinct substrings: n(n + 1)/2 minus the sum of the LCPs. Longest common substring of two strings: build over a + separator + b and take the largest LCP between neighbors from different strings.

Building: sorting suffixes directly is O(n² log n). Prefix doubling sorts by the first 2k characters using the ranks for the first k, in O(n log n) with radix sort; SA-IS is linear. Kasai builds the LCP array in O(n), because the common prefix drops by at most one when moving from suffix i to i + 1.

I would build one when many queries run against one large, mostly static text: genome indexes, full-text search, duplicate-code detection. For a single search, KMP or the library's find is simpler. For one repeated-substring question, binary search with rolling hashes is less code. Suffix trees answer similar questions but need many times more memory, so suffix arrays usually replace them; the FM-index built on the Burrows-Wheeler transform compresses the idea further.

What the interviewer is listening for

  • What is stored and why sorted order makes substring queries work.
  • The LCP array's role.
  • Realistic construction costs and when simpler tools suffice.

Common mistakes

  • Storing the suffix strings themselves.
  • Building with string comparisons on large inputs.
  • Reaching for a suffix array when a single KMP search would do.

This answer walks

Practice follow-ups

  1. 01How does prefix doubling sort the suffixes?
  2. 02Why does Kasai's algorithm run in linear time?
  3. 03How do you count distinct substrings?
  4. 04How does a suffix array relate to the Burrows-Wheeler transform?

Not started

Sign in to save your learning progress.

Sign in to save