Searching Algorithms

Last Updated :
Discuss
Comments

Question 1

What is the worst-case time complexity of linear search on an array of size n?

  • O(1)

  • O(log n)

  • O(n)

  • O(n log n)

Question 2

What will be the output of the following code?

C
int arr[] = {1,3,5,7,9};
int l = 0, r = 4, x = 6, ans = -1;
while (l <= r) {
    int m = (l + r) / 2;
    if (arr[m] < x) l = m + 1;
    else if (arr[m] > x) r = m - 1;
    else { ans = m; break; }
}
printf("%d\n", ans);


  • 2

  • -1

  • 3

  • 1

Question 3

Ternary search is suitable for finding maximum of a function if it is:

  • Monotonic

  • Unimodal (first increasing then decreasing)

  • Arbitrary

  • Constant

Question 4

In C++ STL terms, lower_bound(v.begin(), v.end(), x) returns:

  • First position > x

  • First position ≥ x

  • First position < x

  • Last position ≤ x

Question 5

What will be output of following code?

C
int arr[] = {2, 4, 6, 8, 10};
int l = 0, r = 4, x = 8, ans = -1;
while (l <= r) {
    int m = l + (r - l) / 2;
    if (arr[m] == x) { ans = m; break; }
    if (arr[m] < x) l = m + 1;
    else r = m - 1;
}
printf("%d\n", ans);


  • 2

  • 3

  • -1

  • 4

Question 6

You have an array of size n−1 containing distinct numbers from 1 to n with one missing. Which binary-search condition finds the missing in O(log n)?

  • if (arr[mid] == mid+1) go right

  • if (arr[mid] > mid+1) go left

  • both 1 and 2

  • neither, use hash

Question 7

What will be output of following code?

C
int a[] = {4,1,2,1,2};
int res = 0;
for (int i = 0; i < 5; i++) res ^= a[i];
printf("%d\n", res);


  • 4

  • 1

  • 0

  • 2

Question 8

What will be output of following code?

C
#include <stdio.h>

int upper_bound(int arr[], int n, int x) {
    int l = 0, r = n;
    while (l < r) {
        int m = (l + r) / 2;
        if (arr[m] <= x) l = m + 1;
        else r = m;
    }
    return l;
}

int main(void) {
    int a[] = {2,4,4,4,6,8};
    printf("%d\n", upper_bound(a, 6, 4));
    return 0;
}


  • 1

  • 4

  • 5

  • 3

Question 9

Which precondition is necessary for binary search to work correctly?

  • The array must contain only positive numbers

  • The array must be sorted

  • All elements must be distinct

  • The array size must be a power of two

Question 10

What is the best-case time complexity of binary search on n elements?

  • O(1)

  • O(logn)

  • O(nlogn)

  • O(n)

There are 15 questions to complete.

Take a part in the ongoing discussion