KatInterview

14. Longest Common Prefix

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Vertical Scanning

This approach is intuitive and efficient. Instead of comparing strings with each other (horizontal scanning), we compare characters column by column.

Solution

Longest Common Prefix in Python

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        # According to constraints, `strs` will have at least one element.
        # If strs is empty, this would raise an IndexError. But constraints prevent that.

        # Iterate through the characters of the first string using an index.
        for i in range(len(strs[0])):
            char_to_match = strs[0][i]

            # Check this character against all other strings.
            for s in strs[1:]:
                # Two conditions for mismatch:
                # 1. The current string `s` is shorter than the prefix we are checking.
                # 2. The character at index `i` in `s` does not match.
                if i >= len(s) or s[i] != char_to_match:
                    # Mismatch found. The prefix is up to the character before this one.
                    return strs[0][:i]
        
        # If the loop completes, the entire first string is the common prefix.
        return strs[0]

Longest Common Prefix in Java

class Solution {
    public String longestCommonPrefix(String[] strs) {
        // According to constraints, `strs` will have at least one element,
        // so `strs[0]` is safe to access.

        // Iterate through the characters of the first string (vertical scanning).
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);
            
            // Check if this character is common to all other strings at this position.
            for (int j = 1; j < strs.length; j++) {
                // Two conditions to end the common prefix:
                // 1. The current string `strs[j]` is shorter than the prefix we are checking (i.e., index `i` is out of bounds).
                // 2. The character at index `i` in `strs[j]` doesn't match `c`.
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    // The common prefix is the part of the first string before index `i`.
                    return strs[0].substring(0, i);
                }
            }
        }

        // If the outer loop finishes, the entire first string is the common prefix.
        return strs[0];
    }
}

Longest Common Prefix in C++

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        // According to constraints, `strs` will have at least one element,
        // so `strs[0]` is safe to access.

        // Iterate through the characters of the first string (vertical scanning).
        for (int i = 0; i < strs[0].length(); ++i) {
            char c = strs[0][i];

            // Check this character against all other strings.
            for (int j = 1; j < strs.size(); ++j) {
                // Two conditions for mismatch:
                // 1. The current string `strs[j]` is shorter than the prefix we are checking (i.e., index `i` is out of bounds).
                // 2. The character at index `i` in `strs[j]` does not match `c`.
                if (i >= strs[j].length() || strs[j][i] != c) {
                    // Mismatch found. The prefix is the substring of strs[0] from the start up to index `i`.
                    return strs[0].substr(0, i);
                }
            }
        }

        // If the outer loop completes, it means the entire first string is a common prefix.
        return strs[0];
    }
};

Longest Common Prefix in TypeScript

function longestCommonPrefix(strs: string[]): string {
    // According to constraints, `strs` will have at least one element,
    // so `strs[0]` is safe to access.

    // Iterate through the characters of the first string (vertical scanning).
    for (let i = 0; i < strs[0].length; i++) {
        const char = strs[0][i];
        
        // Check this character against all other strings.
        for (let j = 1; j < strs.length; j++) {
            // Two conditions for mismatch:
            // 1. The current string `strs[j]` is shorter than the prefix being checked.
            // 2. The character at position `i` does not match.
            if (i >= strs[j].length || strs[j][i] !== char) {
                // Found the end of the common prefix. Return the prefix found so far.
                return strs[0].substring(0, i);
            }
        }
    }

    // If the loop completes, the entire first string is the common prefix.
    return strs[0];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.