Question 1
EasyWhich condition must hold before binary search can be used on an array?
- A.
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Data Structures and Algorithms
Which condition must hold before binary search can be used on an array?
The array must be small
The array must have no negatives
The array must be sorted
The array must be stored in a linked list
Answer: C
Binary search discards half of the range on each comparison, which only works on sorted data.
In binary search, how many comparisons are needed in the worst case for 1024 elements?
About 10 (11 at most)
1024
512
32
Answer: A
log₂ 1024 = 10, so about 10 halvings reduce the range to one element.
What is the output of this code?
a = [1, 3, 5, 7, 9, 11]
lo, hi = 0, len(a) - 1
ans = -1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == 7:
ans = mid
break
elif a[mid] < 7:
lo = mid + 1
else:
hi = mid - 1
print(ans)
4
-1
Answer: D
The binary search finds 7 at index 3 of the sorted list.
What is the best-case time complexity of binary search?
O(n log n)
O(n)
O(1)
O(log n)
Answer: C
If the middle element is the target, it is found with one comparison.
Which search works on unsorted data?
Exponential search
Binary search
Linear search
Interpolation search
Answer: C
Linear search simply checks each element in turn.
Why is mid often computed as lo + (hi − lo) / 2 instead of (lo + hi) / 2?
To avoid integer overflow when lo and hi are large
It finds the last element
It is faster
It works on unsorted arrays
Answer: A
lo + hi can exceed the maximum int value in languages like C and Java.
What is the output of this code?
import bisect
print(bisect.bisect_left([1, 3, 5, 5, 7], 5))
4
1
Answer: D
bisect_left returns the first index where 5 could be inserted while keeping order: index 2.
Linear search looks for 15 in [4, 8, 15, 16]. How many comparisons are made?
1
3
2
4
Answer: B
It compares with 4, 8 and then 15, where it stops.
Binary search looks for 11 in [1, 3, 5, 7, 9, 11, 13]. Which element is compared first?
5
9
7
11
Answer: C
The middle of indices 0–6 is index 3, which holds 7.
Binary search starts with 16 elements. How many halvings reduce the range to a single element?
8
4
16
2
Answer: B
16 → 8 → 4 → 2 → 1: four halvings, since 2⁴ = 16.
2
3
3
2