FastPrepCount Pairs with K Divisible Values in the Interval

Count Pairs with K Divisible Values in the Interval

Chubb logoChubb● HardNEW GRADOA
Learn

Problem statement

Given an integer array arr, a nonnegative integer k, and a positive integer x, count index pairs (i, j) with i < j and arr[i] <= arr[j] such that the inclusive integer interval [arr[i], arr[j]] contains exactly k multiples of x.

Pairs are counted by index, so equal values at different positions are distinct. Zero is divisible by every positive x. Return the number of valid pairs.

Function

countValidPairs(arr: int[], k: int, x: int) → long

Examples

Example 1

arr = [1,2,3,4,5]k = 2x = 2return = 4

The valid pairs have value intervals [1,4], [1,5], [2,4], and [2,5], each containing the multiples 2 and 4.

Example 2

arr = [-3,0,2]k = 2x = 3return = 2

The intervals [-3,0] and [-3,2] each contain -3 and 0. The interval [0,2] contains only 0.

Constraints

  • 1 <= arr.length <= 200000.
  • -1000000 <= arr[i] <= 1000000.
  • 0 <= k <= 2000000.
  • 1 <= x <= 1000000.
  • The answer fits in a signed 64-bit integer.

More Chubb problems

See Chubb hiring insights
public long countValidPairs(int[] arr, int k, int x) {
    // Write your solution here.
}
arr[1,2,3,4,5]
k2
x2
expected4
Checking account…