Data Structures & AlgorithmsHardGATE CS · DSA
Binary search for first/last occurrence runs on the sorted array [8, 9, 15, 18, 18, 20, 21, 22] for target 18. What (first index, last index) pair (0-based) does it return?
- A. (3, 3)
- B. (3, 5)
- C. (2, 4)
- D. (3, 4)
Correct answer: D. (3, 4)
The first-occurrence search keeps moving left after a match (hi = mid − 1) to find the earliest index, and the last-occurrence search keeps moving right (lo = mid + 1) to find the latest; for 18 in this array that gives first index 3 and last index 4.
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
- What is the sum of the minimum element over every contiguous subarray of [4, 1, 1, 2, 3, 3, 7, 3]?
- What does this loop-counting code print? (Python) python n, c = 42, 0 i = 1 while i < n: j = i while j < n: c += 1 j = 2 i += 1 print(c)
- A circular queue of capacity 5 starts empty and runs this sequence in order: enqueue(6), dequeue(), enqueue(4), enqueue(6), dequeue()…
- The Boyer–Moore majority vote algorithm (candidate/counter, no verification pass) runs on [9, 6, 6, 6, 6, 5, 6]. What candidate and final…
- Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the…
- What does this loop-counting code print? (Python) python n, c = 22, 0 i = 1 while i < n: j = i while j < n: c += 1 j = 2 i += 1 print(c)