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

Suffix Array Implementation in JavaScript

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 JavaScript as in every other language.
  • ✓The platform has no suffix array. You build on Int32Array for the sa/rank/tmp buffers, String.prototype.charCodeAt for UTF-16 code units or new TextEncoder().encode(s) for a Uint8Array of UTF-8 bytes, and %TypedArray%.prototype.sort(comparator).
  • ✓A reviewer wants typed arrays, not []: a plain array of indices drifts to HOLEY_ELEMENTS after one sparse write and loses the fast path forever.
  • ✓The JavaScript trap: sort() with no comparator on a plain Array sorts by the STRING form of each element, so index 10 lands before index 9 and you get a decimal-lexicographic permutation that still passes every is-this-a-permutation check.
  • ✓V8 keeps small integers as Smis, so an Int32Array read is a load plus a bounds check; a plain Array that has gone holey costs a prototype-chain miss on every read.

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 JavaScript: what you actually reach for

The platform has no suffix array. You build on Int32Array for the sa/rank/tmp buffers, String.prototype.charCodeAt for UTF-16 code units or new TextEncoder().encode(s) for a Uint8Array of UTF-8 bytes, and %TypedArray%.prototype.sort(comparator). Array.prototype.sort has been spec-required stable since ES2019; %TypedArray%.prototype.sort defaults to NUMERIC ascending, unlike Array's default. npm has no dominant suffix-array package, so the doubling loop is normally hand-written and a WASM build of libdivsufsort is the escape hatch for large corpora.

JavaScript implementation

A reviewer wants typed arrays, not []: a plain array of indices drifts to HOLEY_ELEMENTS after one sparse write and loses the fast path forever. The comparator must return a Number - returning `a < b`, a boolean, is the single most-flagged line in this algorithm. localeCompare is rejected because ICU collation is not code-unit order. And they want the comparator hoisted out of the sort call so the engine sees one call site rather than a fresh closure per round.
javascript
function suffixArray(str) {
  const n = str.length;
  const sa = new Int32Array(n);
  let rank = new Int32Array(n);
  let tmp = new Int32Array(n);
  for (let i = 0; i < n; i++) { sa[i] = i; rank[i] = str.charCodeAt(i); }

  // ONE comparator for the whole build, hoisted above the loop so the sort sees a
  // single call site. Explicit numeric result -- never the default, never a boolean.
  let k = 1;
  const cmp = (a, b) =>
    rank[a] !== rank[b]
      ? rank[a] - rank[b]
      : (a + k < n ? rank[a + k] : -1) - (b + k < n ? rank[b + k] : -1);

  for (; k < n; k <<= 1) {
    sa.sort(cmp);
    tmp[sa[0]] = 0;
    for (let i = 1; i < n; i++) {
      tmp[sa[i]] = tmp[sa[i - 1]] + (cmp(sa[i - 1], sa[i]) < 0 ? 1 : 0);
    }
    [rank, tmp] = [tmp, rank];
    if (rank[sa[n - 1]] === n - 1) break;
  }
  return sa;
}

suffixArray('banana');   // Int32Array(6) [5, 3, 1, 0, 4, 2]

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 JavaScript-specific trap

sort() with no comparator on a plain Array sorts by the STRING form of each element, so index 10 lands before index 9 and you get a decimal-lexicographic permutation that still passes every is-this-a-permutation check. Nothing throws. The trap is doubled because Int32Array.prototype.sort() with no comparator IS numeric, so the bug vanishes the moment someone changes the container type and comes back when a later refactor turns it into a plain array again. Always pass an explicit (a, b) => number, and never return a boolean from it: false coerces to 0, which the sort reads as 'these two are equal'.

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

V8 keeps small integers as Smis, so an Int32Array read is a load plus a bounds check; a plain Array that has gone holey costs a prototype-chain miss on every read. The comparator is a JS call per comparison, on the order of n log n of them - keep it monomorphic, one arity and one argument shape, or the sort site goes megamorphic and inlining stops. charCodeAt on a cons or sliced string flattens it once; do that flatten deliberately up front. Reuse two Int32Arrays and swap them instead of allocating a rank array per round, which churns the young generation. 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 JavaScript, 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 JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

Frequently Asked Questions

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

The platform has no suffix array. You build on Int32Array for the sa/rank/tmp buffers, String.prototype.charCodeAt for UTF-16 code units or new TextEncoder().encode(s) for a Uint8Array of UTF-8 bytes, and %TypedArray%.prototype.sort(comparator). Array.prototype.sort has been spec-required stable since ES2019; %TypedArray%.prototype.sort defaults to NUMERIC ascending, unlike Array's default. npm has no dominant suffix-array package, so the doubling loop is normally hand-written and a WASM build of libdivsufsort is the escape hatch for large corpora.

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

sort() with no comparator on a plain Array sorts by the STRING form of each element, so index 10 lands before index 9 and you get a decimal-lexicographic permutation that still passes every is-this-a-permutation check. Nothing throws. The trap is doubled because Int32Array.prototype.sort() with no comparator IS numeric, so the bug vanishes the moment someone changes the container type and comes back when a later refactor turns it into a plain array again. Always pass an explicit (a, b) => number, and never return a boolean from it: false coerces to 0, which the sort reads as 'these two are equal'.

How does Suffix Array actually perform in JavaScript?

V8 keeps small integers as Smis, so an Int32Array read is a load plus a bounds check; a plain Array that has gone holey costs a prototype-chain miss on every read. The comparator is a JS call per comparison, on the order of n log n of them - keep it monomorphic, one arity and one argument shape, or the sort site goes megamorphic and inlining stops. charCodeAt on a cons or sliced string flattens it once; do that flatten deliberately up front. Reuse two Int32Arrays and swap them instead of allocating a rank array per round, which churns the young generation. 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 Devin 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.