Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the index of the target if found, or -1 if not found.
DSA Javascript
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === [1]) {
return i;
}
}
return -1;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the loop index i instead of the target for comparison.
Comparing arr[i] with arr instead of target.
✗ Incorrect
The code compares each element arr[i] with the target value to find a match.
2fill in blank
mediumComplete the code to search through the array and return true if the target exists.
DSA Javascript
function contains(arr, target) {
for (let i = 0; i < [1]; i++) {
if (arr[i] === target) {
return true;
}
}
return false;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using target.length which is incorrect because target is a value, not an array.
Using arr instead of arr.length in the loop condition.
✗ Incorrect
The loop must run from 0 to arr.length to check every element.
3fill in blank
hardFix the error in the code to correctly perform linear search and return the index or -1.
DSA Javascript
function linearSearch(arr, target) {
let index = -1;
for (let i = 0; i <= [1]; i++) {
if (arr[i] === target) {
index = i;
break;
}
}
return index;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr.length causes index out of range error.
Using arr.length + 1 causes runtime error.
✗ Incorrect
The loop should run while i is less than or equal to arr.length - 1 to avoid going out of bounds.
4fill in blank
hardFill both blanks to create a function that returns the index of the target or -1 if not found.
DSA Javascript
function search(arr, target) {
for (let i = 0; i [1] arr.length; i++) {
if (arr[i] [2] target) {
return i;
}
}
return -1;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= in the loop condition causes out of bounds error.
Using !== instead of === in the if condition.
✗ Incorrect
The loop runs while i is less than arr.length, and inside the loop, we check if arr[i] equals the target.
5fill in blank
hardFill all three blanks to create a function that returns true if the target is found, false otherwise.
DSA Javascript
function exists(arr, target) {
for (let [1] = 0; [2] < arr.length; [3]++) {
if (arr[i] === target) {
return true;
}
}
return false;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in loop parts causes errors.
Using 'j' in one part and 'i' in others causes reference errors.
✗ Incorrect
The loop variable is 'i' used consistently in initialization, condition, and increment.