FastPrepCount Index Pairs with Equal Value Offset

Count Index Pairs with Equal Value Offset

Google logoGoogle● EasyINTERNONSITE INTERVIEW
Learn

Problem statement

Given an integer array arr, return the number of index pairs (i, j) such that 0 <= i < j < arr.length and arr[i] - arr[j] = i - j.

Function

countMatchingIndexPairs(arr: int[]) → long

Examples

Example 1

arr = [4,1,2,3]return = 3

The valid pairs are (1,2), (1,3), and (2,3).

Example 2

arr = [1,5,6]return = 1

Only indices 1 and 2 satisfy the equation.

Example 3

arr = [0,1,2,3]return = 6

Every pair satisfies the equation because arr[i] - i is always zero.

Constraints

  • 0 <= arr.length <= 200000.
  • -1000000000 <= arr[i] <= 1000000000.

More Google problems

See Google hiring insights
public long countMatchingIndexPairs(int[] arr) {
    // Write your code here.
}
arr[4,1,2,3]
expected3
Checking account…