Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the prefix array with zeros.
DSA Typescript
const prefix: number[] = new Array(pattern.length).fill([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Initializing prefix array with ones or negative numbers.
Using pattern length as initial value.
✗ Incorrect
The prefix array is initialized with zeros to store the longest prefix suffix lengths.
2fill in blank
mediumComplete the code to update the prefix index when characters match.
DSA Typescript
if (pattern[i] === pattern[j]) { j++; prefix[i] = [1]; i++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning i instead of j to prefix[i].
Assigning zero incorrectly.
✗ Incorrect
When characters match, prefix[i] is set to j, the length of the current longest prefix suffix.
3fill in blank
hardFix the error in the while loop condition to avoid infinite loop.
DSA Typescript
while (i < pattern.length) { if (pattern[i] === pattern[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 curly braces or square brackets incorrectly.
Using j + 1 which causes index error.
✗ Incorrect
When mismatch occurs and j > 0, j is updated to prefix[j - 1] to check previous longest prefix suffix.
4fill in blank
hardFill both blanks to complete the search loop that finds pattern matches in text.
DSA Typescript
while (i < text.length) { if (pattern[j] === text[i]) { i++; j++; } if (j === [1]) { result.push(i - j); j = prefix[2]; } else if (i < text.length && pattern[j] !== text[i]) { if (j !== 0) { j = prefix[j - 1]; } else { i++; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing j to text length instead of pattern length.
Using prefix.length incorrectly.
✗ Incorrect
j is compared to pattern.length to check full match; j is reset to prefix[j - 1] to continue search.
5fill in blank
hardFill all three blanks to complete the function that returns all starting indices of pattern matches in text.
DSA Typescript
function kmpSearch(text: string, pattern: string): number[] {
const prefix: number[] = new Array(pattern.length).fill(0);
let i = 1, j = 0;
while (i < pattern.length) {
if (pattern[i] === pattern[j]) {
j++;
prefix[i] = j;
i++;
} else if (j > 0) {
j = prefix[1];
} else {
prefix[i] = 0;
i++;
}
}
const result: number[] = [];
i = 0;
j = 0;
while (i < text.length) {
if (pattern[j] === text[i]) {
i++;
j++;
}
if (j === [2]) {
result.push(i - j);
j = prefix[3];
} else if (i < text.length && pattern[j] !== text[i]) {
if (j !== 0) {
j = prefix[j - 1];
} else {
i++;
}
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using text.length instead of pattern.length for match check.
Incorrect indexing with prefix array.
✗ Incorrect
j is updated to prefix[j - 1] on mismatch; full match is when j equals pattern.length; after match, j resets to prefix[j - 1].
