Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the pattern exists in the text using includes method.
DSA Typescript
const text = "hello world"; const pattern = "world"; const found = text.[1](pattern); console.log(found);
Attempts:
3 left
💡 Hint
Common Mistakes
Using indexOf returns a number, not a boolean.
Using search returns an index or -1, not a boolean.
✗ Incorrect
The includes() method returns true if the pattern is found in the text, otherwise false.
2fill in blank
mediumComplete the code to find the first index of the pattern in the text.
DSA Typescript
const text = "abracadabra"; const pattern = "cad"; const index = text.[1](pattern); console.log(index);
Attempts:
3 left
💡 Hint
Common Mistakes
Using includes returns boolean, not index.
Using match returns an array, not index.
✗ Incorrect
indexOf returns the first index where the pattern starts or -1 if not found.
3fill in blank
hardFix the error in the code to correctly find all occurrences of the pattern using RegExp.
DSA Typescript
const text = "banana"; const pattern = /an/g; const matches = text.[1](pattern); console.log(matches);
Attempts:
3 left
💡 Hint
Common Mistakes
Using matchAll returns an iterator, not an array.
Using search returns only first match index.
✗ Incorrect
The match() method with global flag returns all matches as an array.
4fill in blank
hardFill both blanks to create a function that returns all start indices of the pattern in the text.
DSA Typescript
function findAllIndices(text: string, pattern: string): number[] {
const indices: number[] = [];
let pos = text.[1](pattern);
while (pos !== [2]) {
indices.push(pos);
pos = text.indexOf(pattern, pos + 1);
}
return indices;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using includes returns boolean, not index.
Comparing pos to 0 instead of -1 causes infinite loop.
✗ Incorrect
indexOf finds the first occurrence; -1 means no more occurrences.
5fill in blank
hardFill all three blanks to create a function that returns a map of each pattern to its count in the text.
DSA Typescript
function countPatterns(text: string, patterns: string[]): Record<string, number> {
const counts: Record<string, number> = {};
for (const pattern of patterns) {
counts[[1]] = 0;
let pos = text.indexOf(pattern);
while (pos !== [2]) {
counts[pattern] += [3];
pos = text.indexOf(pattern, pos + 1);
}
}
return counts;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using text as key instead of pattern.
Incrementing count by wrong value.
Checking pos against 0 instead of -1.
✗ Incorrect
Use pattern as key, -1 to check no more matches, and increment count by 1.
