Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to perform a linear search that returns the index of the target or -1 if not found.
DSA Java
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == [1]) {
return i;
}
}
return -1;
}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 the index.
2fill in blank
mediumComplete the code to perform a binary search on a sorted array to find the target index or return -1 if not found.
DSA Java
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == [1]) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing arr[mid] with mid instead of target.
Using left or right instead of target for comparison.
✗ Incorrect
The binary search compares the middle element arr[mid] with the target to decide the search direction.
3fill in blank
mediumComplete the code to return the worst-case time complexity of linear search.
DSA Java
public static String linearTimeComplexity() {
return "[1]";
}Attempts:
3 left
💡 Hint
Common Mistakes
Confusing with best case O(1).
Thinking it is quadratic O(n^2).
✗ Incorrect
Linear search worst case requires checking all n elements, O(n). This highlights the real cost difference for large arrays compared to binary search O(log n).
4fill in blank
hardFix the error in the binary search code: complete the condition to correctly update the left pointer when target is greater than mid element.
DSA Java
if (arr[mid] < [1]) { left = mid + 1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using mid instead of target in the comparison.
Using left or right instead of target.
✗ Incorrect
When the middle element is less than the target, move the left pointer to mid + 1 to search the right half.
5fill in blank
hardComplete the code to return the worst-case time complexity of binary search on a sorted array.
DSA Java
public static String binaryTimeComplexity() {
return "[1]";
}Attempts:
3 left
💡 Hint
Common Mistakes
Confusing with linear O(n).
Thinking it is quadratic O(n^2).
✗ Incorrect
Binary search halves the search space each step, leading to O(log n) worst-case time. For large n (e.g., 1 million), log n ≈ 20 vs linear's 1 million operations.
