Skip to content

feat(strings): add suffix array algorithm - #15688

Open
hasnain607 wants to merge 5 commits into
TheAlgorithms:masterfrom
hasnain607:add-suffix-array
Open

hasnain607 wants to merge 5 commits into
TheAlgorithms:masterfrom
hasnain607:add-suffix-array

Conversation

@hasnain607

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Checklist

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues, then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label Nov 3, 2026
@hasnain607

Copy link
Copy Markdown
Author

@mindaugl , @cclauss please review my PR, I know you guys must be busy for taking so long at responding to open PRs

@cclauss

cclauss commented Nov 4, 2026

Copy link
Copy Markdown
Member

What is the advantage over suffix trees?

@hasnain607

Copy link
Copy Markdown
Author

What is the advantage over suffix trees?

Thanks for the review! The main advantages are memory and simplicity. A suffix array stores one integer per suffix, while a suffix tree needs up to 2n nodes, each holding child pointers

@hasnain607

hasnain607 commented Nov 6, 2026 •

Copy link
Copy Markdown
Author

@cclauss @darkstar , I am very sorry for pinging you guys, but I am very excited for my first contribution if you will look into my PR please, tell me if I am missing out on something. Thanks for your time

@richarddikembe-glitch

Copy link
Copy Markdown

add-suffix-array

Comment thread strings/suffix_array.py
>>> suffix_array("a")
[0]
>>> suffix_array("")
[]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness looks good: I compared this against the naive sorted(range(n), key=lambda i: text[i:]) on 3,000 random strings over small alphabets, including non-ASCII characters, with no mismatches. Could you add a doctest that does the same cross-check, e.g. >>> all(suffix_array(s) == sorted(range(len(s)), key=lambda i: s[i:]) over a few strings like "aaaa", "abab", "banana" and a longer string? That documents the invariant and protects future refactors.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added, using sorted(range(len(s)), key=lambda i: s[i:]) over "aaaa", "abab", "banana", "mississippi" and "abracadabra", so the invariant is documented in the doctests.

Comment thread strings/suffix_array.py Outdated
new_rank = [0] * n
for position in range(1, n):
previous, current = suffixes[position - 1], suffixes[position]
previous_key = (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The (rank[i], rank[i + k] or -1) pair is built here for previous and current, and again on line 52 for every suffix. Since keys is already sorted in the same order as suffixes, you can compare the first two entries of neighbouring keys instead, which removes lines 61 to 68 and the duplicated -1 handling:

    new_rank = [0] * n
    for position in range(1, n):
        previous, current = suffixes[position - 1], suffixes[position]
        same_prefix = keys[position - 1][:2] == keys[position][:2]
        new_rank[current] = new_rank[previous] + int(not same_prefix)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied. The renumbering loop now compares keys[position - 1][:2] with keys[position][:2], so the per-suffix pair rebuilding and the duplicated -1 handling are gone.

Comment thread strings/suffix_array.py

Construction here uses prefix doubling (Manber-Myers).

Time Complexity: O(n log² n) - where n is the length of the text

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This answers cclauss's question well. Since the advantage over suffix trees is memory and simplicity, please say plainly that construction here is slower than the O(n) approaches (Ukkonen for suffix trees, SA-IS for suffix arrays). Also, "a node per character" (lines 6 to 7) is slightly loose: a suffix tree has up to 2n nodes, so "up to 2n nodes" is more precise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both are in the module docstring now: "up to 2n nodes" for suffix trees, and an explicit sentence that prefix doubling is O(n log² n) versus the O(n) constructions (Ukkonen, SA-IS).

Comment thread strings/suffix_array.py
# pair (rank of the first k, rank of the next k). A second half that
# runs past the end gets -1: ranks are never negative, so a shorter
# suffix sorts before a longer one that shares its prefix.
keys = [(rank[i], rank[i + k] if i + k < n else -1, i) for i in range(n)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: the third tuple element i is only a tie-breaker, and the renumbering step makes tied entries share a rank. A short comment saying so would save readers a moment.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a comment noting the index only makes the sort deterministic and that tied suffixes share a rank in the renumbering step.

Comment thread strings/suffix_array.py
break
k *= 2

return suffixes

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: most files in this repo end with an if __name__ == "__main__": import doctest; doctest.testmod() block so contributors can run the doctests directly. CI runs them anyway, so this only helps local runs.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the if __name__ == "__main__": block with doctest.testmod().

@jgohel9902 jgohel9902 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution. I compared the implementation against a naive sorted(range(n), key=lambda i: text[i:]) on a few thousand random strings, including non-ASCII ones, and found no mismatches. The prefix-doubling logic and the early exit are correct and well commented. My suggestions are small: add a cross-check doctest against the naive version, reuse the already sorted keys instead of rebuilding them in the renumbering loop, and state that construction is slower than the O(n) suffix-tree and SA-IS approaches. Nothing here blocks the PR.

@jgohel9902 jgohel9902 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

- add a doctest cross-checking the result against a naive sort
- compare neighbouring sorted keys when renumbering instead of rebuilding
  the rank pairs
- document the node bound against suffix trees and the O(n log^2 n) cost
  against linear-time constructions
- explain the tie-breaking index
- run the doctests under __main__
@hasnain607

Copy link
Copy Markdown
Author

All five review points are addressed in 4bd43e4:

  • new doctest cross-checks the output against sorted(range(len(s)), key=lambda i: s[i:]) for "aaaa", "abab", "banana", "mississippi" and "abracadabra"
  • renumbering compares keys[position - 1][:2] with keys[position][:2], so the per-suffix pair rebuild and the duplicated -1 handling are gone
  • module docstring says "up to 2n nodes" and states that prefix doubling is O(n log² n) against O(n) for Ukkonen/SA-IS
  • the tie-breaking index is documented
  • the if __name__ == "__main__": doctest block is added

Local verification: doctests pass, 4,000 random strings (including non-ASCII and spaces) match the naive sort with zero mismatches, ruff check and ruff format --check are clean, and all six checks are green on the new commit.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants