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 on Array
What is the output of the following C++ code that performs a linear search for the value 7 in the array?
DSA C++
int arr[] = {3, 5, 7, 9, 11}; int n = 5; int target = 7; int index = -1; for (int i = 0; i < n; i++) { if (arr[i] == target) { index = i; break; } } std::cout << index << std::endl;
Attempts:
2 left
💡 Hint
Remember that array indexing in C++ starts at 0.
✗ Incorrect
The value 7 is at index 2 in the array. The loop stops when it finds 7 and prints 2.
❓ Predict Output
intermediate2:00remaining
Linear Search Result When Target Not Found
What will be the output of this C++ code when searching for 10 in the array?
DSA C++
int arr[] = {1, 2, 3, 4, 5}; int n = 5; int target = 10; int index = -1; for (int i = 0; i < n; i++) { if (arr[i] == target) { index = i; break; } } std::cout << index << std::endl;
Attempts:
2 left
💡 Hint
If the target is not found, the index remains -1.
✗ Incorrect
Since 10 is not in the array, the loop never updates index from -1, so -1 is printed.
🔧 Debug
advanced2:00remaining
Find the Bug in Linear Search Implementation
This code is supposed to perform a linear search but does not work correctly. What is the output and why?
DSA C++
int arr[] = {2, 4, 6, 8}; int n = 4; int target = 10; int index = -1; for (int i = 1; i <= n; i++) { if (arr[i] == target) { index = i; break; } } std::cout << index << std::endl;
Attempts:
2 left
💡 Hint
Check the loop boundaries and array indexing carefully.
✗ Incorrect
The loop accesses arr[4] when i == 4, which is out of bounds causing undefined behavior or runtime error.
🧠 Conceptual
advanced1:00remaining
Time Complexity of Linear Search
What is the worst-case time complexity of linear search on an array of size n?
Attempts:
2 left
💡 Hint
Consider how many elements you might check if the target is not present.
✗ Incorrect
In the worst case, linear search checks every element once, so it takes O(n) time.
🚀 Application
expert3:00remaining
Linear Search on Linked List
Given a singly linked list with nodes containing values [10, 20, 30, 40], what is the output of searching for 30 using linear search?
DSA C++
struct Node {
int data;
Node* next;
};
Node* head = new Node{10, nullptr};
head->next = new Node{20, nullptr};
head->next->next = new Node{30, nullptr};
head->next->next->next = new Node{40, nullptr};
int target = 30;
int index = 0;
Node* current = head;
while (current != nullptr) {
if (current->data == target) {
break;
}
current = current->next;
index++;
}
if (current == nullptr) index = -1;
std::cout << index << std::endl;Attempts:
2 left
💡 Hint
Count nodes starting from 0 until you find the target value.
✗ Incorrect
The value 30 is in the third node, which is index 2 starting from 0.