Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print?
Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print?
def two_sum_sorted(a, t):
i, j = 0, len(a) - 1
while i <= j:
s = a[i] + a[j]
if s == t: return (i, j)
if s < t: i += 1
else: j -= 1
return None
print(two_sum_sorted([1, 3, 5, 8], 10), two_sum_sorted([1, 3, 6], 12))What is printed?- A. (2, 2) (2, 2)
- B. None None
- C. (1, 3) None
- D. (2, 2) None
Correct answer: A. (2, 2) (2, 2)
With i <= j the pointers are allowed to meet, so one element is used twice. [1, 3, 5, 8], t = 10: 9 → i++, 11 → j−−, 8 → i++, then i = j = 2 and 5 + 5 = 10 is 'found'. Likewise 6 + 6 = 12. The loop must be while i < j to require two different positions (then both calls return None). O(n).
More Coding Interview Problems questions
- Problem: A ride app must repeatedly add drivers with ratings and remove the highest-rated driver, n = 10⁵ operations. Which data structure…
- Problem: A leaderboard needs: insert a score, delete a score, and 'how many scores are below x?' – all online, 10⁵ operations, scores up…
- Problem: A browser keeps history so that 'back' and 'forward' work like the real buttons, and visiting a new page clears the forward…
- Problem: For a stream of n = 10⁶ (user, timestamp) hits, answer 'how many hits in the last 300 seconds?' after each new hit (timestamps…
- Problem: Implement a set that supports insert, delete and getRandom (uniformly random element) all in average O(1). Which combination works?
- Problem: Support 'add number' and 'find a pair summing to t' where adds are 10⁵ and finds are rare, versus the opposite workload. Which…