Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Binary search on large indices in C++ (int is 32-bit).
Problem: Binary search on large indices in C++ (int is 32-bit).
int lo = 2000000000, hi = 2100000000; int bad = (lo + hi) / 2; // signed overflow int good = lo + (hi - lo) / 2; cout << bad << " " << good; // typical result on 2's-complement hardwareWhat is printed?
- A. -97483648 2050000000
- B. 2050000000 2050000000
- C. -2050000000 2050000000
- D. 97483648 2050000000
Correct answer: A. -97483648 2050000000
lo + hi = 4.1 × 10⁹ exceeds INT_MAX (≈ 2.147 × 10⁹). Signed overflow is undefined behaviour in C++; on typical hardware it wraps to −194967296, and halving gives −97483648 – a negative 'midpoint'. lo + (hi − lo)/2 never exceeds hi. This is why the safe formula is standard in binary search on the answer.
More Coding Interview Problems questions
- Problem: Find the celebrity (known by all, knows nobody) with O(n) calls to knows(a, b). python M = [[0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0…
- Problem: Delete exactly one element from a binary array and return the longest run of 1s that can remain. python def afterdelete(a): l =…
- Problem: Find the minimum number of railway platforms with a sweep line over arrival and departure events (a train arriving when another…
- Problem: Find how many numbers in 1..n have all distinct digits — the digit-DP-free shortcut for n = 10ᵏ uses counting. python def…
- Problem: Find the minimum window length in which every one of k distinct product IDs appears at least once (k = number of distinct values…
- Problem: Find the number of operations to reduce n to 1: if even halve it, else add or subtract 1 (choose optimally). python def steps(n)…