The Wayback Machine - https://web.archive.org/web/20241119202556/https://www.geeksforgeeks.org/longest-common-prefix/
Open In App

Longest Common Prefix

Last Updated : 14 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Using Sorting

In this method, we sort the array of strings. After sorting, the longest common prefix of the whole array will be the common prefix between the first and last strings in the sorted array. 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.

To know more about the implementation, please refer Longest Common Prefix using Sorting.

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.

Using Word by Word Matching

The idea here is based on the associative property of the Longest Common Prefix (LCP). Specifically:

LCP (“geeksforgeeks”, “geeks”, “geek”)
= LCP (LCP (“geeksforgeeks”, “geeks”), “geek”)
= LCP (“geeks”, “geek”)
= “geek”

Using this property, we calculate the LCP of each string with the current LCP found so far. By the end, this results in the LCP of the entire array of strings.

To know more about the implementation, please refer Longest Common Prefix Word by Word Matching.

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

Using Character by Character Matching

This approach is similar to word-by-word matching, but instead, we compare characters across the strings one at a time. First, we compare the character at the 0th index, then the 1st index, and so on until all characters at an index are the same.

This method stops as soon as a mismatch is found, making it efficient if the common prefix is short or doesn’t exist at all. Word-by-word matching, on the other hand, goes through each word entirely, even if there’s no common prefix.

To know more about the implementation, please refer Longest Common Prefix Character by Character Matching.

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.

Using Divide and Conquer

The divide and conquer method splits the array of strings into two parts. Each part’s Longest Common Prefix is computed recursively, and then the Longest Common Prefix of the two parts is combined to get the Longest Common Prefix of the entire array. This approach is similar to the divide-and-conquer technique used in merge sort.

To know more about the implementation, please refer Longest Common Prefix Divide and Conquer.

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

The idea is to use binary search on the indices to find the length of longest common prefix.

We can observe that the length of common prefix cannot be greater than the length of smallest string in given set of strings. So the search space for binary search will be from 0 to length of smallest string – 1.

In each iteration of binary search [low to high], we will check whether the prefix [0 to mid] is common among all strings or not.

  • If the prefix is common among all string then check for larger length prefix by updating low = mid + 1
  • Else check for smaller length prefix, by updating high = mid – 1.

To know more about the implementation, please refer Longest Common Prefix Binary Search.

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

Using Trie

In this approach, each string is inserted into a trie, character by character. After insertion, we traverse the trie until a branching node (one with more than one child) or an end node is found. 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.

To know more about the implementation, please refer Longest Common Prefix Using Trie.

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



Next Article

Similar Reads

Longest Common Prefix using Linked List
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Previous Approaches: Word by Word Matching, Character by Character Matching, Divide and Conquer, Binary Search, Using Trie Data Structure Below is an algorithm to solve
14 min read
Longest Common Prefix Matching | Set-6
Given a set of strings, find the longest common prefix. Examples: Input: str[] = {geeksforgeeks, geeks, geek, geezer} Output: gee Input: str[] = {apple, ape, april} Output: ap Previous Approaches: Set1 | Set2 | Set3 | Set4 | Set5 Approach: Sort the given set of N strings.Compare the first and last string in the sorted array of strings.The string wi
6 min read
Find the longest common prefix between two strings after performing swaps on second string
Given two strings [Tex]a [/Tex]and [Tex]b [/Tex]. Find the longest common prefix between them after performing zero or more operations on string [Tex]b [/Tex]. In each operation, you can swap any two letters.Examples: Input : a = "here", b = "there" Output : 4 The 2nd string can be made "heret" by just swapping characters and thus the longest prefi
6 min read
Construct an Array of Strings having Longest Common Prefix specified by the given Array
Given an integer array arr[] of size N, the task is to construct an array consisting of N+1 strings of length N such that arr[i] is equal to the Longest Common Prefix of ith String and (i+1)th String. Examples: Input: arr[] = {1, 2, 3} Output: {"abb", "aab", "aaa", "aaa"} Explanation: Strings "abb" and "aab" have a single character "a" as Longest C
6 min read
Length of longest common prefix possible by rearranging strings in a given array
Given an array of strings arr[], the task is to find the length of the longest common prefix by rearranging the characters of each string of the given array. Examples: Input: arr[] = {“aabdc”, “abcd”, “aacd”}Output: 3Explanation: Rearrange characters of each string of the given array such that the array becomes {“acdab”, “acdb”, “acda”}.Therefore,
8 min read
Pair of strings having longest common prefix of maximum length in given array
Given an array of strings arr[], the task is to find the pair of strings from the given array whose length of the longest common prefix between them is maximum. If multiple solutions exist, then print any one of them. Examples: Input: arr[] = {"geeksforgeeks", "geeks", "geeksforcse", } Output: (geeksforgeeks, geeksforcse) Explanation: All possible
15+ min read
Length of longest prefix anagram which are common in given two strings
Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str2 are "a", and "c".Prefixes of length 2 of string
8 min read
Find minimum shift for longest common prefix
You are given two strings str1 and str2 of the same length. In a single shift, you can rotate one string (str2) by 1 element such that its 1st element becomes the last and the second one becomes the first like "abcd" will change to "bcda" after the one-shift operation. You have to find the minimum shift operation required to get the common prefix o
7 min read
Javascript Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"}Output: "gee"Input: {"apple", "ape", "april"}Output: "ap"The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {"apple", "ape", "ze
2 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.Now let us introduce
3 min read
Longest Common Prefix using Sorting
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: “ge
5 min read
Longest Common Prefix using Binary Search
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: "ge
8 min read
Longest Common Prefix using Trie
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: “ge
7 min read
Longest Common Prefix using Word by Word Matching
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: "ge
5 min read
Longest Common Prefix using Character by Character Matching
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: "ge
5 min read
Longest Common Prefix using Divide and Conquer Algorithm
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: "ge
7 min read
Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Maximum sum increasing subsequence from a prefix and a given element after prefix is must
Given an array of n positive integers, write a program to find the maximum sum of increasing subsequence from prefix till ith index and also including a given kth element which is after i, i.e., k > i. Examples : Input: arr[] = {1, 101, 2, 3, 100, 4, 5} i-th index = 4 (Element at 4th index is 100) K-th index = 6 (Element at 6th index is 5.) Outp
14 min read
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix
Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "helloworldworldhelloworld", S1 = "hello", S2 = "world"Output: NoExpla
8 min read
Maximum prefix sum which is equal to suffix sum such that prefix and suffix do not overlap
Given an array arr[] of N Positive integers, the task is to find the largest prefix sum which is also the suffix sum and prefix and suffix do not overlap. Examples: Input: N = 5, arr = [1, 3, 2, 1, 4]Output: 4Explanation: consider prefix [1, 3] and suffix [4] which gives maximum prefix sum which is also suffix sum such that prefix and suffix do not
7 min read
Counting common prefix/suffix strings in two lists
Given two Lists of strings s1 and s2, you have to count the number of strings in s2 which is either a suffix or prefix of at least one string of s1. Examples: Input: s1 = ["cat", "catanddog", "lion"], s2 = ["cat", "dog", "rat"]Output: 2Explanation: String "cat" of s2 is a prefix of "catanddog"string "dog" of s2 is suffix of "catanddog" Input: s1 =
4 min read
Find position i to split Array such that prefix sum till i-1, i and suffix sum till i+1 are in GP with common ratio K
Given an array, arr[] and a positive integer K. The task is to find the position say i of the element in arr[] such that prefix sum till i-1, i and suffix sum till i+1 are in Geometric Progression with common ratio K. Examples: Input: arr[] = { 5, 1, 4, 20, 6, 15, 9, 10 }, K = 2Output: 4Explanation: The following operations are performed to get req
8 min read
Find position forming AP with prefix and suffix sum of Array with common difference D
Given an array, arr[] of size N and a positive integer D, the task is to find the position i of an element in arr[] such that the prefix sum, arr[i] and suffix sum is in arithmetic progression with common difference D, i.e. arr[i] - sum(arr[0, . . ., i-1]) = sum(arr[i+1, . . ., N-1]) - arr[i] = D. If no such position exists return -1. Examples: Inp
8 min read
Maximum number of Strings with Common Prefix of length K
Given a string array arr[] of length N, the task is to find the maximum number of strings that share a common prefix of length K. Examples: Input: arr = { { "hello", "heydeei", "hap", "hak", "paloa", "padfk", "padfla", "pada" } }, K = 4Output: 2Explanation: String padfk", "padfla" are the two string that share the common prefix of length k. Input:
8 min read
Maximum common prefix of all strings
Given array A[] of strings of size N, the task for this problem is to print the Maximum Common prefix of string 'i' with other strings from 1 to N apart from 'i' itself for all given strings from 1 to N. Given strings consists of lowercase English letters. Examples: Input: {"abc", "abb", "aac"}Output: 2 2 1Explanation: Answer for first string is tw
12 min read
Longest prefix that contains same number of X and Y in an array
Content has been removed on Author's request.
1 min read
Longest palindromic string formed by concatenation of prefix and suffix of a string
Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str. Examples: Input: str = "rombobinnimor" Output: rominnimor Explanation: The concatenation of string "rombob"(prefix) and "mor"(suffix) is "rombobmor" which is a palindromic string. The concatenation of
11 min read
Print the longest prefix of the given string which is also the suffix of the same string
Given string str, the task is to find the longest prefix which is also the suffix of the given string. The prefix and suffix should not overlap. If no such prefix exists then print -1. Examples: Input: str = "aabcdaabc" Output: aabc The string "aabc" is the longest prefix which is also suffix. Input: str = "aaaa" Output: aa Approach: The idea is to
8 min read
Find the longest sub-string which is prefix, suffix and also present inside the string
Given string str. The task is to find the longest sub-string which is a prefix, a suffix, and a sub-string of the given string, str. If no such string exists then print -1.Examples: Input: str = "fixprefixsuffix" Output: fix "fix" is a prefix, suffix and present inside in the string too.Input: str = "aaaa" "aa" is a prefix, suffix and present insid
10 min read
Longest string in an array which matches with prefix of the given string
Given an array of strings arr[] and Q queries where each query consists of a string str, the task is to find the longest string in the array that matches with prefix of the given string str i.e. the string must be prefix of str. Examples: Input: arr[] = {"GeeksForGeeks", "GeeksForGeeksd", "Arnab", "Art"}, q[] = {"GeeksForGeeks", "Ar", "Art"} Output
8 min read
Practice Tags :
three90RightbarBannerImg