JavaScript Program to Find Longest Common Prefix Using Word by Word Matching

Prefixes are substrings that start from the zeroth index of a string and can be of any size from 1 to the complete length of the string. We are given a set of strings and need to find the longest common prefix among all of them using JavaScript. We'll implement word-by-word matching approach where we compare characters at the same position across all strings.

Input

arr = ["zefkefgh", "zefkdefij", "zeffdzy", "zefkdabacd"];

Output

zef

Explanation

From all the given strings, the first three characters "zef" are the same across all strings, while the remaining characters differ.

Input

arr = ["zefkefgh", "bcdefij", "acdzy", "abzefkacd"]

Output

""

Explanation

In the given strings, none of them share a common prefix starting from the first character, so we return an empty string.

Method 1: Comparing All Strings

This approach takes the first string as the initial prefix and compares it with all remaining strings, progressively reducing the prefix until we find the longest common one.

Example

// Function to find the longest common prefix between two strings
function commonPrefix(str1, str2) {
    let result = "";
    let len1 = str1.length;
    let len2 = str2.length;
    
    // Compare characters until they differ or we reach end of shorter string
    let i = 0;
    while (i  0) {
    console.log("The longest common prefix is: " + result);
} else {
    console.log("There is no common prefix among the given strings");
}
The longest common prefix is: zef

Method 2: Word-by-Word (Character-by-Character) Matching

In this approach, we traverse character positions and check if all strings have the same character at each position. We stop when we find a mismatch or reach the end of any string.

Example

// Function using character-by-character comparison
function findLongestCommonPrefixWordByWord(arr) {
    if (arr.length === 0) return "";
    
    let result = "";
    
    // Iterate through each character position
    for (let i = 0; i = arr[j].length || arr[j][i] !== currentChar) {
                isCommon = false;
                break;
            }
        }
        
        if (isCommon) {
            result += currentChar;
        } else {
            break;
        }
    }
    
    return result;
}

// Test the function
let arr2 = ["zefkefgh", "zefkdefij", "zeffdzy", "zefkdabacd"];
let result2 = findLongestCommonPrefixWordByWord(arr2);

if (result2.length > 0) {
    console.log("The longest common prefix is: " + result2);
} else {
    console.log("There is no common prefix among the given strings");
}

// Test with no common prefix
let arr3 = ["abc", "def", "ghi"];
let result3 = findLongestCommonPrefixWordByWord(arr3);
console.log("No common prefix example: '" + result3 + "'");
The longest common prefix is: zef
No common prefix example: ''

Comparison of Methods

Method Approach Time Complexity Space Complexity
String Comparison Compare first string with others O(N × M) O(M)
Character-by-Character Compare characters at each position O(N × M) O(M)

Where N is the number of strings and M is the length of the longest string.

Key Points

  • Both methods have the same time and space complexity
  • The character-by-character method can stop early when a mismatch is found
  • Handle edge cases like empty arrays or strings with no common prefix
  • The algorithm stops as soon as no common character is found at any position

Conclusion

We implemented two approaches to find the longest common prefix: string comparison and character-by-character matching. Both methods efficiently solve the problem with O(N × M) time complexity, making them suitable for finding common prefixes in string arrays.

Updated on: 2026-03-15T23:19:01+05:30

425 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements