HomeLeetcode14. Longest Common Prefix - Leetcode Solutions

14. Longest Common Prefix – Leetcode Solutions

Description:

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Examples:

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Solution in Python:

Steps to Solve the Problem:

  1. Check for Empty Input:
    • If the input list strs is empty, return an empty string.
  2. Initialize the Prefix:
    • Assume the first string is the common prefix initially.
  3. Compare the Prefix with Each String:
    • Iterate through the rest of the strings in the list.
    • For each string, compare characters one by one with the current prefix.
    • If a character doesn’t match, reduce the prefix length accordingly.
    • Stop comparing when the prefix becomes empty or we reach the end of the string.
  4. Return the Result:
    • Return the common prefix after comparing all strings.
Python
from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        # If the list is empty, return an empty string
        if not strs:
            return ""
        
        # Assume the first string is the common prefix
        prefix = strs[0]
        
        # Compare the prefix with each string in the list
        for s in strs[1:]:
            # Find the minimum length between the prefix and the current string
            min_length = min(len(prefix), len(s))
            
            # Initialize a new prefix to build
            new_prefix = ""
            
            # Compare characters one by one
            for i in range(min_length):
                if prefix[i] == s[i]:
                    new_prefix += prefix[i]
                else:
                    break
            
            # Update the prefix
            prefix = new_prefix
            
            # If at any point the prefix is empty, return immediately
            if not prefix:
                return ""
        
        return prefix

Explanation of the Code:

  1. Check for Empty Input:
    • The condition if not strs: checks if the input list is empty and returns an empty string if true.
  2. Initialize the Prefix:
    • The variable prefix is initialized to the first string in the list strs[0].
  3. Compare the Prefix with Each String:
    • The for s in strs[1:]: loop iterates through each string in the list starting from the second string.
    • Inside the loop, min_length is the minimum length between the current prefix and the current string to avoid index out of range errors.
    • The new_prefix is initialized as an empty string to build the new common prefix character by character.
    • The inner for i in range(min_length): loop compares each character of the prefix with the current string. If they match, the character is added to new_prefix. If they don’t match, the loop breaks.
  4. Update and Check the Prefix:
    • After comparing characters, prefix is updated to new_prefix.
    • If prefix becomes empty at any point (if not prefix:), return an empty string immediately.
  5. Return the Result:
    • After the loop finishes, prefix contains the longest common prefix, which is returned.

This method ensures we handle the longest common prefix efficiently by comparing characters of the strings iteratively and updating the prefix accordingly.

Solution in Javascript:

JavaScript
/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    // If the list is empty, return an empty string
    if (!strs.length) {
        return "";
    }

    // Assume the first string is the common prefix
    let prefix = strs[0];

    // Compare the prefix with each string in the list
    for (let i = 1; i < strs.length; i++) {
        let currentString = strs[i];
        let j = 0;
        
        // Compare characters one by one
        while (j < prefix.length && j < currentString.length && prefix[j] === currentString[j]) {
            j++;
        }

        // Update the prefix to the common part
        prefix = prefix.substring(0, j);

        // If at any point the prefix is empty, return immediately
        if (prefix === "") {
            return "";
        }
    }

    return prefix;
};

Solution in Java:

Java
class Solution {
    public String longestCommonPrefix(String[] strs) {
        // If the array is empty, return an empty string
        if (strs == null || strs.length == 0) {
            return "";
        }

        // Assume the first string is the common prefix
        String prefix = strs[0];

        // Compare the prefix with each string in the array
        for (int i = 1; i < strs.length; i++) {
            String currentString = strs[i];
            int j = 0;

            // Compare characters one by one
            while (j < prefix.length() && j < currentString.length() && prefix.charAt(j) == currentString.charAt(j)) {
                j++;
            }

            // Update the prefix to the common part
            prefix = prefix.substring(0, j);

            // If at any point the prefix is empty, return immediately
            if (prefix.isEmpty()) {
                return "";
            }
        }

        return prefix;
    }
}

Solution in C#:

C#
public class Solution {
    public string LongestCommonPrefix(string[] strs) {
        // If the array is null or empty, return an empty string
        if (strs == null || strs.Length == 0) {
            return "";
        }

        // Assume the first string is the common prefix
        string prefix = strs[0];

        // Compare the prefix with each string in the array
        for (int i = 1; i < strs.Length; i++) {
            string currentString = strs[i];
            int j = 0;

            // Compare characters one by one
            while (j < prefix.Length && j < currentString.Length && prefix[j] == currentString[j]) {
                j++;
            }

            // Update the prefix to the common part
            prefix = prefix.Substring(0, j);

            // If at any point the prefix is empty, return immediately
            if (string.IsNullOrEmpty(prefix)) {
                return "";
            }
        }

        return prefix;
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular