Longest Common Prefix (original) (raw)

Given an array of strings arr[], 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 “”.

**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.

Table of Content

[Naive Approach] Using Sorting - O(n*m*log n)Time O(m)Space

The idea is to sort the array of strings and find the common prefix of the first and last string of the sorted array. Sorting is used in this approach because it makes it easier to find the longest common prefix. When we sort the strings, the first and last strings in the sorted list will be the most different from each other in terms of their characters. So, the longest common prefix for all the strings must be a prefix of both the first and the last strings in the sorted list.

**Algorithm:

// C++ program to find the longest common prefix // using Sorting #include #include #include using namespace std;

// Function to find the longest common prefix string longestCommonPrefix(vector& arr) {

// Sort the vector of strings
sort(arr.begin(), arr.end());

// Compare the first and last strings
// in the sorted list
string first = arr.front();
string last = arr.back();
int minLength = min(first.size(), last.size());

int i = 0;

// Find the common prefix between the first
// and last strings
while (i < minLength && first[i] == last[i]) {
    i++;
}

// Return the common prefix
return first.substr(0, i);

}

int main() { vector arr = {"geeksforgeeks", "geeks", "geek", "geezer"}; cout << longestCommonPrefix(arr) << endl;

return 0;

}

Java

// Java program to find the longest common prefix // using Sorting import java.util.Arrays; class GfG {

static String longestCommonPrefix(String[] arr){
  
    // Sort the array of strings
    Arrays.sort(arr);

    // Get the first and last strings after sorting
    String first = arr[0];
    String last = arr[arr.length - 1];
    int minLength = Math.min(first.length(), 
                                 last.length());
    
    // Find the common prefix between the first 
      // and last strings
      int i = 0;
    while (i < minLength && 
           first.charAt(i) == last.charAt(i)) {
        i++;
    }

    // Return the common prefix
    return first.substring(0, i);
}

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 Sorting

def longestCommonPrefix(arr):

# Sort the list of strings
arr.sort()

# Get the first and last strings after sorting
first = arr[0]
last = arr[-1]
minLength = min(len(first), len(last))

i = 0
# Find the common prefix between the first
# and last strings
while i < minLength and first[i] == last[i]:
    i += 1

# Return the common prefix
return first[:i]

if name == "main": arr = ["geeksforgeeks", "geeks", "geek", "geezer"] print( longestCommonPrefix(arr))

C#

// C# program to find the longest common prefix // using Sorting using System;

class GfG { static string LongestCommonPrefix(string[] arr){

    // Sort the array of strings
    Array.Sort(arr);

    // Get the first and last strings after sorting
    string first = arr[0];
    string last = arr[arr.Length - 1];
    int minLength = Math.Min(first.Length, 
                                     last.Length);

    int i = 0;
    // Find the common prefix between the first and 
      // last strings
    while (i < minLength && first[i] == last[i]) {
        i++;
    }

    // Return the common prefix
    return first.Substring(0, i);
}

static void Main(){
    string[] arr = { "geeksforgeeks", "geeks", "geek",
                      "geezer" };
    Console.WriteLine(LongestCommonPrefix(arr));
}

}

JavaScript

// JavaScript program to find the longest common prefix // using Sorting

function longestCommonPrefix(arr){

// Sort the array of strings
arr.sort();

// Get the first and last strings after sorting
let first = arr[0];
let last = arr[arr.length - 1];
let minLength = Math.min(first.length, last.length);

let i = 0;

// Find the common prefix between the first and 
// last strings
while (i < minLength && first[i] === last[i]) {
    i++;
}

// Return the common prefix
return first.substring(0, i);

}

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

`

Time Complexity: O(n*m*log n), to sort the array, where n is the number of strings and m is the length of longest string.
Auxiliary Space: O(m) to store the strings first, last and result.

[Expected Approach 1] Character by Character Matching - O(n * m) Time and O(m) Space

The idea is to iterate character by character from index 0 and take the current character from the first string as reference. For each position, we compare this character with the corresponding character in all other strings. If all characters match, we add it to the result; otherwise, we stop immediately and return the prefix formed so far.

**Algorithm:

// using Character by Character Matching

#include #include using namespace std;

// Function to find the longest common prefix // from the set of strings string longestCommonPrefix(vector& 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 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));

`

[Expected Approach 2] Using Divide and Conquer Algorithm - O(n*m) Time O(m) Space

The idea is simple, first divide the array of strings into two equal parts. Then find the **Longest Common Prefix for all strings in each part individually using recursion. Once we got the **Longest Common Prefix of both parts, the **Longest Common Prefix of this array will be **Longest Common Prefix of these two parts.

Algorithm:

longest_common_prefix_using_divide_and_conquer_algorithm

C++ `

// C++ program to find the longest common prefix // using Divide and Conquer Algorithm

#include #include using namespace std;

// A Utility Function to find the common prefix between // strings s1 and s2 string commonPrefixUtil(string &s1, string &s2) { string res; int n1 = s1.length(), n2 = s2.length();

for (int i = 0; i < n1 && i < n2; i++) {
    if (s1[i] != s2[i])
        break;
    res.push_back(s1[i]);
}

return res;

}

// A Divide and Conquer based function to find the // longest common prefix. This is similar to the // merge sort technique string commonPrefix(vector &arr, int l, int r) {

// Base Case: common prefix for a single string is
// the string itself
if (l == r)
    return arr[l];

if (l < r) {
    int mid = l + (r - l) / 2;

    // Find Longest Common Prefix of first part
    string p1 = commonPrefix(arr, l, mid);

    // Find Longest Common Prefix of second part
    string p2 = commonPrefix(arr, mid + 1, r);

    // Find and return the Longest Common Prefix
    // of subarray arr[l ... r]
    return commonPrefixUtil(p1, p2);
}
return "";

}

string longestCommonPrefix(vector &arr) { return commonPrefix(arr, 0, arr.size() - 1); }

int main() { vector arr = {"geeksforgeeks", "geeks", "geek", "geezer"}; cout << longestCommonPrefix(arr); return 0; }

Java

// Java program to find the longest common prefix // using Divide and Conquer Algorithm

import java.util.*;

class GfG {

// Utility function to find the common prefix between
// strings s1 and s2
static String commonPrefixUtil(String s1, String s2) {
    StringBuilder res = new StringBuilder();
    int n1 = s1.length(), n2 = s2.length();

    for (int i = 0; i < n1 && i < n2; i++) {
        if (s1.charAt(i) != s2.charAt(i))
            break;
        res.append(s1.charAt(i));
    }
    return res.toString();
}

// Divide and Conquer function to find the longest common prefix
// This is similar to the merge sort technique
static String commonPrefix(String[] arr, int l, int r) {
  
      // Base Case: common prefix for a set of single string 
      // is string itself
    if (l == r)
        return arr[l];

    if (l < r) {
        int mid = l + (r - l) / 2;
      
          // Find Longest Common Prefix of first part
        String p1 = commonPrefix(arr, l, mid);
      
          // Find Longest Common Prefix of second part
        String p2 = commonPrefix(arr, mid + 1, r);

          // Find and return the Longest Common Prefix
          // of sub array arr[l ... r]
        return commonPrefixUtil(p1, p2);
    }
    return "";
}

static String longestCommonPrefix(String[] arr) {
    return commonPrefix(arr, 0, arr.length - 1);
}

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 Divide and Conquer Algorithm

Utility function to find the common prefix between

strings s1 and s2

def commonPrefixUtil(s1, s2): res = [] n1, n2 = len(s1), len(s2)

for i in range(min(n1, n2)):
    if s1[i] != s2[i]:
        break
    res.append(s1[i])

return ''.join(res)

Divide and Conquer function to find the longest common prefix

This is similar to the merge sort technique

def commonPrefix(arr, l, r):

  # Base Case: common prefix for a set of single string 
  # is string itself
if l == r:
    return arr[l]

if l < r:
    mid = l + (r - l) // 2
    
    # Find Longest Common Prefix of first part
    p1 = commonPrefix(arr, l, mid)
    
    # Find Longest Common Prefix of second part
    p2 = commonPrefix(arr, mid + 1, r)

    # Find and return the Longest Common Prefix
      # of sub array arr[l ... r]
    return commonPrefixUtil(p1, p2)

def longestCommonPrefix(arr): return commonPrefix(arr, 0, len(arr) - 1)

if name == "main": arr = ["geeksforgeeks", "geeks", "geek", "geezer"] print(longestCommonPrefix(arr))

C#

// C# program to find the longest common prefix // using Divide and Conquer Algorithm using System; using System.Collections.Generic; using System.Text;

class GfG {

// Utility function to find the common prefix between
// strings s1 and s2
static string commonPrefixUtil(string s1, string s2) {
    StringBuilder res = new StringBuilder();
    int n1 = s1.Length, n2 = s2.Length;

    for (int i = 0; i < n1 && i < n2; i++) {
        if (s1[i] != s2[i])
            break;
        res.Append(s1[i]);
    }
    return res.ToString();
}

// Divide and Conquer function to find the longest common prefix
// This is similar to the merge sort technique
static string commonPrefix(string[] arr, int l, int r) {
  
      // Base Case: common prefix for a set of single string 
    // is string itself
    if (l == r)
        return arr[l];

    if (l < r) {
        int mid = l + (r - l) / 2;
      
          // Find Longest Common Prefix of first part
        string p1 = commonPrefix(arr, l, mid);
      
          // Find Longest Common Prefix of second part
        string p2 = commonPrefix(arr, mid + 1, r);

          // Find and return the Longest Common Prefix
        // of sub array arr[l ... r]
        return commonPrefixUtil(p1, p2);
    }
    return "";
}

static string longestCommonPrefix(string[] arr) {
    return commonPrefix(arr, 0, arr.Length - 1);
}

static void Main() {
    string[] arr = {"geeksforgeeks", "geeks", "geek", "geezer"};
    Console.WriteLine(longestCommonPrefix(arr));
}

}

JavaScript

// JavaScript program to find the longest common prefix // using Divide and Conquer Algorithm

// Utility function to find the common prefix between // strings s1 and s2 function commonPrefixUtil(s1, s2) { let res = []; let n1 = s1.length, n2 = s2.length;

for (let i = 0; i < n1 && i < n2; i++) {
    if (s1[i] != s2[i])
        break;
    res.push(s1[i]);
}
return res.join("");

}

// Divide and Conquer function to find the longest common prefix // This is similar to the merge sort technique function commonPrefix(arr, l, r) {

// Base Case: common prefix for a set of single string 
  // is string itself
if (l === r)
    return arr[l];

if (l < r) {
    let mid = l + Math.floor((r - l) / 2);
    
    // Find Longest Common Prefix of first part
    let p1 = commonPrefix(arr, l, mid);
    
    // Find Longest Common Prefix of second part
    let p2 = commonPrefix(arr, mid + 1, r);

    // Find and return the Longest Common Prefix
      // of sub array arr[l ... r]
    return commonPrefixUtil(p1, p2);
}

}

function longestCommonPrefix(arr) { return commonPrefix(arr, 0, arr.length - 1); }

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

`

[Expected Approach 3] Using Trie - O(n*m) Time O(n*m) Space

The idea is to insert all the string one by one in the trie. After inserting we perform a walk on the trie. In this walk, we go deeper until we find a node having more than **1 children(branching occurs) or 0 children (one of the string gets exhausted). This is because the characters (nodes in trie) which are present in the longest common prefix must be the single child of its parent, i.e- there should not be branching in any of these nodes.

**Algorithm:

longest_common_prefix_using_trie

C++ `

// C++ Program to find the Longest Common Prefix // of the given strings using Trie

#include #include using namespace std;

class TrieNode { public: vector<TrieNode*> children; int childCount;

// isLeaf is true if the node represents
// end of a word
bool isLeaf;

  TrieNode() {
      children = vector<TrieNode*> (26, nullptr);
      childCount = 0;
      isLeaf = false;
}

};

// If not present, inserts the key into the trie // If the key is a prefix of trie node, just mark leaf node void insert(TrieNode* root, string& key) { TrieNode* curr = root;

for (char ch: key) {
    int idx = ch - 'a';
    if (curr->children[idx] == nullptr) {
        curr->children[idx] = new TrieNode();
          curr->childCount++;
    }

    curr = curr->children[idx];
}

// mark last node as leaf
curr->isLeaf = true;

}

// Perform a walk on the trie and return the // longest common prefix string string walkTrie(TrieNode root, string& s) { TrieNode curr = root; int i = 0;

while (curr->childCount == 1 && !curr->isLeaf) {
      int idx = s[i] - 'a';
      i++;
    curr = curr->children[idx];
}
return s.substr(0, i);

}

// A Function that returns the longest common prefix // from the array of strings string longestCommonPrefix(vector& arr) { TrieNode *root = new TrieNode();

  // Insert all strings to the trie
  for (string& s: arr) 
      insert(root, s);

// Perform a walk on the trie
return walkTrie(root, arr[0]);

}

int main() { vector arr = {"geeksforgeeks", "geeks", "geek", "geezer"};

cout << longestCommonPrefix(arr) << endl;
return 0;

}

Java

// Java Program to find the Longest Common Prefix // of the given strings using Trie import java.util.*;

class TrieNode { public List children; public int childCount; public boolean isLeaf;

public TrieNode() {
    children = new ArrayList<>(26);
    for (int i = 0; i < 26; i++) {
        children.add(null);
    }
    childCount = 0;
    isLeaf = false;
}

}

class GfG {

// If not present, inserts the key into the trie
// If the key is a prefix of trie node, just mark leaf node
static void insert(TrieNode root, String key) {
    TrieNode curr = root;
    for (char ch : key.toCharArray()) {
        int idx = ch - 'a';
        if (curr.children.get(idx) == null) {
            curr.children.set(idx, new TrieNode());
            curr.childCount++;
        }

        curr = curr.children.get(idx);
    }

    // mark last node as leaf
    curr.isLeaf = true;
}

// Perform a walk on the trie and return the
// longest common prefix string
static String walkTrie(TrieNode root, String s) {
    TrieNode curr = root;
    int i = 0;
    
    while (curr.childCount == 1 && !curr.isLeaf) {
        int idx = s.charAt(i) - 'a';
        i++;
        curr = curr.children.get(idx);
    }
    return s.substring(0, i);
}

// A Function that returns the longest common prefix
// from the array of strings
static String longestCommonPrefix(String[] arr) {
    TrieNode root = new TrieNode();

    // Insert all strings to the trie
    for (String s : arr) 
        insert(root, s);

    // Perform a walk on the trie
    return walkTrie(root, arr[0]);
}

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

of the given strings using Trie

class TrieNode: def init(self): self.children = [None] * 26 self.childCount = 0 self.isLeaf = False

If not present, inserts the key into the trie

If the key is a prefix of trie node, just mark leaf node

def insert(root, key): curr = root for ch in key: idx = ord(ch) - ord('a') if curr.children[idx] is None: curr.children[idx] = TrieNode() curr.childCount += 1

    curr = curr.children[idx]

# mark last node as leaf
curr.isLeaf = True

Perform a walk on the trie and return the

longest common prefix string

def walkTrie(root, s): curr = root i = 0

while curr.childCount == 1 and not curr.isLeaf:
    idx = ord(s[i]) - ord('a')
    i += 1
    curr = curr.children[idx]

return s[:i]

A Function that returns the longest common prefix

from the array of strings

def longestCommonPrefix(arr): root = TrieNode()

# Insert all strings to the trie
for s in arr:
    insert(root, s)

# Perform a walk on the trie
return walkTrie(root, arr[0])

if name == "main": arr = ["geeksforgeeks", "geeks", "geek", "geezer"] print(longestCommonPrefix(arr))

C#

// C# Program to find the Longest Common Prefix // of the given strings using Trie using System; using System.Collections.Generic;

class TrieNode { public List children; public int childCount; public bool isLeaf;

public TrieNode() {
    children = new List<TrieNode>(26);
    for (int i = 0; i < 26; i++) {
        children.Add(null);
    }
    childCount = 0;
    isLeaf = false;
}

}

class GfG {

// If not present, inserts the key into the trie
// If the key is a prefix of trie node, just mark leaf node
static void insert(TrieNode root, string key) {
    TrieNode curr = root;
    foreach (char ch in key) {
        int idx = ch - 'a';
        if (curr.children[idx] == null) {
            curr.children[idx] = new TrieNode();
            curr.childCount++;
        }

        curr = curr.children[idx];
    }

    // mark last node as leaf
    curr.isLeaf = true;
}

// Perform a walk on the trie and return the
// longest common prefix string
static string walkTrie(TrieNode root, string s) {
    TrieNode curr = root;
    int i = 0;

    while (curr.childCount == 1 && !curr.isLeaf) {
        int idx = s[i] - 'a';
        i++;
        curr = curr.children[idx];
    }
  
    return s.Substring(0, i);
}

// A Function that returns the longest common prefix
// from the array of strings
static string longestCommonPrefix(string[] arr) {
    TrieNode root = new TrieNode();

    // Insert all strings to the trie
    foreach (string s in arr) {
        insert(root, s);
    }

    // Perform a walk on the trie
    return walkTrie(root, arr[0]);
}

static void Main(string[] args) {
    string[] arr = { "geeksforgeeks", "geeks", "geek", 
                                            "geezer" };

    Console.WriteLine(longestCommonPrefix(arr));
}

}

JavaScript

// JavaScript Program to find the Longest Common Prefix // of the given strings using Trie

class TrieNode { constructor() { this.children = new Array(26).fill(null); this.childCount = 0; this.isLeaf = false; } }

// If not present, inserts the key into the trie // If the key is a prefix of trie node, just mark leaf node function insert(root, key) { let curr = root; for (let ch of key) { let idx = ch.charCodeAt(0) - 'a'.charCodeAt(0); if (curr.children[idx] === null) { curr.children[idx] = new TrieNode(); curr.childCount++; }

    curr = curr.children[idx];
}

// mark last node as leaf
curr.isLeaf = true;

}

// Perform a walk on the trie and return the // longest common prefix string function walkTrie(root, s) { let curr = root; let i = 0;

while (curr.childCount === 1 && !curr.isLeaf) {
    let idx = s.charCodeAt(i) - 'a'.charCodeAt(0);
    i++;
    curr = curr.children[idx];
}
return s.substring(0, i);

}

// A Function that returns the longest common prefix // from the array of strings function longestCommonPrefix(arr) { let root = new TrieNode();

// Insert all strings to the trie
for (let s of arr) {
    insert(root, s);
}

// Perform a walk on the trie
return walkTrie(root, arr[0]);

}

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

`