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?
  1. A. 7 6
  2. B. 7 3
  3. C. 4 6
  4. 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

Exams that ask this topic