Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start the outer loop from the first character of the text.
DSA Javascript
for (let i = [1]; i <= text.length - pattern.length; i++) { // matching logic }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop from 1 misses checking the pattern at the very beginning of the text.
Starting loop from pattern.length skips initial positions.
✗ Incorrect
The outer loop should start from index 0 to check all possible starting positions in the text.
2fill in blank
mediumComplete the code to start the inner loop from the first character of the pattern.
DSA Javascript
for (let j = [1]; j < pattern.length; j++) { if (text[i + j] !== pattern[j]) { break; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting inner loop from 1 skips the first character of the pattern.
Using text.length as start index causes out-of-range errors.
✗ Incorrect
The inner loop should start from 0 to compare each character of the pattern from the beginning.
3fill in blank
hardFix the error in the condition to check if the pattern matches completely.
DSA Javascript
if (j === [1]) { result.push(i); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pattern.length - 1 causes off-by-one error.
Comparing j to text.length is incorrect.
✗ Incorrect
When j equals pattern.length, it means all characters matched successfully.
4fill in blank
hardFill both blanks to complete the naive string matching function.
DSA Javascript
function naiveSearch(text, pattern) {
const result = [];
for (let i = [1]; i <= text.length - pattern.length; i++) {
let j = 0;
for (; j < [2]; j++) {
if (text[i + j] !== pattern[j]) {
break;
}
}
if (j === pattern.length) {
result.push(i);
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting outer loop at 1 misses first position.
Using text.length in inner loop causes errors.
✗ Incorrect
The outer loop starts at 0, and the inner loop runs up to pattern.length to check all characters.
5fill in blank
hardFill all three blanks to return all starting indices where the pattern is found in the text.
DSA Javascript
function naiveSearch(text, pattern) {
const result = [];
for (let i = [1]; i <= text.length - pattern.length; i++) {
let j = 0;
for (; j < [2]; j++) {
if (text[i + j] !== pattern[j]) {
break;
}
}
if (j === [3]) {
result.push(i);
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using text.length instead of pattern.length in inner loop or match check.
Starting outer loop at 1 misses first position.
✗ Incorrect
Start outer loop at 0, inner loop runs to pattern.length, and full match is when j equals pattern.length.
