
Sponsored
In this approach, you start with the first string as a reference and gradually compare it with each subsequent string in the array. The reference prefix is shortened until it matches the prefixes of all strings.
Time Complexity: O(S), where S is the sum of all characters in all strings.
Space Complexity: O(1), as we are using constant extra space.
1class Solution {
2 public String longestCommonPrefix(String[] strs) {
3 if (strs == null || strs.length == 0) return "";
4 String prefix = strs[0];
5 for (int i = 1; i < strs.length; i++) {
6 while (strs[i].indexOf(prefix) != 0) {
7 prefix = prefix.substring(0, prefix.length() - 1);
8 if (prefix.isEmpty()) return "";
9 }
10 }
11 return prefix;
12 }
13
14 public static void main(String[] args) {
15 Solution sol = new Solution();
16 String[] strs = { "flower", "flow", "flight" };
17 System.out.println(sol.longestCommonPrefix(strs));
18 }
19}In the Java solution, a similar logic is used where the indexOf method checks for the prefix in each string. If not found at the start, the prefix is progressively shortened.
This approach involves dividing the array of strings into two halves, recursively finding the longest common prefix for each half, and merging the results. The merge step compares characters from the two strings to find the common prefix.
Time Complexity: O(S), where S is the sum of all characters in the strings.
Space Complexity: O(M*logN), where M is the length of the common prefix and N is the number of strings.
1
This C solution reduces the problem into finding the longest common prefix of smaller sections, leading to a combination of results using a helper function to merge prefixes by character comparison.