Divisible Triplets

Start Timer

0:00:00

Upvote
0
Downvote
Save question
View comments

Given an integer array nums and a positive integer d, write count_divisible_triplets(nums, d) to count triples of indices i < j < k for which:

(nums[i] + nums[j] + nums[k]) % d == 0

Values can repeat. Two triples using different indices count separately, even when their values are identical.

Example

nums = [3, 3, 4, 7, 8]
d = 3
count_divisible_triplets(nums, d)  # 4
Indices Values Sum
(0, 2, 4) (3, 4, 8) 15
(0, 3, 4) (3, 7, 8) 18
(1, 2, 4) (3, 4, 8) 15
(1, 3, 4) (3, 7, 8) 18

For this practice version: the array contains at most 2,000 integers, negative values are allowed, and 1 <= d <= 10**9. Fewer than three elements returns 0. Aim for O(n²) time and avoid storage proportional to d.

.
.
.
.
.


Comments

Loading comments