Skip to content

feat(strings): add longest common prefix algorithm - #15574

Open
len1227 wants to merge 1 commit into
TheAlgorithms:masterfrom
len1227:add-longest-common-prefix
Open

len1227 wants to merge 1 commit into
TheAlgorithms:masterfrom
len1227:add-longest-common-prefix

Conversation

@len1227

@len1227 len1227 commented Oct 14, 2026

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests?
  • 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".

What this adds

strings/longest_common_prefix.py — the longest common prefix (LCP) algorithm.

Given a list of strings it returns the longest string that is a prefix of every
element of the list. The list is sorted first and only the lexicographically
smallest and largest string are compared; any prefix shared by the whole list
must also be a prefix of both of those extremes, so no other pair needs to be
examined.

>>> longest_common_prefix(["flower", "flow", "flight"])
'fl'
>>> longest_common_prefix(["dog", "racecar", "car"])
''

The doctests cover empty input, single-element input, strings that diverge at
the first character, and a ValueError raised for a non-string element.

Reference: https://en.wikipedia.org/wiki/Longest_common_prefix

@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label Oct 14, 2026

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.

2 participants