Data Structures & AlgorithmsHardProduct-company MCQ pattern
What does this function return for a = [1, 3, 3, 3, 5, 7] with x = 3 and with x = 4?
What does this function return for a = [1, 3, 3, 3, 5, 7] with x = 3 and with x = 4?
def g(a, x):
lo, hi = 0, len(a) - 1
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < x:
lo = mid + 1
else:
hi = mid
return lo- A. 1 and 4
- B. 2 and 4
- C. 3 and 4
- D. 1 and 3
Correct answer: A. 1 and 4
This is a lower bound: it returns the first index whose value is ≥ x. The first 3 is at index 1, and the first value ≥ 4 is 5 at index 4. Thinking it returns 'mid when found' gives 2, the first midpoint.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- while (lo <= hi) binary search runs on a sorted array of 31 elements for a key LARGER than every element. How many times does the loop…
- A dynamic array starts with capacity 1 and doubles its capacity (copying all current elements) whenever an insert finds it full. How many…
- A stack-based checker is run on four strings. Which one is balanced?
- A circular queue in an array of size 6 uses front (index of the first item) and rear (index of the next free slot), both starting at 0…
- A 2-D array A[10][20] (indices from 0) of 4-byte integers is stored in COLUMN-major order starting at address 1000. What is the address of…
- Only the lower triangle (including the diagonal) of a 10 × 10 matrix is stored, row by row, in a 1-D array starting at address 2000, with…