Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return an empty string if the input list is empty.
DSA Go
func longestCommonPrefix(strs []string) string {
if len(strs) == [1] {
return ""
}
return ""
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking if len(strs) == 1 instead of 0
Using a negative number for length check
✗ Incorrect
If the list has zero elements, its length is 0, so we check if len(strs) == 0 to return an empty string.
2fill in blank
mediumComplete the code to set the prefix as the first string in the list.
DSA Go
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
prefix := [1]
return prefix
}Attempts:
3 left
💡 Hint
Common Mistakes
Using strs[1] which is the second string
Using strs[len(strs)] which is out of range
✗ Incorrect
The first string in the list is at index 0, so prefix should be strs[0].
3fill in blank
hardFix the error in the loop condition to iterate over all strings in the list.
DSA Go
for i := 1; i [1] len(strs); i++ { // loop body }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' which causes no iterations
Using '<=' which causes out of range error
✗ Incorrect
To loop from 1 up to but not including len(strs), use i < len(strs).
4fill in blank
hardFill both blanks to check if the prefix is longer than the current string and to compare characters.
DSA Go
for i := 0; i < len(prefix); i++ { if i [1] len(strs[j]) || prefix[i] [2] strs[j][i] { prefix = prefix[:i] break } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>=' for length check
Using '==' instead of '!=' for character comparison
✗ Incorrect
We check if i is greater or equal to the length of the current string to avoid index error, and if characters differ, we shorten the prefix.
5fill in blank
hardFill all three blanks to complete the nested loop that finds the longest common prefix.
DSA Go
for j := 1; j [1] len(strs); j++ { for i := 0; i [2] len(prefix); i++ { if i [3] len(strs[j]) || prefix[i] != strs[j][i] { prefix = prefix[:i] break } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' in loops causing index out of range
Using '<' instead of '>=' in condition causing errors
✗ Incorrect
The outer loop runs while j < len(strs), the inner loop runs while i < len(prefix), and the condition checks if i >= len(strs[j]) to avoid index errors.
