Count Equal and Divisible Pairs in an Array

Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) with 0 <= i < j < n such that nums[i] == nums[j] and i * j is divisible by k.

30:00

Count Equal and Divisible Pairs in an Array
easy
Free written solution
Topics
Companies

Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) with 0 <= i < j < n such that nums[i] == nums[j] and i * j is divisible by k.

Example 1:
Input: {"nums":[3,1,2,2,2,1,3],"k":2}
Output: 4
Constraints:
  • 1≤nums.length≤1001 \leq \text{nums.length} \leq 100

  • 1≤nums[i],k≤1001 \leq \text{nums}[i], k \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,1,2,2,2,1,3],"k":2}

Only equal values can pair, so group indices by value. For each new index j, test it against the earlier indices in its own group: the pair counts when i * j is a multiple of 2.

nums · k = 2

3

0

1

1

2

2

2

3

2

4

1

5

3

6

groups: indices seen so far, by value

empty

divisibility tests for j = -

Waiting for the scan to start.

pairs

0

pairs that passed

none yet

Variables
VariableValue
k2
pairs0
n7
DepthFunction Call
Stack empty
0/20