Longest Common Prefix in DSA C - Time & Space Complexity
We want to understand how the time needed to find the longest common prefix changes as we add more words or longer words.
How does the work grow when the input list or word length grows?
Analyze the time complexity of the following code snippet.
char* longestCommonPrefix(char** strs, int strsSize) {
if (strsSize == 0) return "";
if (strsSize == 1) return strs[0];
for (int i = 0; ; i++) {
char c = strs[0][i];
for (int j = 1; j < strsSize; j++) {
if (strs[j][i] == '\0' || strs[j][i] != c) {
strs[0][i] = '\0';
return strs[0];
}
}
}
}
This code finds the longest common prefix among an array of strings by comparing characters one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops comparing characters of each string at the same position.
- How many times: Outer loop runs up to the length of the shortest string; inner loop runs for each string in the array.
As we add more strings or longer strings, the comparisons increase.
| Input Size (n = number of strings) | Approx. Operations |
|---|---|
| 10 strings, each length 5 | About 50 character comparisons |
| 100 strings, each length 5 | About 500 character comparisons |
| 100 strings, each length 100 | Up to 10,000 character comparisons |
Pattern observation: The work grows roughly with the product of the number of strings and the length of the shortest string.
Time Complexity: O(n * m)
This means the time grows with the number of strings (n) times the length of the shortest string (m).
[X] Wrong: "The time depends only on the number of strings, not their length."
[OK] Correct: We must check characters one by one, so longer strings mean more work even if the number of strings stays the same.
Understanding this helps you explain how your solution scales and shows you can analyze nested loops clearly.
"What if we sorted the strings first and only compared the first and last strings? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem definition
The Longest Common Prefix means the longest substring starting from the beginning that is shared by all strings in the array.Step 2: Compare options with definition
Only The longest starting substring common to all strings matches this definition exactly. Options A and C talk about suffix or any substring, and D is unrelated.Final Answer:
The longest starting substring common to all strings -> Option CQuick Check:
Longest Common Prefix = longest starting substring [OK]
- Confusing prefix with suffix
- Thinking about any substring instead of prefix
- Choosing shortest string instead of prefix
Solution
Step 1: Identify correct data type for prefix length
The length of a prefix is a number, so it should be stored in an integer variable.Step 2: Check initialization syntax
int lcp_length = 0; correctly declares an int and initializes it to 0. char lcp_length = ''; uses char with invalid empty quotes, C uses NULL which is for pointers, and D uses string which is not a C type.Final Answer:
int lcp_length = 0; -> Option AQuick Check:
Prefix length is an integer initialized to zero [OK]
- Using char for numeric length
- Assigning NULL to int variable
- Using non-C types like string
char *strs[] = {"flower", "flow", "flight"};
int i = 0;
while (strs[0][i] && strs[1][i] && strs[2][i] && strs[0][i] == strs[1][i] && strs[1][i] == strs[2][i]) {
i++;
}
printf("%d", i);Solution
Step 1: Compare characters at each index
Index 0: 'f' == 'f' == 'f' (true), index 1: 'l' == 'l' == 'l' (true), index 2: 'o' == 'o' == 'i' (false)Step 2: Count matching prefix length
Matching characters are at indices 0 and 1 only, so length is 2.Final Answer:
2 -> Option BQuick Check:
Matching prefix length = 2 [OK]
- Counting beyond first mismatch
- Confusing index with length
- Ignoring all strings in comparison
int longestCommonPrefix(char **strs, int strsSize) {
int i = 0;
while (strs[0][i]) {
for (int j = 1; j < strsSize; j++) {
if (strs[j][i] != strs[0][i])
return i;
}
i++;
}
return i;
}Solution
Step 1: Analyze character comparison in inner loop
The code compares strs[j][i] with strs[0][i] but does not check if strs[j][i] is '\0' (string end).Step 2: Understand consequence of missing null check
If strs[j] is shorter than strs[0], accessing strs[j][i] beyond its length causes undefined behavior or wrong result.Final Answer:
Does not check if strs[j][i] is null before comparison -> Option DQuick Check:
Check string length before comparing characters [OK]
- Ignoring string length in loops
- Returning too early without full check
- Using wrong loop indices
["interview", "interval", "internal", "internet"], which of the following C code snippets correctly returns the longest common prefix string?Solution
Step 1: Check loop and character comparison logic
The correct code uses while(1) with break if strs[0][i] == '\0', caches c = strs[0][i], and for each j checks strs[j][i] != c || strs[j][i] == '\0' then goto end before i++. This stops exactly at the first mismatch or shorter string.Step 2: Verify prefix extraction and return
After loop, malloc(i + 1), strncpy(prefix, strs[0], i), prefix[i] = '\0', return prefix. This creates and returns the new prefix string correctly.Final Answer:
Uses while(1), goto on mismatch/null, malloc/strncpy new prefix -> Option AQuick Check:
Check all strings char by char, then copy prefix [OK]
- Not handling string ends properly
- Returning original string instead of prefix
- Not allocating memory for prefix
Ready to prove it?
Pass the test and this pattern moves unknown
