Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the prefix array with zeros.
DSA Java
int[] prefix = new int[pattern.length()]; for (int i = 0; i < prefix.length; i++) { prefix[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing prefix array with ones or negative values.
Using pattern length as initial value.
✗ Incorrect
The prefix array should be initialized with zeros because it stores the length of the longest prefix which is also a suffix for each substring.
2fill in blank
mediumComplete the code to update the prefix array when characters match.
DSA Java
if (pattern.charAt(i) == pattern.charAt(j)) { j++; prefix[i] = [1]; i++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning prefix[i] = i instead of j.
Assigning prefix[i] = 0 when characters match.
✗ Incorrect
When characters match, prefix[i] is set to j which is the length of the current longest prefix suffix.
3fill in blank
hardFix the error in the while loop condition to avoid infinite loop.
DSA Java
while (i < pattern.length()) { if (pattern.charAt(i) == pattern.charAt(j)) { j++; prefix[i] = j; i++; } else if (j > 0) { j = prefix[1]; } else { prefix[i] = 0; i++; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or braces instead of square brackets for array access.
Using j+1 instead of j-1.
✗ Incorrect
When characters don't match and j > 0, we update j to prefix[j-1] to try shorter prefix suffix.
4fill in blank
hardFill both blanks to complete the KMP search loop that finds pattern in text.
DSA Java
while (i < text.length()) { if (text.charAt(i) == pattern.charAt(j)) { i++; j++; if (j == [1]) { System.out.println("Pattern found at index " + (i - j)); j = prefix[2]; } } else if (j > 0) { j = prefix[j - 1]; } else { i++; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using text.length() instead of pattern.length() for comparison.
Resetting j to prefix[i] instead of prefix[j-1].
✗ Incorrect
When j equals pattern length, a full match is found. Then j is reset to prefix[j-1] to continue searching.
5fill in blank
hardFill all three blanks to build the prefix array using the KMP preprocessing function.
DSA Java
public int[] buildPrefixArray(String pattern) {
int[] prefix = new int[pattern.length()];
int i = 1, j = 0;
while (i < [1]) {
if (pattern.charAt(i) == pattern.charAt(j)) {
j++;
prefix[i] = [2];
i++;
} else if (j > 0) {
j = prefix[3];
} else {
prefix[i] = 0;
i++;
}
}
return prefix;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong loop condition.
Assigning prefix[i] wrong value.
Incorrect array index for updating j.
✗ Incorrect
The loop runs while i < pattern length. When characters match, prefix[i] = j. When mismatch and j > 0, j is updated to prefix[j-1].
