Data Structures & AlgorithmsHardProduct company OA
Problem: A sensor array is 'steady' between positions i < j if a[j] − a[i] = j − i. Count steady pairs in O(n) by grouping a[i] − i.
Problem: A sensor array is 'steady' between positions i < j if a[j] − a[i] = j − i. Count steady pairs in O(n) by grouping a[i] − i.
from collections import Counter
def steady_pairs(a):
c = Counter(x - i for i, x in enumerate(a))
return sum(v * (v - 1) // 2 for v in c.values())
print(steady_pairs([3, 4, 1, 6, 7, 4]), steady_pairs([1, 2, 3, 4]))What is printed?- A. 7 6
- B. 7 3
- C. 4 6
- D. 5 6
Correct answer: A. 7 6
Rewrite a[j] − a[i] = j − i as a[j] − j = a[i] − i: pairs inside the same group of key a[i] − i. Keys for [3, 4, 1, 6, 7, 4]: 3, 3, −1, 3, 3, −1 → C(4,2) + C(2,2) = 6 + 1 = 7. [1, 2, 3, 4] has all keys 1 → C(4,2) = 6. The O(n²) double loop gives the same count but times out at n = 2·10⁵.
More Coding Interview Problems questions
- Problem: Four price lists A, B, C, D (each of length n ≤ 500). Count index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] = 0 by…
- Problem: A hiking trail is a list of heights. Find the length of the longest 'ridge' – a contiguous stretch that strictly rises and then…
- Problem: Return the sum of min(sub) over all contiguous subarrays using a monotonic stack. Ties must be broken so every subarray's minimum…
- Problem: Pick two NON-overlapping windows of fixed lengths L and M (either order) to maximise the total of their elements. Prefix sums…
- Problem: Remove the SHORTEST contiguous block (not the whole array) so that the remaining sum is divisible by p; return −1 if impossible…
- Problem: Count contiguous subarrays whose MAXIMUM lies in [L, R]: count subarrays with max ≤ R and subtract those with max ≤ L − 1. python…