


You are given an array ‘ARR’ consisting of ‘N’ strings. Your task is to find the longest common prefix among all these strings. If there is no common prefix, you have to return an empty string.
A prefix of a string can be defined as a substring obtained after removing some or all characters from the end of the string.
For Example:Consider ARR = [“coding”, ”codezen”, ”codingninja”, ”coders”]
The longest common prefix among all the given strings is “cod” as it is present as a prefix in all strings. Hence, the answer is “cod”.
The first line of the input contains a single integer, 'T,’ denoting the number of test cases.
The first line of each test case contains a single integer ‘N’ denoting the number of strings in the array.
The next line contains ‘N’ space-separated strings denoting the elements of the array ‘ARR’.
Output Format:
For each test case, print a single string corresponding to the longest common prefix.
Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 3000
1 <= |ARR[i]| <=1000
Each string consists of only lowercase letters.
Time limit: 1 sec
2
4
coding codezen codingninja coder
3
night ninja nil
cod
ni
For the first test case,
The longest common prefix among all the given strings is “cod” as it is present as a prefix in all strings. Hence, the answer is “cod”.
For the second test case,
The longest common prefix among all the given strings is “ni” as it is present as a prefix in all strings. Hence, the answer is “ni”.
2
3
applejuice applepie apple
4
car cus cart carat
apple
c
Try to find the optimal condition to include the character in the longest common prefix.
In this approach, we will iterate through each character of the first string and check if the same character exists in each string or not. We will maintain a variable longestPrefix to store the longest common prefix.
We will traverse idx from 0 to the length of ARR[0] -1.
In the end, we will return the variable longestPrefix.
Algorithm:
O(N*M), where N is the number of strings in the array and M is the shortest length of the string present in the array.
We are doing M iteration, and in each iteration, we are traversing through the strings that take O(N) time. Hence, the overall time complexity is O(N*M).
O(1).
Constant space is being used. Hence, the overall space complexity is O(1).