FastPrepCount Pairs Divisible by K

Count Pairs Divisible by K

Apple logoApple● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given an integer array nums and positive integer k, count index pairs (i,j) with i < j for which nums[i] + nums[j] is divisible by k.

Different index pairs count separately, including pairs with equal values. An element cannot pair with itself. Return the count as a signed 64-bit integer.

Function

countDivisiblePairs(nums: int[], k: int) → long

Examples

Example 1

nums = [4,3,5,1,4,5]k = 5return = 3

The two separate occurrences of four each pair with one, and the two fives form one pair.

Example 2

nums = [-1,1,2,-2]k = 3return = 4

The valid sums are zero, negative three, positive three, and zero.

Constraints

  • 0 <= nums.length <= 10^5.
  • -10^9 <= nums[i] <= 10^9.
  • 1 <= k <= 10^9.

More Apple problems

See Apple hiring insights
public long countDivisiblePairs(int[] nums, int k) {
    // Write your solution here.
}
nums[4,3,5,1,4,5]
k5
expected3
Checking account…