From 71332334c753a8f4d7f5456f3126ef07aee95f1d Mon Sep 17 00:00:00 2001 From: Kartik Shastrakar <81631437+kartikshastrakar@users.noreply.github.com> Date: Wed, 25 Sep 2024 22:42:15 +0530 Subject: [PATCH] Update 003. Count Triplets.py add refactored method --- 003. Count Triplets.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/003. Count Triplets.py b/003. Count Triplets.py index 26ccdb6..b5114b0 100644 --- a/003. Count Triplets.py +++ b/003. Count Triplets.py @@ -19,3 +19,22 @@ def count_triplets(arr, r): n, r = map(int, input().split()) arr = list(map(int, input().split())) print(count_triplets(arr, r)) + + +from collections import defaultdict + +def count_triplets(n, r, arr): + arr2 = defaultdict(int) + arr3 = defaultdict(int) + count = 0 + for i in arr: + count += arr3[i] + arr3[i * r] += arr2[i] + arr2[i * r] += 1 + return count + +# Example usage +n, r = map(int, input("Enter n and r: ").split()) +arr = list(map(int, input("Enter array elements: ").split())) +result = count_triplets(n, r, arr) +print("Number of triplets:", result)