Longest Common Prefix in DSA C# - Time & Space Complexity
We want to understand how the time needed to find the longest common prefix grows as the number of strings and their lengths increase.
The question is: How does the work change when we have more strings or longer strings?
Analyze the time complexity of the following code snippet.
public string LongestCommonPrefix(string[] strs) {
if (strs == null || strs.Length == 0) return "";
string prefix = strs[0];
for (int i = 1; i < strs.Length; i++) {
while (strs[i].IndexOf(prefix) != 0) {
prefix = prefix.Substring(0, prefix.Length - 1);
if (prefix == "") return "";
}
}
return prefix;
}
This code finds the longest common prefix among an array of strings by comparing and shortening the prefix as needed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer loop goes through each string, and the inner while loop shortens the prefix until it matches the start of the current string.
- How many times: The outer loop runs once per string (n-1 times), and the inner loop can run up to the length of the prefix (m) in the worst case.
As the number of strings (n) or the length of the prefix (m) grows, the number of operations increases roughly by n times m.
| Input Size (n strings, prefix length m) | Approx. Operations |
|---|---|
| 10 strings, prefix length 5 | About 50 checks |
| 100 strings, prefix length 10 | About 1000 checks |
| 1000 strings, prefix length 20 | About 20,000 checks |
Pattern observation: The work grows roughly by multiplying the number of strings by the prefix length.
Time Complexity: O(n * m)
This means the time needed grows proportionally with both the number of strings and the length of the prefix.
[X] Wrong: "The time depends only on the number of strings, not their length."
[OK] Correct: The prefix length matters because the code may shorten the prefix many times, checking characters each time, so longer prefixes mean more work.
Understanding this time complexity helps you explain how your solution scales and shows you can analyze nested loops clearly, a key skill in interviews.
"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 problem asks for the longest substring that appears at the start of every string in the array.Step 2: Compare options with the definition
The longest starting substring common to all strings matches the definition exactly. Options A, B, and C do not describe the prefix or the problem correctly.Final Answer:
The longest starting substring common to all strings -> Option AQuick Check:
Longest Common Prefix = longest starting substring [OK]
- Confusing prefix with substring anywhere
- Thinking about shortest string instead
- Counting strings instead of prefix
Solution
Step 1: Identify the expected return type
The longest common prefix is a string, so the method should return a string.Step 2: Check parameter type and return type
public string LongestCommonPrefix(string[] strs) returns string and takes string array, which is correct. public int LongestCommonPrefix(string[] strs) returns int (wrong type). public void LongestCommonPrefix(string[] strs) returns void (no return). public string LongestCommonPrefix(List<string> strs) uses List<string> instead of array, which is valid but not matching the question's array input.Final Answer:
public string LongestCommonPrefix(string[] strs) -> Option CQuick Check:
Return type string with string[] parameter [OK]
- Using wrong return type like int or void
- Using List<string> instead of string[] when array expected
- Confusing parameter types
string[] words = {"flower", "flow", "flight"};
string prefix = LongestCommonPrefix(words);
Console.WriteLine(prefix);
string LongestCommonPrefix(string[] strs) {
if (strs == null || strs.Length == 0) return "";
string prefix = strs[0];
for (int i = 1; i < strs.Length; i++) {
while (!strs[i].StartsWith(prefix)) {
prefix = prefix.Substring(0, prefix.Length - 1);
if (prefix == "") return "";
}
}
return prefix;
}Solution
Step 1: Initialize prefix and iterate
Prefix starts as "flower". Compare with "flow": "flow" does not start with "flower", so remove last char -> "flowe", then "flow", which matches.Step 2: Compare prefix with "flight"
"flight" does not start with "flow", remove last char: "flo", no; "fl", yes. So prefix becomes "fl".Final Answer:
"fl" -> Option AQuick Check:
Common prefix of all = "fl" [OK]
- Assuming prefix is first string always
- Not shrinking prefix correctly
- Returning empty string too early
string LongestCommonPrefix(string[] strs) {
if (strs == null || strs.Length == 0) return "";
string prefix = strs[0];
for (int i = 1; i < strs.Length; i++) {
while (!strs[i].Contains(prefix)) {
prefix = prefix.Substring(0, prefix.Length - 1);
if (prefix == "") return "";
}
}
return prefix;
}Solution
Step 1: Analyze the prefix check method
The code uses strs[i].Contains(prefix) to check prefix, but prefix must be at the start, so StartsWith is correct.Step 2: Understand impact of Contains
Contains allows prefix anywhere in the string, so it may accept wrong prefixes that are not at the start.Final Answer:
Using Contains instead of StartsWith causes wrong prefix check -> Option BQuick Check:
Prefix must be at start, not anywhere [OK]
- Using Contains instead of StartsWith
- Ignoring null or empty strings in array
- Incorrect loop start index
["interview", "interrupt", "integrate", "integral"], what is the longest common prefix? Also, explain why the prefix ends where it does.Solution
Step 1: Compare strings character by character
All strings start with "int". "interview" and "interrupt" continue with "er", while "integrate" and "integral" continue with "eg".Step 2: Identify where prefix breaks
"interview" and "interrupt" have "inter", but "integrate" and "integral" have "integ", so common prefix stops at "int".Final Answer:
"int" -> Option DQuick Check:
Prefix stops where any string differs [OK]
- Assuming longer prefix without checking all strings
- Ignoring difference in later strings
- Confusing similar prefixes with actual common prefix
Ready to prove it?
Pass the test and this pattern moves unknown
