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

Text Search Engine 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

  • ✓Text Search Engine runs in O(n log n) time and O(n) space, in Java as in every other language.
  • ✓No suffix array in the JDK. You get java.util.Arrays for sorting and binary search, String.getBytes(StandardCharsets.UTF_8) from java.nio.charset for the corpus bytes, java.text.BreakIterator for locale-aware word segmentation when you tokenize, java.text.Collator for linguistic term ordering, and java.util.regex for the scan fallback.
  • ✓Primitive arrays everywhere the API permits (byte[] corpus, int[] suffix array, int[] rank), boxing confined to the one place the JDK forces it.
  • ✓The Java trap: byte is signed in Java and in none of the other seven languages here. A UTF-8 continuation or lead byte, 0x80 through 0xFF, reads as -128 through -1, so every suffix starting with a non-ASCII character sorts before every ASCII suffix.
  • ✓Arrays.sort(int[]) is a tuned dual-pivot quicksort with no allocation, and you lose it the instant you need a comparator, because there is no comparator overload for primitive arrays.

What Text Search Engine actually is

An in-memory full-text index that answers "which documents contain this substring" without rescanning the corpus. Concatenate every document into one byte buffer, sort all n suffixes by prefix doubling, and keep two things: the suffix array of offsets and the document-start boundaries. Written the way every snippet here writes it, with a comparison sort inside each of the log n rounds, that build is O(n log^2 n); radix-sorting each round brings it to O(n log n), and SA-IS, which is what Go's index/suffixarray uses, is linear. The index itself is O(n) space. Any pattern of length m is then a contiguous range of the suffix array, found by two binary searches in O(m log n). You reach for this instead of an inverted index when queries are infix, code-like, or in a language you cannot reliably tokenize.

Text Search Engine in Java: what you actually reach for

No suffix array in the JDK. You get java.util.Arrays for sorting and binary search, String.getBytes(StandardCharsets.UTF_8) from java.nio.charset for the corpus bytes, java.text.BreakIterator for locale-aware word segmentation when you tokenize, java.text.Collator for linguistic term ordering, and java.util.regex for the scan fallback. Note that Arrays.binarySearch has no overload taking a comparator over int[], so the lower-bound search is yours to write. The ecosystem answer for anything ranked is Apache Lucene: org.apache.lucene.index.IndexWriter, DirectoryReader and IndexSearcher, with StandardAnalyzer doing the tokenization.

Java implementation

Primitive arrays everywhere the API permits (byte[] corpus, int[] suffix array, int[] rank), boxing confined to the one place the JDK forces it. Every byte read is written t[i] & 0xFF and a reviewer treats a missing mask as a defect rather than a style note. getBytes() with no argument is rejected outright because it uses the platform default charset. Hand-rolled binary search must compute the midpoint as (lo + hi) >>> 1, the unsigned shift the JDK itself shipped after its own binarySearch overflowed on arrays past 2^30, or the equivalent lo + ((hi - lo) >>> 1).
java
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public final class SuffixIndex {
    private final byte[] text;
    private final int[] sa;

    public SuffixIndex(String corpus) {
        this.text = corpus.getBytes(StandardCharsets.UTF_8);
        this.sa = build(this.text);
    }

    private static int[] build(byte[] t) {
        final int n = t.length;
        Integer[] order = new Integer[n];            // int[] takes no Comparator
        int[] rank = new int[n], nxt = new int[n];
        for (int i = 0; i < n; i++) {
            order[i] = i;
            rank[i] = t[i] & 0xFF;                  // byte is signed: unsign it
        }
        for (int k = 1; k < n; k <<= 1) {
            final int kk = k;
            final int[] r = rank;
            Arrays.sort(order, (a, b) -> {
                if (r[a] != r[b]) return Integer.compare(r[a], r[b]);
                int ra = a + kk < n ? r[a + kk] : -1;
                int rb = b + kk < n ? r[b + kk] : -1;
                return Integer.compare(ra, rb);
            });
            nxt[order[0]] = 0;
            for (int i = 1; i < n; i++) {
                int p = order[i - 1], c = order[i];
                int pk = p + kk < n ? r[p + kk] : -1;
                int ck = c + kk < n ? r[c + kk] : -1;
                nxt[c] = nxt[p] + ((r[p] == r[c] && pk == ck) ? 0 : 1);
            }
            System.arraycopy(nxt, 0, rank, 0, n);
            if (rank[order[n - 1]] == n - 1) break;
        }
        int[] out = new int[n];
        for (int i = 0; i < n; i++) out[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

byte is signed in Java and in none of the other seven languages here. A UTF-8 continuation or lead byte, 0x80 through 0xFF, reads as -128 through -1, so every suffix starting with a non-ASCII character sorts before every ASCII suffix. The array is still a valid permutation, the binary search still terminates, and English test corpora pass perfectly; the engine simply stops finding Chinese, Arabic and accented French. Mask with & 0xFF at every single read, including inside the comparator and the rank seed. Related: modern String.substring copies its char array rather than sharing it, so materialising suffixes is now quadratic in memory as well as in time.

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

Arrays.sort(int[]) is a tuned dual-pivot quicksort with no allocation, and you lose it the instant you need a comparator, because there is no comparator overload for primitive arrays. Boxing to Integer[] costs n allocations once at setup, in fact fewer than n because Integer.valueOf caches -128..127, plus a pointer dereference on both sides of every compare in every round, and the boxes outlive the sort, so escape analysis cannot eliminate them. TimSort over Integer[] also allocates an O(n) working array on each round, which Arrays.sort(int[]) does not. The comparator itself runs interpreted for the first several thousand invocations before C2 inlines it, so the early rounds are the slow ones. Compact strings back Latin-1 content with byte[], so getBytes(UTF_8) on ASCII is close to a straight copy. 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 Text Search Engine between languages.

Real-World Applications

Text Search Engine 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 Text Search Engine helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Text Search Engine 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 Text Search Engine 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 Text Search Engine 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 Text Search Engine?

No suffix array in the JDK. You get java.util.Arrays for sorting and binary search, String.getBytes(StandardCharsets.UTF_8) from java.nio.charset for the corpus bytes, java.text.BreakIterator for locale-aware word segmentation when you tokenize, java.text.Collator for linguistic term ordering, and java.util.regex for the scan fallback. Note that Arrays.binarySearch has no overload taking a comparator over int[], so the lower-bound search is yours to write. The ecosystem answer for anything ranked is Apache Lucene: org.apache.lucene.index.IndexWriter, DirectoryReader and IndexSearcher, with StandardAnalyzer doing the tokenization.

What is the most common Java mistake when implementing Text Search Engine?

byte is signed in Java and in none of the other seven languages here. A UTF-8 continuation or lead byte, 0x80 through 0xFF, reads as -128 through -1, so every suffix starting with a non-ASCII character sorts before every ASCII suffix. The array is still a valid permutation, the binary search still terminates, and English test corpora pass perfectly; the engine simply stops finding Chinese, Arabic and accented French. Mask with & 0xFF at every single read, including inside the comparator and the rank seed. Related: modern String.substring copies its char array rather than sharing it, so materialising suffixes is now quadratic in memory as well as in time.

How does Text Search Engine actually perform in Java?

Arrays.sort(int[]) is a tuned dual-pivot quicksort with no allocation, and you lose it the instant you need a comparator, because there is no comparator overload for primitive arrays. Boxing to Integer[] costs n allocations once at setup, in fact fewer than n because Integer.valueOf caches -128..127, plus a pointer dereference on both sides of every compare in every round, and the boxes outlive the sort, so escape analysis cannot eliminate them. TimSort over Integer[] also allocates an O(n) working array on each round, which Arrays.sort(int[]) does not. The comparator itself runs interpreted for the first several thousand invocations before C2 inlines it, so the early rounds are the slow ones. Compact strings back Latin-1 content with byte[], so getBytes(UTF_8) on ASCII is close to a straight copy. 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

If you are a student, see what GitHub Copilot offers students for free 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.