-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dictionaries and Hashmaps-Count Triplets.py
53 lines (35 loc) · 1.2 KB
/
Dictionaries and Hashmaps-Count Triplets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#Problem Link : https://www.hackerrank.com/challenges/count-triplets-1/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps
#Ans:
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countTriplets function below.
def countTriplets(arr, r):
if len(arr) <= 2:
return 0
map_arr = {}
map_doubles = {}
count = 0
# Traversing the array from rear, helps to avoid division
for x in arr[::-1]:
r_x = r*x
r_r_x = r*r_x
# Case: x is the first element (x, x*r, x*r*r)
count += map_doubles.get((r_x, r_r_x), 0)
# Case: x is the second element (x/r, x, x*r)
map_doubles[(x, r_x)] = map_doubles.get((x, r_x), 0) + map_arr.get(r_x, 0)
# Case: x is the third element (x/(r*r), x/r, x)
map_arr[x] = map_arr.get(x, 0) + 1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nr = input().rstrip().split()
n = int(nr[0])
r = int(nr[1])
arr = list(map(int, input().rstrip().split()))
ans = countTriplets(arr, r)
fptr.write(str(ans) + '\n')
fptr.close()