Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I'm actually attempting to solve the Sock merchant problem from HackerRank. 

John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are n=7 socks with colors 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.

Code:

class Sock

{

    public static void  main(String args[])

    {

        int n=10;

        int ar[] = new int[]{1,1,3,1,2,1,3,3,3,3};

        int count = 0,number=0;

        for(int i=0;i<n-1;i++)

        {

            for(int j=i+1;j<n;j++)

            {

                if(ar[i]==ar[j])

                {

                    count++;

                }

            }

             if(count%2==0)

                number++;

        }

        System.out.println("Pairs =  "+number);

    }

}

1 Answer

0 votes
by (26.4k points)

This should be possible in O(n) time complexity and O(n) space in the event that you utilize a hashtable. 

Hashtable would have Key = shade(color) of Socks, Value = absolute check of each tone.

total_count = dict()

for i in range(len(arr)):

    if arr[i] in total_count:

        total_count[arr[i]] += 1

pairs = 0

for i in total_count:

    pairs += int(total_count[i] / 2)

print(pairs)

Emphasize (Iterate) once over the array and store every event of color in a hashtable. At that point repeat over the hashtable to check if count of each tone are separable by 2. That would give you your sets.

Are you pretty much interested to learn python in detail? Come and join the python training course to gain more knowledge.

Browse Categories

...