Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return an empty string if the input vector is empty.
DSA C++
if (strs.empty()) return [1];
Attempts:
3 left
💡 Hint
Common Mistakes
Returning NULL or 0 instead of an empty string.
Not checking if the vector is empty before processing.
✗ Incorrect
If the input vector is empty, the longest common prefix is an empty string, so we return "".
2fill in blank
mediumComplete the code to initialize the prefix with the first string in the vector.
DSA C++
std::string prefix = strs[1];Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets.
Using front() without including the correct header or context.
✗ Incorrect
We use strs[0] to get the first string from the vector to start the prefix.
3fill in blank
hardFix the error in the while loop condition to check prefix length and character match.
DSA C++
while (prefix.length() > 0 && strs[i][[1]] == prefix[[1]]) { prefix = prefix.substr(0, prefix.length() - 1); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using prefix.length() as index causes out-of-range error.
Using 0 as index compares only the first character.
✗ Incorrect
We compare characters at index prefix.length() - 1 to check the last character of the prefix.
4fill in blank
hardFill both blanks to correctly iterate over the strings and update the prefix.
DSA C++
for (int [1] = 1; [1] < strs.size(); [1]++) { int [2] = 0; while ([2] < prefix.length() && strs[[1]][[2]] == prefix[[2]]) { [2]++; } prefix = prefix.substr(0, [2]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same variable name for both loops.
Using variables that are not declared.
✗ Incorrect
We use 'i' to iterate over strings and 'j' to iterate characters in prefix comparison.
5fill in blank
hardFill all three blanks to complete the function that finds the longest common prefix.
DSA C++
std::string longestCommonPrefix(std::vector<std::string>& strs) {
if (strs.empty()) return [1];
std::string prefix = strs[2];
for (int i = 1; i < strs.size(); i++) {
int j = [3];
while (j < prefix.length() && strs[i][j] == prefix[j]) {
j++;
}
prefix = prefix.substr(0, j);
if (prefix.empty()) break;
}
return prefix;
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning nullptr instead of empty string.
Using parentheses instead of square brackets for indexing.
Not initializing j to 0 before the while loop.
✗ Incorrect
Return empty string if empty input, initialize prefix with first string using [0], and use 0 to start index j.
