Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the prefix array with zeros.
DSA C#
int[] prefix = new int[pattern.Length]; for (int i = 1; i < pattern.Length; i++) { prefix[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing prefix array with ones or negative values.
Using the loop index i as initial value.
✗ Incorrect
The prefix array is initialized with zeros to start building the longest prefix suffix values.
2fill in blank
mediumComplete the code to update the prefix array when characters match.
DSA C#
if (pattern[i] == pattern[length]) { length++; prefix[i] = [1]; i++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning i or character instead of length.
Assigning zero which resets prefix array incorrectly.
✗ Incorrect
When characters match, prefix[i] is updated to the current length of the longest prefix suffix.
3fill in blank
hardFix the error in the while loop condition to avoid infinite loops.
DSA C#
while (i < text.Length) { if (pattern[j] == text[i]) { i++; j++; } else if (j != 0) { j = prefix[[1] - 1]; } else { i++; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using i or text.Length instead of j in prefix indexing.
Using pattern.Length which is out of prefix array bounds.
✗ Incorrect
When mismatch occurs and j is not zero, we update j to prefix[j-1] to avoid rechecking characters.
4fill in blank
hardFill both blanks to correctly build the prefix array in the preprocessing step.
DSA C#
int length = 0; int i = 1; while (i < pattern.Length) { if (pattern[i] == pattern[[1]]) { length++; prefix[i] = length; i++; } else { if (length != 0) { length = prefix[[2] - 1]; } else { prefix[i] = 0; i++; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using i or pattern.Length instead of length.
Using prefix.Length which is not the correct index.
✗ Incorrect
Both blanks use 'length' to compare and update the prefix array correctly.
5fill in blank
hardFill all three blanks to complete the KMP search function that returns the starting indices of matches.
DSA C#
List<int> result = new List<int>(); int i = 0, j = 0; while (i < text.Length) { if (pattern[j] == text[i]) { i++; j++; } if (j == [1]) { result.Add(i - j); j = prefix[[2]]; } else if (i < text.Length && pattern[j] != text[i]) { if (j != 0) { j = prefix[[3]]; } else { i++; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using j or i instead of pattern.Length for match check.
Incorrect prefix indexing causing errors.
✗ Incorrect
When full pattern matched (j == pattern.Length), add index and update j using prefix[j-1]. On mismatch, update j similarly.
