Untitled
unknown
plain_text
a year ago
827 B
4
Indexable
from collections import defaultdict
def get_triplet_count(arr, d):
n = len(arr)
count = 0
# Dictionary to store frequency of (arr[i] + arr[j]) % d
remainder_count = defaultdict(int)
# Traverse each element as the third element in the triplet
for k in range(n):
# For every arr[k], find pairs (arr[i], arr[j]) that make the sum divisible by d
target_remainder = (-arr[k]) % d
if target_remainder in remainder_count:
count += remainder_count[target_remainder]
# Update remainder counts for pairs ending at k
for j in range(k):
pair_sum = (arr[j] + arr[k]) % d
remainder_count[pair_sum] += 1
return count
# Test case from the image
arr = [2, 3, 1, 6]
d = 3
result = get_triplet_count(arr, d)
result # Expected output: 2Editor is loading...
Leave a Comment