This was the very first problem I solved in Hackerrank. I did not have any idea about algorithms. I didn’t learn algorithms in school either. What I learned was how to create a class, a function, edit an HTML, all the basics. I was amazed at the first time I encountered a runtime error because I didn’t know that a function that outputs correctly would need to be optimised. My thought was that as long as my function outputs the correct answers, other aspects did not matter.
My thought was that as long as my function outputs the correct answers, other aspects did not matter.
Well that was naive of me. So my thought process in solving this problem was just to get the “right” output.
Chronology of how my thought went:
- Let’s get the pairs by adding 2 similar numbers
- Add it as 0.5 because 2 * 0.5 = 1
- Return the sum which is the total number of pairs.
# not a pseudocode
each num + 0.5
when 0.5 becomes 1, it will be a pair
1 pair add to other pairs
return all pairs
Here’s the problem:
There is an array of numbers. Find a pair of numbers. Count the number of pairs and return.
arr = [3, 4, 20, 20, 5, 6, 7, 4, 20, 5]

Three pairs. It doesn’t matter if a third number exists, only find the pairs.
pairs = [4, 4, 5, 5, 20, 20]
total_pairs = 3
Here’s my solution:
# python 3
def sockMerchant(n, arr):
dict_pairs = {}
for item in arr:
if item not in dict_pairs:
dict_pairs[item] = 0.5
else:
dict_pairs[item] += 0.5
total_pairs = sum([int(values) for values in dict_pairs.values()])
print(total_pairs)
return total_pairs