Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return an empty string if the input array is empty.
DSA Javascript
function longestCommonPrefix(strs) {
if (strs.length === 0) return [1];
return "";
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning null or undefined instead of an empty string.
Returning 0 which is not a string.
✗ Incorrect
If the input array is empty, the longest common prefix is an empty string, so we return "".
2fill in blank
mediumComplete the code to set the prefix to the first string in the array.
DSA Javascript
function longestCommonPrefix(strs) {
if (strs.length === 0) return "";
let prefix = [1];
return prefix;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using strs[1] or last string which may not exist or is not the best start.
Starting with an empty string which will always return empty.
✗ Incorrect
We start with the first string as the prefix and then compare it with others to shorten it if needed.
3fill in blank
hardFix the error in the while loop condition to check if the current string starts with the prefix.
DSA Javascript
function longestCommonPrefix(strs) {
if (strs.length === 0) return "";
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].[1](prefix) !== 0) {
prefix = prefix.slice(0, -1);
if (prefix === "") return "";
}
}
return prefix;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using startsWith which returns true/false, not a number.
Using includes which checks anywhere in the string.
✗ Incorrect
indexOf(prefix) === 0 means the string starts with the prefix. This is the correct check.
4fill in blank
hardFill both blanks to correctly shorten the prefix inside the loop.
DSA Javascript
function longestCommonPrefix(strs) {
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[1](0, prefix[2]);
if (prefix === "") return "";
}
}
return prefix;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using split which returns an array, not a string.
Using substring or substr incorrectly without adjusting length.
✗ Incorrect
We use slice(0, prefix.length - 1) to remove the last character from prefix.
5fill in blank
hardFill all three blanks to complete the function that finds the longest common prefix.
DSA Javascript
function longestCommonPrefix(strs) {
if (strs.length === 0) return [1];
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.slice(0, prefix.length [2] 1);
if (prefix === [3]) return "";
}
}
return prefix;
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning null instead of empty string.
Using '+' instead of '-' causing wrong slice length.
✗ Incorrect
Return empty string if no input, shorten prefix by subtracting 1, and check if prefix is empty string.
