← Home

14. Longest Common Prefix

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
binary searchC++Markdown
14

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 14. Longest Common Prefix, the solution in this repository is mainly a binary search solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: binary search, two pointers, sliding window, prefix sums.

The notes already sitting in the source point us in the right direction:

  • Horizontal scanning
  • time: O(S), where S is the sum of all characters in all strings.
  • space: O(1)

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are longestCommonPrefix, commonPrefix, isCommonPrefix.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(S), where S is the number of all characters in the array,
  • Space: O(m⋅logn)

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Horizontal scanning
02//time: O(S), where S is the sum of all characters in all strings.
03//space: O(1)
04//Runtime: 8 ms, faster than 98.47% of C++ online submissions for Longest Common Prefix.
05//Memory Usage: 9 MB, less than 98.54% of C++ online submissions for Longest Common Prefix.
06
07class Solution {
08public:
09    string longestCommonPrefix(vector<string>& strs) {
10        if(strs.size() == 0) return "";
11        int ans = INT_MAX;
12        for(int i = 0; i < strs.size()-1; i++){
13            ans = min(ans, (int)min(strs[i].size(), strs[i+1].size()));
14            while(strs[i].substr(0, ans) != strs[i+1].substr(0, ans)){
15                ans--;
16            }
17            if(ans == 0)return "";
18        }
19        return strs[0].substr(0, ans);
20    }
21};
22
23//Vertical scanning
24//Time complexity : O(S) , where S is the sum of all characters in all strings. 
25//In the worst case there will be nn equal strings with length mm and the algorithm performs S=m⋅n character comparisons. 
26//Even though the worst case is still the same as Approach 1, 
27//in the best case there are at most n⋅minLen comparisons where minLen is the length of the shortest string in the array.
28//Space complexity : O(1). We only used constant extra space. 
29class Solution {
30public:
31    string longestCommonPrefix(vector<string>& strs) {
32        if(strs.size() == 0) return "";
33        for(int i = 0; i < strs[0].size(); i++){
34            //i: index of char
35            for(int j = 1; j < strs.size(); j++){
36                //j: index of str
37                if(i >= strs[j].size() || strs[0][i] != strs[j][i]){
38                    return strs[0].substr(0, i);
39                }
40            }
41        }
42        return strs[0];
43    }
44};
45
46//Divide and Conquer
47//In the worst case we have nn equal strings with length m
48//Time complexity : O(S), where S is the number of all characters in the array, 
49//S=m⋅n Time complexity is 2⋅T(n/2)+O(m). Therefore time complexity is O(S). 
50//In the best case this algorithm performs O(minLen⋅n) comparisons, where minLen is the shortest string of the array.
51//Space complexity : O(m⋅logn)
52//There is a memory overhead since we store recursive calls in the execution stack. 
53//There are logn recursive calls, each store need m space to store the result, so space complexity is O(m⋅logn)
54//Runtime: 8 ms, faster than 98.47% of C++ online submissions for Longest Common Prefix.
55//Memory Usage: 12 MB, less than 11.34% of C++ online submissions for Longest Common Prefix.
56
57class Solution {
58public:
59    string commonPrefix(string left, string right){
60        int _min = min(left.size(), right.size());
61        for(int i = 0; i < _min; i++){
62            if(left[i] != right[i]){
63                //i is the length of the resulting substring
64                return left.substr(0, i);
65            }
66        }
67        return left.substr(0, _min);
68    }
69    string longestCommonPrefix(vector<string>& strs, int l, int r){
70        if(l == r) return strs[l];
71        int mid = (l+r)/2;
72        string lcpL = longestCommonPrefix(strs, l, mid);
73        string lcpR = longestCommonPrefix(strs, mid+1, r);
74        return commonPrefix(lcpL, lcpR);
75    }
76    string longestCommonPrefix(vector<string>& strs) {
77        if(strs.size() == 0) return "";
78        return longestCommonPrefix(strs, 0, strs.size()-1);
79    }
80};
81
82//Binary Search
83//Runtime: 8 ms, faster than 98.47% of C++ online submissions for Longest Common Prefix.
84//Memory Usage: 9.1 MB, less than 98.17% of C++ online submissions for Longest Common Prefix.
85//In the worst case we have n equal strings with length m
86//Time complexity : O(S⋅logn), where S is the sum of all characters in all strings.
87//The algorithm makes logn iterations, for each of them there are S=m⋅n comparisons, which gives in total O(S⋅logn) time complexity.
88//Space complexity : O(1). We only used constant extra space. 
89
90class Solution {
91public:
92    bool isCommonPrefix(vector<string>& strs, int len){
93        string str1 = strs[0].substr(0, len);
94        //check str1 is the prefix of all strs[1] to strs[n-1]
95        for(int i = 1; i < strs.size(); i++){
96            //str1.rfind(str2, 0) == 0: str1.startswith(str2)
97            if(strs[i].rfind(str1, 0) != 0) return false;
98        }
99        return true;
100    }
101    string longestCommonPrefix(vector<string>& strs) {
102        if(strs.size() == 0) return "";
103        int _min = INT_MAX;
104        for(string str : strs) _min = min(_min, (int)str.size());
105        //use binary search to find 
106        int low = 1, high = _min;
107        while(low <= high){
108            int middle = (low+high)/2;
109            if(isCommonPrefix(strs, middle)){
110                low = middle + 1;
111            }else{
112                high = middle - 1;
113            }
114        }
115        //same result:
116        // return strs[0].substr(0, (low+high)/2);
117        return strs[0].substr(0, high);
118    }
119};
120
121//Follow up...

Cost

Complexity

Time
O(S), where S is the number of all characters in the array,
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(m⋅logn)
Auxiliary state plus the answer structure where the problem requires one.