HackerRank Interview Preparation Kit - Sales By Match

HackerRank Interview Preparation Kit - Sales By Match

This is the first problem from the "Warm-up Challenges" segment of HackerRank's Interview Preparation Kit.

Question Link: Official Website of HackerRank

Question

There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.'

Example

n = 7
ar = [1,2,1,2,1,3,2]

There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

Function Description

Complete the sockMerchant function in the editor below.

sockMerchant has the following parameter(s):

  • int n: the number of socks in the pile

  • int ar[n]: the colors of each sock

Returns

  • int: the number of pairs

Input Format

The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers, ar[i], the colors of the socks in the pile.

Constraints

Sample Input

STDIN                       Function
-----                       --------
9                           n = 9
10 20 20 10 10 30 50 10 20  ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]

Sample Output

3

Explanation

Code Template (Python)

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'sockMerchant' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER n
#  2. INTEGER_ARRAY ar
#

def sockMerchant(n, ar):
    # Write your code here

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    ar = list(map(int, input().rstrip().split()))

    result = sockMerchant(n, ar)

    fptr.write(str(result) + '\n')

    fptr.close()

My Solution (Python)

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'sockMerchant' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER n
#  2. INTEGER_ARRAY ar
#

def sockMerchant(n, ar):
    # Write your code here

    # create a dictionary to store the count of each sock color
    sock_count = {} # creating an empty dictionary

    # Count the socks of each color
    for sock in ar:
        if sock in sock_count:
            sock_count[sock] += 1
        else:
            sock_count[sock] = 1

    # initialize the variable to keep track of the total number of pairs
    total_pairs = 0

    # calculate the number of pairs for each sock color
    for count in sock_count.values():
        total_pairs += count // 2

    return total_pairs

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    ar = list(map(int, input().rstrip().split()))

    result = sockMerchant(n, ar)

    fptr.write(str(result) + '\n')

    fptr.close()

Breakdown for def sockMerchant(n, ar)

I will walk you through the sockMerchant function step by step, explaining how it works.

  1. Create a Dictionary to Store Sock Counts:

     sock_count = {}
    

    We start by creating an empty dictionary called sock_count to store the count of each sock color. The keys in this dictionary will represent the sock colors, and the values will represent how many socks of each color we've seen so far.

  2. Count the Socks:

     for sock in ar:
         if sock in sock_count:
             sock_count[sock] += 1
         else:
             sock_count[sock] = 1
    

    We iterate through the ar list, which contains the colors of the socks. For each sock color, we check if it's already in the sock_count dictionary. If it is, we increment the count of that color by 1. If it's not in the dictionary, we initialize it with a count of 1.

    This loop effectively counts how many socks of each color are in the pile.

  3. Initialize Total Pairs Counter:

     total_pairs = 0
    

    We initialize a variable total_pairs to keep track of the total number of pairs of socks.

  4. Calculate the Number of Pairs:

     for count in sock_count.values():
         total_pairs += count // 2
    

    After counting the socks of each color, we iterate through the values in the sock_count dictionary. Each value represents the count of socks of a particular color. We calculate how many pairs can be made from that count by dividing it by 2 (using integer division //) and add this value to the total_pairs variable.

    The integer division is used because we want to count the number of pairs, and any remaining socks (odd socks) cannot be used to make pairs.

  5. Return the Total Pairs:

     return total_pairs
    

    Finally, we return the total_pairs as the result of the function.

The code counts the number of pairs of socks by first counting the socks of each color and then determining how many pairs can be made from those counts. It ensures that odd socks are not included in the final pair count.

Conclusion

Thank you so much for reading the entire article till now.

If you have enjoyed the procedures step-by-step, then don't forget to let me know on Twitter/X or LinkedIn.

You can follow me on GitHub as well if you are interested in open source. Make sure to check my website (https://fahimbinamin.com/) as well!

If you like to watch programming and technology-related videos, then you can check my YouTube channel, too.

All the best for your programming and development journey. 😊

You can do it! Don't give up, never! ❣️