Challenge - 5 Problems
Linear Search Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of linear search when element is present
What is the output of the following Java code that performs a linear search for the number 7 in the array?
DSA Java
public class Main { public static int linearSearch(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; } } return -1; } public static void main(String[] args) { int[] numbers = {3, 5, 7, 9, 11}; int index = linearSearch(numbers, 7); System.out.println(index); } }
Attempts:
2 left
💡 Hint
Remember that array indices start at 0 in Java.
✗ Incorrect
The element 7 is at index 2 in the array {3, 5, 7, 9, 11}. The linear search returns the index where the target is found.
❓ Predict Output
intermediateOutput when element is not found in linear search
What will the following Java code print when searching for 10 in the array?
DSA Java
public class Main { public static int linearSearch(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; } } return -1; } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int index = linearSearch(numbers, 10); System.out.println(index); } }
Attempts:
2 left
💡 Hint
If the element is not found, what does the method return?
✗ Incorrect
The method returns -1 when the target is not found in the array.
🔧 Debug
advancedIdentify the error in linear search implementation
What error will the following Java code produce when compiled or run?
DSA Java
public class Main { public static int linearSearch(int[] arr, int target) { int i = 0; while (i <= arr.length) { if (arr[i] == target) { return i; } i++; } return -1; } public static void main(String[] args) { int[] numbers = {1, 3, 5}; System.out.println(linearSearch(numbers, 99)); } }
Attempts:
2 left
💡 Hint
Check the loop condition and array indexing carefully.
✗ Incorrect
The loop condition uses i <= arr.length, which causes the index to go out of bounds when i equals arr.length.
🧠 Conceptual
advancedTime complexity of linear search
What is the worst-case time complexity of linear search on an array of size n?
Attempts:
2 left
💡 Hint
Think about how many elements might be checked in the worst case.
✗ Incorrect
Linear search checks each element one by one, so in the worst case it checks all n elements, making it O(n).
🚀 Application
expertResult of linear search on a linked list
Given a singly linked list with nodes containing values [4, 8, 15, 16, 23, 42], what is the output of a linear search for the value 16? The search returns the zero-based position of the node or -1 if not found.
Attempts:
2 left
💡 Hint
Count nodes starting from zero at the head.
✗ Incorrect
The value 16 is at the fourth node, which is index 3 starting from zero.
