Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Suffix Array Implementation in Java

19 min readadvanced
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Suffix Array runs in O(n log n) time and O(n) space, in Java as in every other language.
  • ✓Nothing in the JDK builds one, and the sort API shapes the whole solution: java.util.Arrays.sort(int[]) is a dual-pivot quicksort with NO Comparator overload - you simply cannot sort primitive ints by a custom order.
  • ✓Boxing to Integer[] inside the doubling loop is the review flag: it mints n objects per round for nothing.
  • ✓The Java trap: If you do box and sort Integer[] with a comparator that reads the rank array while the same round is rewriting it, TimSort notices: it throws IllegalArgumentException with the message 'Comparison method violates its general contract!' from deep inside a merge.
  • ✓Boxed ranks cost a 16-byte Integer plus a 4-byte reference each - 20 bytes per element against 4 for an int[], five times the footprint - and they escape into the array so escape analysis cannot stack-allocate them.

What Suffix Array actually is

A suffix array is the sorted list of the starting positions of every suffix of a text: n integers, instead of the pointers-plus-nodes a suffix tree needs for the same queries. Binary-searching it finds every occurrence of a pattern in O(m log n), and paired with an LCP array (Kasai, O(n)) it answers longest-repeated-substring, distinct-substring counts and the Burrows-Wheeler transform. You reach for it when one text is searched many times and the index has to stay small: log parsing, genomics, full-text search over a fixed corpus.

Suffix Array in Java: what you actually reach for

Nothing in the JDK builds one, and the sort API shapes the whole solution: java.util.Arrays.sort(int[]) is a dual-pivot quicksort with NO Comparator overload - you simply cannot sort primitive ints by a custom order. That leaves boxing to Integer[] and Arrays.sort(Integer[], Comparator) on TimSort, or counting/radix passes you write over int[]. String.compareTo is ordinal by UTF-16 code unit (unlike C#'s culture-sensitive default), s.getBytes(StandardCharsets.US_ASCII) gives the byte view, and System.arraycopy moves the rank buffers between rounds.

Java implementation

Boxing to Integer[] inside the doubling loop is the review flag: it mints n objects per round for nothing. Reviewers want two stable counting-sort passes over int[] - radix by the second key, then by the first - buffers hoisted outside the loop and reused via System.arraycopy or a reference swap, and t[i] & 0xFF on every byte read, because Java's byte is signed and any byte above 0x7F otherwise ranks negative and sorts before everything.
java
public final class SuffixArray {
    public static int[] build(byte[] t) {
        int n = t.length;
        if (n == 0) return new int[0];
        int m = Math.max(256, n) + 2;
        int[] sa = new int[n], rank = new int[n], tmp = new int[n], key2 = new int[n];
        for (int i = 0; i < n; i++) { sa[i] = i; rank[i] = t[i] & 0xFF; }  // byte is SIGNED

        for (int k = 1; k < n; k <<= 1) {
            for (int i = 0; i < n; i++) key2[i] = (i + k < n) ? rank[i + k] + 1 : 0;
            sa = countingSort(countingSort(sa, key2, m), rank, m);   // LSD radix, no boxing
            tmp[sa[0]] = 0;
            for (int i = 1; i < n; i++) {
                int a = sa[i - 1], b = sa[i];
                boolean same = rank[a] == rank[b] && key2[a] == key2[b];
                tmp[b] = tmp[a] + (same ? 0 : 1);
            }
            System.arraycopy(tmp, 0, rank, 0, n);
            if (rank[sa[n - 1]] == n - 1) break;
        }
        return sa;
    }

    private static int[] countingSort(int[] order, int[] key, int m) {
        int[] cnt = new int[m], out = new int[order.length];
        for (int v : key) cnt[v]++;
        for (int i = 1; i < m; i++) cnt[i] += cnt[i - 1];
        for (int i = order.length - 1; i >= 0; i--) out[--cnt[key[order[i]]]] = order[i];
        return out;
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Java-specific trap

If you do box and sort Integer[] with a comparator that reads the rank array while the same round is rewriting it, TimSort notices: it throws IllegalArgumentException with the message 'Comparison method violates its general contract!' from deep inside a merge. Arrays under 32 elements take the binary-insertion path and never throw, so the unit tests are green and only the production corpus explodes. The other Java-only trap is Integer identity: valueOf caches -128 to 127, so rank[a] == rank[b] on boxed values is accidentally true for a tiny alphabet and silently false for the same logical equality once ranks pass 127.

Performance in Java, beyond the O(n log n)

Boxed ranks cost a 16-byte Integer plus a 4-byte reference each - 20 bytes per element against 4 for an int[], five times the footprint - and they escape into the array so escape analysis cannot stack-allocate them. But boxing is only the constant; the real gap is asymptotic. Two counting-sort passes make each doubling round O(n), so the whole build is O(n log n), while any comparison sort makes a round O(n log n) and the build O(n log^2 n). A Comparator is an interface call; the JIT wants on the order of ten thousand invocations before it compiles and inlines one, so a single cold build runs largely interpreted. Bounds checks on rank[sa[i]] are only eliminated when the loop bound is visibly array.length. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Suffix Array between languages.

Real-World Applications

Suffix Array applies wherever its problem shape appears in your own code. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Suffix Array helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Suffix Array appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Suffix Array over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Suffix Array to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

Frequently Asked Questions

Which Java type or library should I use for Suffix Array?

Nothing in the JDK builds one, and the sort API shapes the whole solution: java.util.Arrays.sort(int[]) is a dual-pivot quicksort with NO Comparator overload - you simply cannot sort primitive ints by a custom order. That leaves boxing to Integer[] and Arrays.sort(Integer[], Comparator) on TimSort, or counting/radix passes you write over int[]. String.compareTo is ordinal by UTF-16 code unit (unlike C#'s culture-sensitive default), s.getBytes(StandardCharsets.US_ASCII) gives the byte view, and System.arraycopy moves the rank buffers between rounds.

What is the most common Java mistake when implementing Suffix Array?

If you do box and sort Integer[] with a comparator that reads the rank array while the same round is rewriting it, TimSort notices: it throws IllegalArgumentException with the message 'Comparison method violates its general contract!' from deep inside a merge. Arrays under 32 elements take the binary-insertion path and never throw, so the unit tests are green and only the production corpus explodes. The other Java-only trap is Integer identity: valueOf caches -128 to 127, so rank[a] == rank[b] on boxed values is accidentally true for a tiny alphabet and silently false for the same logical equality once ranks pass 127.

How does Suffix Array actually perform in Java?

Boxed ranks cost a 16-byte Integer plus a 4-byte reference each - 20 bytes per element against 4 for an int[], five times the footprint - and they escape into the array so escape analysis cannot stack-allocate them. But boxing is only the constant; the real gap is asymptotic. Two counting-sort passes make each doubling round O(n), so the whole build is O(n log n), while any comparison sort makes a round O(n log n) and the build O(n log^2 n). A Comparator is an interface call; the JIT wants on the order of ten thousand invocations before it compiles and inlines one, so a single cold build runs largely interpreted. Bounds checks on rank[sa[i]] are only eliminated when the loop bound is visibly array.length. Time complexity is O(n log n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.