Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit.
Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit.
def pairs_below(a, limit):
i, j, c = 0, len(a) - 1, 0
while i < j:
if a[i] + a[j] < limit:
c += j - i
i += 1
else:
j -= 1
return c
print(pairs_below([1, 3, 4, 6, 9], 10))What is printed?- A. 4
- B. 6
- C. 5
- D. 3
Correct answer: C. 5
If a[i] + a[j] < limit then a[i] pairs with every index i+1..j, so add j − i at once. Trace: 1 + 9 = 10 is not below the limit so j moves; 1 + 6 adds 3; 3 + 6 adds 2; 4 + 6 fails and the pointers meet: 5 pairs ((1,3),(1,4),(1,6),(3,4),(3,6)). Counting (1,9) as valid gives the trap 6. Adding 1 per step instead undercounts. O(n) after sorting.
More Coding Interview Problems questions
- Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance)…
- Problem: Find the length of the longest substring of a log line with no repeated character. python def longest(s): last = {} l = best = 0…
- Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none). python def minlen(a, s)…
- Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable. python def longestones(a, k): l =…
- Problem: Return the maximum of every window of size k in a stream of readings. python from collections import deque def winmax(a, k): dq…
- Problem: For n = 10⁶ readings and window size k = 10⁵, report every window maximum. Which approach fits the limits best?