Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the pattern matches the substring starting at index i.
DSA Typescript
if (text[i + j] !== pattern[j]) { return [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true instead of false on mismatch.
Returning null or undefined which are not boolean.
✗ Incorrect
If any character does not match, the function should return false indicating no match at this position.
2fill in blank
mediumComplete the code to return the starting index when the pattern is found.
DSA Typescript
if (j === pattern.length) { return [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Returning j which is the pattern length index.
Returning -1 which means not found.
✗ Incorrect
When all characters match, return the starting index i where the pattern begins.
3fill in blank
hardFix the error in the loop condition to avoid out-of-bound errors.
DSA Typescript
for (let i = 0; i <= text.length [1] pattern.length; i++) { // matching logic }
Attempts:
3 left
💡 Hint
Common Mistakes
Using + which causes index overflow.
Using * or / which are invalid here.
✗ Incorrect
We subtract pattern.length to ensure the pattern fits inside the text without overflow.
4fill in blank
hardFill both blanks to complete the nested loop for naive pattern matching.
DSA Typescript
for (let i = 0; i <= text.length [1] pattern.length; i++) { let j = 0; for (; j < pattern.length; j++) { if (text[i + j] !== pattern[j]) { break; } } if (j === [2]) { return i; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using + in outer loop limit causing overflow.
Comparing j to text.length instead of pattern.length.
✗ Incorrect
The outer loop stops at text.length - pattern.length. The inner loop compares up to pattern.length characters.
5fill in blank
hardFill all three blanks to complete the naive pattern matching function that returns -1 if not found.
DSA Typescript
function naiveSearch(text: string, pattern: string): number {
for (let i = 0; i <= text.length [1] pattern.length; i++) {
let j = 0;
for (; j < [2]; j++) {
if (text[i + j] !== pattern[j]) {
break;
}
}
if (j === [3]) {
return i;
}
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using text.length in inner loop or match check.
Using addition in outer loop limit.
✗ Incorrect
The outer loop limit subtracts pattern length. Both inner loop conditions and match check use pattern.length.
