I did the Divisible Sum Pairs problem on HackerRank
input: n is length of array ar, k is an integer value.
a pair is define only if ar[i]+ar[j] is dividable by k where i < j.
Problem: find and return pairs in array.
def divisibleSumPairs(n, k, ar):
i=0 #pointer 1
j=1 #pointer 2 is faster than p1
count =0 #pointer 3 will only increment 1 once j = n-1 (second last element)
pairs=0
while count < n-1:
if (ar[i]+ar[j])%k==0:
pairs+=1
j+=1
count+=1
if count==n-1:
i+=1
j=i+1
count =i
print(pairs)
Code visualized
step 1:
i j
[a][b][c][e][f]
compare (i,j)
i j
[a][b][c][e][f]
compare (i,j)
i j
[a][b][c][e][f]
compare (i,j)
i j
[a][b][c][e][f]
compare (i,j)
i+=1
j=i+1
step2
i j
[a][b][c][e][f]
compare (i,j)
.
.
.
.
step n
i j
[a][b][c][e][f]
compare (i,j)
finish
I have a couple of questions:
- Does this algorithm have a name?
- Is there other way (maybe better, faster)?
- Is there some code I could have done better/ differently?
#some test data n=6 , k=3 ar =[1, 3, 2, 6, 1, 2]