Open In App

Longest Common Prefix using Character by Character Matching

Last Updated : 14 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "".

Examples:

Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]
Output: "gee"
Explanation: “gee” is the longest common prefix in all the given strings: "geeksforgeeks", "geeks", "geeks" and "geezer".

Input: arr[] = ["apple", "ape", "april"]
Output : "ap"
Explanation: “ap” is the longest common prefix in all the given strings: "apple", "ape" and "april".

Input: arr[] = [“hello”, “world”]
Output: ""
Explanation: There’s no common prefix in the given strings.

Approach:

This approach is similar to the approach discussed in the article Longest Common Prefix using Word by Word Matching. But, instead of going through the strings one by one, we will go through the characters one by one. 

Character-by-character matching works faster than word-by-word matching. As we immediately stops the matching when a mismatch is found. It is efficient, especially when there’s a short or no common prefix. On the other hand, word-by-word matching goes through each word entirely, even if there’s no common prefix at all.


C++
// C++ program to find the longest common prefix
// using Character by Character Matching

#include <iostream>
#include <vector>
using namespace std;

// Function to find the longest common prefix
// from the set of strings
string longestCommonPrefix(vector<string>& arr) {
  
  	// Find length of smallest string
    int minLen = arr[0].length();

    for(string &str: arr)
        minLen = min(minLen, (int)str.size());

    string res;
    for (int i = 0; i < minLen; i++) {
      
        // Current character (must be the same
        // in all strings to be a part of result)
        char ch = arr[0][i];

        for (string &str: arr) {
            if (str[i] != ch)    
                return res;
        }

        // Append to result
        res.push_back(ch);
    }
  	
    return res;
}

int main() {
    vector<string> arr = {"geeksforgeeks", "geeks", 
                          			"geek", "geezer"};
    cout << longestCommonPrefix(arr);
    return 0;
}
Java
// Java program to find the longest common prefix
// using Character by Character Matching

import java.util.*;

class GfG {

    // Function to find the longest common prefix
    // from the set of strings
    static String longestCommonPrefix(String[] arr) {
      
      	// Find length of smallest string
        int minLen = arr[0].length();

        for (String str : arr)
            minLen = Math.min(minLen, str.length());

        StringBuilder res = new StringBuilder();

        for (int i = 0; i < minLen; i++) {

            // Current character (must be the same
            // in all strings to be a part of result)
            char ch = arr[0].charAt(i);

            for (String str : arr) {
                if (str.charAt(i) != ch) {
                    return res.toString();
                }
            }

            // Append to result
            res.append(ch);
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String[] arr = {"geeksforgeeks", "geeks", "geek", "geezer"};
        System.out.println(longestCommonPrefix(arr));
    }
}
Python
# Python program to find the longest common prefix
# using Character by Character Matching

# Function to find the longest common prefix
# from the list of strings
def longestCommonPrefix(arr):
  
  	# Find length of smallest string
    minLen = len(arr[0])

    for s in arr:
        minLen = min(minLen, len(s))

    res = []
    for i in range(minLen):

        # Current character (must be the same
        # in all strings to be a part of result)
        ch = arr[0][i]

        for s in arr:
            if s[i] != ch:
                return "".join(res)

        # Append to result
        res.append(ch)

    return "".join(res)

if __name__ == "__main__":
    arr = ["geeksforgeeks", "geeks", "geek", "geezer"]
    print(longestCommonPrefix(arr))
C#
// C# program to find the longest common prefix
// using Character by Character Matching

using System;
class GfG {
  
    // Function to find the longest common prefix
    // from the array of strings
    static string longestCommonPrefix(string[] arr) {
      
      	// Find length of smallest string
        int minLen = arr[0].Length;

        foreach (string str in arr)
            minLen = Math.Min(minLen, str.Length);

        string res = "";

        for (int i = 0; i < minLen; i++) {

            // Current character (must be the same
            // in all strings to be a part of result)
            char ch = arr[0][i];

            foreach (string str in arr) {
                if (str[i] != ch) {
                    return res;
                }
            }

            // Append to result
            res += ch;
        }
        return res;
    }

    static void Main() {
        string[] arr = { "geeksforgeeks", "geeks", 
                        		"geek", "geezer" };
      
        Console.WriteLine(longestCommonPrefix(arr));
    }
}
JavaScript
// JavaScript program to find the longest common prefix
// using Character by Character Matching

// Function to find the longest common prefix
// from the array of strings
function longestCommonPrefix(arr) {

	// Find length of smallest string
    let minLen = arr[0].length;

    for (let str of arr)
        minLen = Math.min(minLen, str.length);

    let res = [];

    for (let i = 0; i < minLen; i++) {

        // Current character (must be the same
        // in all strings to be a part of result)
        const ch = arr[0][i];

        for (let str of arr) {
            if (str[i] !== ch) {
                return res.join("");
            }
        }

        // Append to result
        res.push(ch);
    }
    return res.join("");
}

// Driver code
const arr = ["geeksforgeeks", "geeks", 
						"geek", "geezer"];
console.log(longestCommonPrefix(arr));

Output
gee

Time Complexity: O(n*m), where n is number of strings and m is length of the shortest string.
Auxiliary Space: O(m), to store the longest prefix string.

Related Articles

 


Next Article
Article Tags :
Practice Tags :

Similar Reads