📖 Scenario: You are building a simple tool to find the longest common starting part (prefix) of a list of words. This is useful in apps like search engines or contact lists to quickly find common beginnings.
🎯 Goal: Build a program that finds the longest common prefix string among a list of words.
📋 What You'll Learn
Create a vector of strings called words with exactly these entries: "flower", "flow", "flight"
Create an integer variable called minLength to store the length of the shortest word
Write a loop to find the longest common prefix among the words
Print the longest common prefix string
💡 Why This Matters
🌍 Real World
Finding common prefixes helps autocomplete features in search engines, code editors, and contact lists to suggest words quickly.
💼 Career
Understanding string manipulation and loops is essential for software development roles involving text processing and user interface features.
Progress0 / 4 steps
1
Create the list of words
Create a vector of strings called words with these exact entries: "flower", "flow", "flight"
DSA C++
Hint
Use std::vector<std::string> and initialize it with the three words inside curly braces.
2
Find the shortest word length
Create an integer variable called minLength and set it to the length of the shortest word in words using a loop.
DSA C++
Hint
Start minLength with the first word's length. Then check each word's length and update minLength if smaller.
3
Find the longest common prefix
Write a loop using an integer i from 0 to minLength - 1 to compare characters at position i in all words. Stop if any character differs. Store the length of the common prefix in prefixLength.
DSA C++
Hint
Compare each character at position i in all words. If any word differs, stop the loop. Use prefixLength to count matching characters.
4
Print the longest common prefix
Print the substring of the first word from index 0 to prefixLength as the longest common prefix using std::cout.
DSA C++
Hint
Use words[0].substr(0, prefixLength) to get the prefix and print it with std::cout.
Practice
(1/5)
1. What does the Longest Common Prefix (LCP) problem ask you to find given a list of strings?
easy
A. The total count of common characters in all strings
B. The longest starting substring common to all strings
C. The longest ending substring common to all strings
D. The longest substring common to any two strings
Solution
Step 1: Understand the problem definition
The Longest Common Prefix means the longest substring at the start of all strings that is the same.
Step 2: Compare options with the definition
Only The longest starting substring common to all strings matches the definition exactly: longest starting substring common to all strings.
Final Answer:
The longest starting substring common to all strings -> Option B
Quick Check:
Longest Common Prefix = longest starting substring [OK]
Hint: Focus on the start of strings, not anywhere else [OK]
Common Mistakes:
Confusing prefix with substring anywhere
Thinking about suffix instead of prefix
Counting characters instead of substring
2. Which of the following C++ code snippets correctly initializes a vector of strings named strs with values "flower", "flow", "flight"?
easy
A. std::vector strs = {"flower", "flow", "flight"};
B. std::vector strs = {"flower", "flow", "flight"};
C. vector<string> strs = ("flower", "flow", "flight");
D. std::vector strs = ("flower", "flow", "flight");
In C++, to initialize a vector of strings with values, use curly braces {} and specify type with std::vector.
Step 2: Validate each option
std::vector strs = {"flower", "flow", "flight"}; uses correct syntax with std::vector and braces {}. Versions missing std:: namespace, using parentheses instead of braces, or lacking template type <std::string> are invalid.
Final Answer:
std::vector strs = {"flower", "flow", "flight"}; -> Option A
Quick Check:
Correct vector initialization uses braces and type [OK]
Hint: Use curly braces {} and full type for vector initialization [OK]
Common Mistakes:
Using parentheses instead of braces
Omitting std:: namespace
Missing template argument
3. What is the output of the following C++ code?
std::vector strs = {"interview", "internet", "internal"};
std::string prefix = strs[0];
for (int i = 1; i < strs.size(); i++) {
int j = 0;
while (j < prefix.size() && j < strs[i].size() && prefix[j] == strs[i][j]) {
j++;
}
prefix = prefix.substr(0, j);
}
std::cout << prefix << std::endl;
medium
A. int
B. inte
C. intern
D. inter
Solution
Step 1: Initialize prefix and compare with each string
Start prefix = "interview". Compare with "internet": common prefix is "inter". Update prefix = "inter".
Step 2: Compare updated prefix "inter" with "internal"
Common prefix is "inter" again. So prefix remains "inter".
Final Answer:
inter -> Option D
Quick Check:
Common prefix of all = "inter" [OK]
Hint: Compare prefix with each string, shorten prefix on mismatch [OK]
Common Mistakes:
Stopping after first comparison
Not updating prefix correctly
Confusing substring indices
4. Identify the bug in the following C++ code that tries to find the longest common prefix:
std::string longestCommonPrefix(std::vector& strs) {
std::string prefix = strs[0];
for (int i = 1; i < strs.size(); i++) {
int j = 0;
while (j < prefix.size() && j < strs[i].size() && prefix[j] == strs[i][j]) {
j++;
}
prefix = prefix.substr(0, j);
if (prefix.empty()) return "";
}
return prefix;
}
// Usage:
// std::vector words = {"dog", "racecar", "car"};
// std::cout << longestCommonPrefix(words) << std::endl;
medium
A. The function does not handle empty input vector
B. The function returns incorrect prefix for input {"dog", "racecar", "car"}
C. The while loop condition is incorrect and causes infinite loop
D. The function should return the longest common suffix instead
Solution
Step 1: Check empty input handling
The code directly accesses strs[0] without checking if strs is empty, causing a runtime error (out-of-range access) for empty vectors.
Step 2: Verify other statements
The loop logic correctly shortens the prefix, no infinite loop occurs, it returns prefix not suffix, and for {"dog", "racecar", "car"} it correctly returns "".
Final Answer:
The function does not handle empty input vector -> Option A
Quick Check:
Missing if(strs.empty()) return ""; [OK]
Hint: Test edge cases like empty lists first [OK]
Common Mistakes:
Overlooking empty vector handling
Misjudging the output for no common prefix cases
Suspecting infinite loop in the while condition
5. Given a list of strings {"apple", "ape", "april", "apt"}, write a C++ function to find the longest common prefix using a vertical scanning approach. What will be the output of your function?
hard
A. "app"
B. "a"
C. "ap"
D. ""
Solution
Step 1: Understand vertical scanning approach
Check characters column by column across all strings until mismatch or end of any string.
Step 2: Apply vertical scanning on given strings
Index 0: all have 'a'. Index 1: all have 'p'. Index 2: "apple" has 'p', "ape" has 'e' (mismatch). Stop scanning.
Final Answer:
"ap" -> Option C
Quick Check:
Vertical scan stops at first mismatch, prefix = "ap" [OK]
Hint: Scan characters column-wise until mismatch found [OK]
Common Mistakes:
Assuming prefix is longest word's start
Stopping scan too early or too late
Confusing vertical with horizontal scanning
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.