Problem of the day
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".
Input: 'arr' = [“abcd”, “abc”, “abref”, “abcde”]
Output: ab
Explanation:
Answer is “ab”, as it is the longest prefix present in all the given strings.
The first line contains an integer ‘n’, denoting the number of strings.
The next ‘n’ lines each contain a string, elements of array ‘arr’.
Return the longest common prefix of all the strings. If there is no such prefix, return “-1”.
You don’t need to print anything, it has already been taken care of, just complete the given function.
4
Codingninjas
Coding
Coders
Codezen
Cod
In the given testcase, the longest prefix that is present in all the strings is “Cod”. Hence the answer is “Cod”.
3
abcd
Abcd
abc
-1
In the given testcase, there is no prefix that is present in all the strings. Hence the answer is “-1”
1 <= ‘n’ <= 10^3
1 <= ‘arr[i].length’ <= 10^3
Time Limit: 1 sec
Try solving this in O(n).