LeetCode Challenge: 14. Longest Common Prefix – JavaScript Solution 🚀
December 23, 2024

LeetCode Challenge: 14. Longest Common Prefix – JavaScript Solution 🚀

Popular interviews 150

The longest common prefix problem is a classic string manipulation challenge that tests your ability to identify shared patterns between strings. Let’s break it down LeetCode 14: Longest common prefix And solve it with JavaScript.


🚀 Problem description

Given an array of strings strsreturns the longest common prefix among all strings in the array.

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


💡 Example

Example 1

Input: strs = ["flower","flow","flight"]  
Output: "fl"  
Explanation: The first two letters "fl" are common to all strings.
Enter full screen mode

Exit full screen mode

Example 2

Input: strs = ["dog","racecar","car"]  
Output: ""  
Explanation: No common prefix exists among the input strings.
Enter full screen mode

Exit full screen mode


🏆 JavaScript solution

We will use a horizontal scan method to iteratively compare the prefix of one string to the next string to update the common prefix.

implement

var longestCommonPrefix = function(strs) {
    if (!strs.length) return "";

    let prefix = strs[0];
    for (let i = 1; i < strs.length; i++) {
        while (strs[i].indexOf(prefix) !== 0) {
            prefix = prefix.slice(0, -1);
            if (prefix === "") return "";
        }
    }

    return prefix;
};
Enter full screen mode

Exit full screen mode


🔍 How it works

  1. Starting from the first string:

    • Use the first string as the initial prefix.
  2. Iterate over a string:

    • Compares the current prefix to each string.
    • If the prefix does not match the beginning of the string, shorten the prefix by removing the last character until it matches.
  3. Return prefix:

    • After all strings have been checked, the remaining prefix is ​​the longest common prefix.

🔑 Complexity analysis

  • > Time complexity: O(S)Where S is the sum of all characters in the array.
    • In the worst case, every character in the array will be compared.
  • > Space complexity: O(1)because no additional data structures are used.

📋 Run on empty

enter: strs = ["flower", "flow", "flight"]


Output: "fl"


Alternative Solution: Vertical Scan

Instead of comparing strings individually, you can compare characters at every index in all strings.

var longestCommonPrefix = function(strs) {
    if (!strs.length) return "";

    for (let i = 0; i < strs[0].length; i++) {
        const char = strs[0][i];

        for (let j = 1; j < strs.length; j++) {
            if (i >= strs[j].length || strs[j][i] !== char) {
                return strs[0].slice(0, i);
            }
        }
    }

    return strs[0];
};
Enter full screen mode

Exit full screen mode


🔑 Complexity analysis (vertical scan)

  • > Time complexity: O(S)the same as horizontal scan.
  • > Space complexity: O(1).

✨ Professional tips for interviews

  1. Clarify constraints: Confirm whether the array can be empty or contain strings of different lengths.
  2. Discuss edge cases:
    • empty string array ([]"").
    • Single string input (["single"]"single").
    • Strings without common prefix (["dog", "cat"]"").
  3. Explain your chosen method: Highlight the difference between horizontal and vertical scanning.

📚 Learn more

Check out the full explanation and code walkthrough on my Dev.to post:
👉 length of last word – JavaScript solution

What is your solution to this problem? Let’s discuss it! 🚀

2024-12-23 11:59:51

Leave a Reply

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