Given an array a and a number d, I want to count the number of distinct triplets (i,j,k) such that i<j<k and the sum aᵢ + aⱼ + aₖ is divisible by d.
Example: when a is [3, 3, 4, 7, 8]
and d is 5
it should give count as 3:
- triplet with indices (1,2,3) 3+3+4=10
- triplet with indices (1,3,5) 3+4+8=15
- triplet with indices (2,3,4) 3+4+8=15
Constraints:
- 3 ≤ len(a) ≤ 10³
- 1 ≤ aᵢ ≤ 10⁹
def count_triplets(arr, d):
n = len(arr)
count = 0
for i in range(n - 2):
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
if (arr[i] + arr[j] + arr[k]) % d == 0:
count += 1
return count
I got this for my OA but only came up with O(n³) approach.
arr
guaranteed monotonic? Cite the puzzle's URL, please. Confusingly you seem to be using Fortran's one-origin array indexes, OK, whatever. Surely the indexes(1,3,5)
and(2,3,5)
are "distinct" i,j,k triplets that both give a valid sum of15
, right? It's unclear why you say "should give count as 3", since there are additional valid index triplets. Did you maybe want to rephrase it terms of distinct values, rather than distinct indexes? \$\endgroup\$d
is? \$\endgroup\$