Data Structures & AlgorithmsHardProduct company OA · Infosys pattern
Binary search finds the index of the minimum of the rotated sorted array [15, 18, 22, 3, 6, 9, 12] using: mid = (lo + hi) / 2; if a[mid] > a[hi] then lo = mid + 1 else hi = mid; stop when lo == hi. What index is returned, and how many loop iterations run?
- A. index 3, 2 iterations
- B. index 4, 3 iterations
- C. index 0, 3 iterations
- D. index 3, 3 iterations
Correct answer: D. index 3, 3 iterations
lo=0, hi=6: mid 3, a[3] = 3 ≤ 12 → hi = 3. lo=0, hi=3: mid 1, 18 > 3 → lo = 2. lo=2, hi=3: mid 2, 22 > 3 → lo = 3 = hi. Three iterations, returning index 3. Stopping as soon as a[mid] is the minimum (after the first probe) gives '2 iterations', but this loop only stops when lo == hi. Comparing with a[hi] (not a[lo]) is what makes the rule work for both rotated and unrotated arrays.
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
- The sorted array [3, 4, 7, 10, 11] contains some positive integers. What is the 4th positive integer MISSING from it?
- For [2, 3, 0, 4], out[i] is the product of all elements except a[i], computed with prefix and suffix products (no division). What is out?
- The intervals [1, 4], [6, 8], [2, 3], [8, 10], [12, 13] are sorted by start and merged (intervals that touch at an endpoint also merge)…
- A 'leader' is an element strictly greater than every element to its right (the last element is always a leader). Scanning from the right…
- The words stop, pots, opts, post, tops, spot, pot, top are grouped so that anagrams share a group (key = the sorted letters). How many…
- A stack is built from two queues with a costly push: enqueue x into the empty queue Q2, move every element of Q1 into Q2 one by one, then…