Challenge - 5 Problems
Linear Search Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Linear Search for Existing Element
What is the output of the following JavaScript code that performs a linear search for the number 7 in the array?
DSA Javascript
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
const numbers = [3, 5, 7, 9, 11];
console.log(linearSearch(numbers, 7));Attempts:
2 left
💡 Hint
Remember that array indexes start at 0 in JavaScript.
✗ Incorrect
The function checks each element in order. The number 7 is at index 2 in the array, so the function returns 2.
❓ Predict Output
intermediate2:00remaining
Output When Element is Not Found
What does the following code print when searching for 10 in the array?
DSA Javascript
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
const numbers = [1, 2, 3, 4, 5];
console.log(linearSearch(numbers, 10));Attempts:
2 left
💡 Hint
If the target is not in the array, what does the function return?
✗ Incorrect
Since 10 is not in the array, the loop finishes without finding it, so the function returns -1.
🧠 Conceptual
advanced1:30remaining
Time Complexity of Linear Search
What is the worst-case time complexity of the linear search algorithm when searching in an array of size n?
Attempts:
2 left
💡 Hint
Think about how many elements the algorithm might check in the worst case.
✗ Incorrect
In the worst case, linear search checks every element once, so the time complexity is O(n).
🔧 Debug
advanced2:00remaining
Identify the Bug in Linear Search Implementation
What is the output of the following code when searching for 4 in the array?
DSA Javascript
function linearSearch(arr, target) {
for (let i = 0; i <= arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
const numbers = [1, 2, 3, 4, 5];
console.log(linearSearch(numbers, 4));Attempts:
2 left
💡 Hint
Check the loop condition and array indexing carefully.
✗ Incorrect
The code returns 3 because 4 is found at index 3 before the out-of-bounds access. However, the loop uses i <= arr.length, which is a bug that accesses arr[arr.length] (undefined) if the target is not found early.
🚀 Application
expert1:30remaining
Number of Comparisons in Linear Search
If you perform a linear search for the target value 8 in the array [2, 4, 6, 8, 10], how many comparisons does the algorithm make before finding the target?
Attempts:
2 left
💡 Hint
Count how many elements the algorithm checks until it finds 8.
✗ Incorrect
The algorithm checks elements at indexes 0, 1, 2, and 3 before finding 8, so it makes 4 comparisons.