Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the LPS array with zeros.
DSA Javascript
const lps = new Array(pattern.length).fill([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Initializing LPS with ones or negative numbers.
Leaving LPS uninitialized.
✗ Incorrect
The LPS (Longest Prefix Suffix) array should be initialized with zeros to start computing prefix lengths.
2fill in blank
mediumComplete the while loop condition to compute the LPS array correctly.
DSA Javascript
while (len > 0 && pattern[len] !== pattern[[1]]) { len = lps[len - 1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using undefined variables like 'j' or 'pos'.
Confusing the index variables.
✗ Incorrect
The variable 'i' is used as the current index in the pattern while computing LPS.
3fill in blank
hardFix the error in the KMP search loop condition to avoid infinite loops.
DSA Javascript
while (i < text.length) { if (pattern[j] === text[i]) { i++; j++; if (j === pattern.length) { result.push(i - j); j = [1]; } } else if (j > 0) { j = lps[j - 1]; } else { i++; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting j to 1 or lps[j], causing incorrect matching.
Not resetting j, causing infinite loops.
✗ Incorrect
After finding a match, reset j to 0 to continue searching for other matches.
4fill in blank
hardFill both blanks to correctly update the LPS array inside the computeLPS function.
DSA Javascript
if (pattern[i] === pattern[[1]]) { len++; lps[[2]] = len; i++; } else { // handle mismatch }
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning lps[len] instead of lps[i].
Using wrong indices for comparison.
✗ Incorrect
When characters match, increase len and assign it to lps at index i, then move i forward.
5fill in blank
hardFill all three blanks to complete the KMP search function's main loop correctly.
DSA Javascript
while (i < text.length) { if (pattern[[1]] === text[[2]]) { i++; j++; if (j === pattern.length) { result.push(i - j); j = [3]; } } else if (j > 0) { j = lps[j - 1]; } else { i++; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping i and j in comparisons.
Not resetting j properly after a match.
✗ Incorrect
Compare pattern[j] with text[i], increment both indices on match, and reset j to 0 after a full match.
