Longest Common Prefix in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to find the longest common prefix grows as we add more words or longer words.
How does the work increase when the input list or word length grows?
Analyze the time complexity of the following code snippet.
function longestCommonPrefix(strs: string[]): string {
if (strs.length === 0) return "";
let prefix = strs[0];
for (let 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 string 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 in the array after the first.
- How many times: The outer loop runs (n - 1) times where n is the number of strings.
- The inner while loop compares the current prefix with the start of each string and shortens it until it matches.
- The inner loop can run up to the length of the prefix (m) times in the worst case.
As we add more strings or longer strings, the number of comparisons grows.
| Input Size (n strings, max length m) | Approx. Operations |
|---|---|
| 10 strings, length 5 | About 45 comparisons |
| 100 strings, length 10 | About 900 comparisons |
| 1000 strings, length 20 | About 20,000 comparisons |
Pattern observation: The work grows roughly with the product of the number of strings and the length of the prefix.
Time Complexity: O(n * m)
This means the time grows proportionally to the number of strings times the length of the shortest prefix.
[X] Wrong: "The time depends only on the number of strings, not their length."
[OK] Correct: The length of the prefix matters because we compare characters one by one, so longer prefixes mean more work.
Understanding this complexity helps you explain how your solution scales and shows you can analyze string operations 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 prefix concept
A prefix is a substring at the start of a string.Step 2: Define longest common prefix
The LCP is the longest substring starting from the beginning that all strings share.Final Answer:
The longest starting substring common to all strings -> Option AQuick Check:
Prefix means start of string = B [OK]
- Confusing prefix with suffix
- Looking for substring anywhere, not just start
- Choosing shortest string as prefix
Solution
Step 1: Identify input type
The input should be an array of strings, so type is string[].Step 2: Identify output type
The output is the longest common prefix, a string.Final Answer:
function longestCommonPrefix(strs: string[]): string -> Option AQuick Check:
Input array of strings, output string = D [OK]
- Using number[] instead of string[]
- Returning array instead of string
- Passing single string instead of array
function longestCommonPrefix(strs: string[]): string {
if (strs.length === 0) return "";
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
if (prefix === "") return "";
}
}
return prefix;
}
console.log(longestCommonPrefix(["flower", "flow", "flight"]));Solution
Step 1: Initialize prefix and loop through strings
Start with prefix = "flower". Check "flow": prefix "flower" not prefix of "flow", shorten to "flowe", then "flow", which is prefix of "flow".Step 2: Check next string "flight"
"flow" not prefix of "flight", shorten to "flo", then "fl", which is prefix of "flight".Final Answer:
"fl" -> Option BQuick Check:
Common start is "fl" = A [OK]
- Returning first string without checking others
- Not shortening prefix correctly
- Confusing substring indices
function longestCommonPrefix(strs: string[]): string {
if (strs.length === 0) return "";
let prefix = strs[0];
for (let i = 1; i <= strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
if (prefix === "") return "";
}
}
return prefix;
}Solution
Step 1: Check loop boundary
The loop uses i <= strs.length, which causes out-of-bounds access at i = strs.length.Step 2: Correct loop condition
Change to i < strs.length to avoid accessing undefined element.Final Answer:
Loop condition should be i < strs.length, not i <= strs.length -> Option CQuick Check:
Array index out of bounds = C [OK]
- Off-by-one error in loop condition
- Initializing prefix incorrectly
- Misusing string methods
["interview", "interval", "internal", "internet"], what is the longest common prefix? Also, explain why the prefix stops where it does.Solution
Step 1: Compare characters one by one
Check each character index across all strings: 'i', 'n', 't', 'e', 'r' are common in all.Step 2: Identify where mismatch occurs
At index 5, 'v' in "interview" and "interval", but 'n' in "internal" and "internet", so prefix stops at "inter".Final Answer:
"inter" because all strings start with these five letters -> Option DQuick Check:
Common start "inter" = B [OK]
- Assuming prefix is longer than actual common part
- Ignoring character positions carefully
- Confusing similar but different letters
Ready to prove it?
Pass the test and this pattern moves unknown
