DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk2 min

Longest Common Prefix: A Simple Python Solution

Compare each string at matching positions and stop at the first mismatch or string ending. Here is a concise Python solution and its complexity.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Compare the strings one character position at a time, from left to right. The first mismatch—or the first string that runs out—ends the shared prefix. If that happens at position zero, return "".

What counts as a common prefix?

A prefix is a sequence of characters at the beginning of a string. Every input string must share it from position zero; a matching sequence found later in a string does not count. For example, ["flower", "flow", "flight"] has the longest common prefix "fl". For ["dog", "racecar", "car"], no prefix is shared, so the result is "". LeetCode’s problem statement allows 1 to 200 strings, each 0 to 200 characters long; non-empty strings contain lowercase English letters.

As an Amazon Associate I earn from qualifying purchases.

Compare characters by position

Use the first string as the reference and scan it from left to right. At each position, check that every other string has a character there and that it matches the reference. Return the reference string up to—but not including—the first position that fails.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Start with the first string as the reference.
  2. For each character position in that string, compare the character with the character at the same position in every other string.
  3. If a string has ended or a character differs, return the reference string before that position.
  4. If every position in the reference matches, return the entire reference string.

In Python:

def longest_common_prefix(strs: list[str]) -> str:
    first = strs[0]
    for i, char in enumerate(first):
        for word in strs[1:]:
            if i == len(word) or word[i] != char:
                return first[:i]
    return first

The length check must come before word[i]; otherwise, indexing a shorter string can raise an error. The input constraints guarantee at least one string, so strs[0] exists. If the first string is empty, the loop does not run and the function returns "". If a later string is empty, the first comparison returns "".

Why the first failure is the stopping point

A prefix has to match continuously from the beginning. Once a position differs—or one string has no character at that position—no later characters can make the preceding sequence a longer shared prefix. The function therefore returns immediately rather than checking later positions.

Time and space complexity

Let n be the number of strings and m the length of the shortest string. The character-comparison method takes O(n × m) time in the cited analysis, since it may compare up to m positions across the strings. It uses O(1) auxiliary space for its algorithm state. Creating the returned prefix with a Python slice may allocate the output string; that output is not counted as auxiliary state in this analysis. Doocs’ solution explanation gives this complexity for the comparison approach.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When to use a different approach

A trie is another possible way to represent shared prefixes, but the direct scan is easier to follow for the problem’s stated limits. The cited solution discusses a trie as an alternative but gives no measured runtime comparison, so there is no basis here to claim it is faster. For this task, the position-by-position scan provides a short implementation and a clear stopping condition.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.