Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Longest Common Prefix

Moderate
0/80
65 upvotes

Problem statement

You are given an array ‘arr’ of ‘n’ strings.


Find the longest common prefix in all these strings.


If there is no common prefix in all the strings return "-1".


Example:
Input: 'arr' = [“abcd”, “abc”, “abref”, “abcde”]

Output: ab

Explanation:
Answer is “ab”, as it is the longest prefix present in all the given strings.
Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line contains an integer ‘n’, denoting the number of strings.

The next ‘n’ lines each contain a string, elements of array ‘arr’.


Output Format:
Return the longest common prefix of all the strings. If there is no such prefix, return “-1”.


Note:
You don’t need to print anything, it has already been taken care of, just complete the given function.


Sample Input 1:
4
Codingninjas
Coding
Coders
Codezen


Sample Output 1:
Cod   


Explanation of sample output 1:
In the given testcase, the longest prefix that is present in all the strings is “Cod”. Hence the answer is “Cod”. 


Sample Input 2:
3
abcd
Abcd
abc
Sample Output 2:
-1


Explanation of sample output 2:
In the given testcase, there is no prefix that is present in all the strings. Hence the answer is “-1”


Constraints:
1 <= ‘n’ <= 10^3
1 <= ‘arr[i].length’ <= 10^3

Time Limit: 1 sec


Expected Time Complexity:
Try solving this in O(n).
Full screen
Console