0
0
DSA C++programming~10 mins

Binary Search vs Linear Search Real Cost Difference in DSA C++ - Interactive Comparison Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to perform a linear search for a target value in an array.

DSA C++
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == [1]) {
            return i;
        }
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
Ai
Btarget
Cn
Darr
Attempts:
3 left
💡 Hint
Common Mistakes
Using the loop index instead of the target value in the comparison.
Comparing with the array name instead of an element.
2fill in blank
medium

Complete the code to perform a binary search on a sorted array.

DSA C++
int binarySearch(int arr[], int left, int right, int target) {
    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;
}
Drag options to blanks, or click blank then click option'
Amid
Bleft
Ctarget
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with the wrong variable like left or right indices.
Using the middle index instead of the target value.
3fill in blank
hard

Fix the error in the binary search condition to correctly update the search range.

DSA C++
if (arr[mid] < [1]) {
    left = mid + 1;
} else {
    right = mid - 1;
}
Drag options to blanks, or click blank then click option'
Atarget
Bleft
Cright
Dmid
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with the left or right index instead of the target value.
Using the middle index instead of the target value.
4fill in blank
hard

Fill both blanks to create a dictionary that maps each element to its index, then check if target exists.

DSA C++
std::unordered_map<int, int> indexMap;
for (int i = 0; i < n; i++) {
    indexMap[[1]] = i;
}
if (indexMap.find([2]) != indexMap.end()) {
    return indexMap[[2]];
} else {
    return -1;
}
Drag options to blanks, or click blank then click option'
Aarr[i]
Btarget
Ci
Darr
Attempts:
3 left
💡 Hint
Common Mistakes
Using the index i as the key instead of the element.
Checking the map with the index instead of the target.
5fill in blank
hard

Fill all three blanks to create a map comprehension that stores elements greater than 10 with their squares.

DSA C++
std::unordered_map<int, int> result;
for (int [1] = 0; [1] < [3]; [1]++) {
    if (arr[[1]] [2] 10) {
        result[arr[[1]]] = arr[[1]] * arr[[1]];
    }
}
Drag options to blanks, or click blank then click option'
Ai
B>
C<
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong comparison operator like <.
Using the wrong loop variable or loop condition.