Last Updated: 14 Oct, 2025

Invariant Pairs

Easy
Asked in company
Google inc

Problem statement

You are given a list of N integers, a. Your task is to compute the number of ordered pairs of indices (i, j) that satisfy two conditions:


1) i != j


2) a[i] - a[j] = i - j


An ordered pair (i, j) is different from (j, i).


Insight: The condition a[i] - a[j] = i - j can be algebraically rearranged to a[i] - i = a[j] - j. This means we are looking for pairs of distinct indices (i, j) where the value a[k] - k is the same.


Input Format:
The first line contains a single integer N, the size of the array.

The second line contains N space-separated integers, representing the elements of the array a.


Output Format:
Print a single integer representing the total count of such ordered pairs.


Note:
A brute-force solution that checks every possible pair (i, j) would have a time complexity of O(N^2) and will be too slow for the given constraints. A more efficient O(N) solution can be achieved by calculating the value a[k] - k for each index k and using a hash map to count the frequencies of these values.