Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a word starts with the given prefix.
DSA Java
if (word.[1](prefix)) { count++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using equals instead of startsWith
Using contains which checks anywhere in the word
✗ Incorrect
The method startsWith checks if the word begins with the given prefix.
2fill in blank
mediumComplete the code to loop through all words in the list.
DSA Java
for (String [1] : words) { if ([1].startsWith(prefix)) { count++; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the list name 'words' as the loop variable
Using 'prefix' which is the search term, not the loop variable
✗ Incorrect
The loop variable should be a single word from the list, so 'word' is appropriate.
3fill in blank
hardFix the error in the method signature to return the correct type.
DSA Java
public static [1] countWordsWithPrefix(List<String> words, String prefix) { int count = 0; for (String word : words) { if (word.startsWith(prefix)) { count++; } } return count; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using void which means no return value
Using String which is incorrect for a number
✗ Incorrect
The method returns the count of words, which is an integer, so the return type should be int.
4fill in blank
hardFill both blanks to create a map of words and their lengths for words starting with the prefix.
DSA Java
Map<String, Integer> wordLengths = words.stream()
.filter(word -> word.[1](prefix))
.collect(Collectors.toMap(word -> word, word -> word.[2]()));Attempts:
3 left
💡 Hint
Common Mistakes
Using equals instead of startsWith in filter
Using size() which is not a String method
✗ Incorrect
Use startsWith to filter words by prefix and length() to get the word length.
5fill in blank
hardFill all three blanks to count words with prefix using streams and lambda.
DSA Java
long count = words.stream()
.filter([1] -> [2].[3](prefix))
.count();Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in lambda
Using equals instead of startsWith
✗ Incorrect
Use 'w' as the lambda variable and call startsWith on it to filter words by prefix.
