Skip to main content
All questions
MediumArrays · Hash Map

Count Pairs Matching Sum and Difference Conditions

Written by a community member · · 1 attempt · 0% pass

0

You are given an integer array a of size n and two integers D and M.

Count the number of unordered index pairs (i, j) such that:

  • 0 <= i < j < n
  • (a[i] + a[j]) % D == 0
  • abs(a[i] - a[j]) % M == 0

Return the total number of valid pairs.

Function signature

Write a function count_valid_pairs(a: list[int], D: int, M: int) -> int.

Constraints

  • 1 <= n <= 10^5
  • -10^9 <= a[i] <= 10^9
  • 1 <= D, M <= 10^9

Examples

Example 1:
Input: count_valid_pairs([1, 2, 3, 4], 5, 1)
Output: 2
Explanation: Valid pairs are (1, 4) and (2, 3).

Notes

  • Pairs are unordered, so (i, j) and (j, i) are the same pair.
  • The array may contain duplicate values.