Aparna
Hackerrank Solution
1 min readMar 21, 2020

--

Sock Merchant Solution

Problem Statement:

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.

Sample Input:

9
10 20 20 10 10 30 50 10 20

Sample Output:

3

Solution:

static int sockMerchant(int n, int[] ar) {

int visited = -1;

int result = 0, result1=0;
int finalres;
int [] freq = new int [ar.length];

for(int i = 0; i < ar.length; i++){
int count = 1;
for(int j = i+1; j < ar.length; j++){
if(ar[i] == ar[j]){
count++;
//To avoid counting same element again
freq[j] = visited;
}
}
if(freq[i] != visited) {
freq[i] = count;
}
}
for(int i = 0; i < freq.length; i++){
if(freq[i] != visited){
System.out.println(“ “ + ar[i] + “ | “ + freq[i]);
}
}
for(int i = 0; i < freq.length; i++){
if(freq[i] > 1){
result += freq[i]/2;
}
}
return result;
}

--

--