Data Structures & AlgorithmsModerateProduct company OA · Amazon/Microsoft-style OA
Array a = [6, 1, 8, 3, 9, 4, 2, 7, 5] has distinct values. How many ordered pairs (i, j) with i != j satisfy a[i] - a[j] = 4?
- A. 10
- B. 6
- C. 5
- D. 7
Correct answer: C. 5
Store the values in a set and, for each x, check whether x - 4 is present; each hit is one ordered pair (i, j). The difference is positive in one direction only, so no pair is counted twice.
More Coding Interview Problems questions
- For a = [1, 2, 3, 4, 5, 6, 7, 8], how many contiguous subarrays have a sum that is a multiple of 5?
- Array a = [2, 1, 5, 2, 3, 1, 4] has only positive values. How many non-empty contiguous subarrays have sum at most 9?
- Sorted values [1, 4, 6, 9, 13, 14, 18, 22] must be split into the fewest contiguous groups so that in every group the largest value minus…
- Two multisets A = {7, 2, 9, 4, 5} and B = {3, 8, 1, 6, 10} are matched one-to-one, pairing each element of A with exactly one element of…
- How many permutations of (1, 2, 3, 4, 5) have every pair of adjacent entries differing by at least 2? Solve with a bitmask DP that…
- How many integers x with 0 <= x <= 1000 have exactly four 1-bits in their binary representation?