Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the prefix array with zeros.
DSA Go
prefix := make([]int, len(pattern)) for i := range prefix { prefix[i] = [1] }
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing prefix array with ones or negative values causes incorrect matching.
Using loop index 'i' as initial value is wrong.
✗ Incorrect
The prefix array stores lengths of longest proper prefix which is also suffix. It starts with zeros.
2fill in blank
mediumComplete the code to update the prefix length when characters match.
DSA Go
if pattern[i] == pattern[j] { j = j + [1] prefix[i] = j }
Attempts:
3 left
💡 Hint
Common Mistakes
Incrementing by zero or negative values causes no progress.
Using loop index 'i' instead of 1 is incorrect.
✗ Incorrect
When characters match, increase prefix length by 1 and assign it.
3fill in blank
hardFix the error in the loop condition to avoid index out of range.
DSA Go
for i := 1; i < [1]; i++ { // build prefix array }
Attempts:
3 left
💡 Hint
Common Mistakes
Using text length causes index errors.
Using len(pattern) - 1 misses last character.
✗ Incorrect
The prefix array is built for the pattern length, so loop must run till len(pattern).
4fill in blank
hardFill both blanks to correctly update the index j when characters mismatch during prefix building.
DSA Go
for i := 1; i < len(pattern); i++ { for j > 0 && pattern[i] != pattern[j] { j = prefix[1] } if pattern[i] == pattern[j] { j = j + [2] } prefix[i] = j }
Attempts:
3 left
💡 Hint
Common Mistakes
Using prefix[j] instead of prefix[j-1] causes infinite loops.
Incrementing j by 0 causes no progress.
✗ Incorrect
When mismatch occurs, j moves to prefix[j-1]. When match occurs, j increments by 1.
5fill in blank
hardFill all three blanks to correctly implement the main KMP search loop.
DSA Go
for i := 0; i < len(text); i++ { for j > 0 && text[i] != pattern[1] { j = prefix[2] } if text[i] == pattern[3] { j++ } if j == len(pattern) { fmt.Println("Pattern found at index", i - j + 1) j = prefix[j-1] } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices causes incorrect matching.
Not updating j after finding a pattern causes missed matches.
✗ Incorrect
Use pattern[j] to compare characters, fallback to prefix[j-1] on mismatch, and increment j on match.
