Saturday, January 26, 2019

Sock Merchant - Hacker Rank Solution

Sock Merchant - Hacker Rank Solution


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  socks with colors . There is one pair of color  and one of color . There are three odd socks left, one of each color. The number of pairs is .
Function Description
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
  • n: the number of socks in the pile
  • ar: the colors of each sock
Input Format
The first line contains an integer , the number of socks represented in .
The second line contains  space-separated integers describing the colors  of the socks in the pile.
Constraints
  •  where 
Output Format
Return the total number of matching pairs of socks that John can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
Explanation
sock.png
John can match three pairs of socks.

Sock Merchant - Hacker Rank Solution

To solve this challenge, we go through each color  and count its frequency, . Once we've calculated all the frequencies, we calculate the number of pairs of each kind of sock as  (using integer division). Finally, we print the total sum of all pairs of socks.

Problem Setter's code:


C++

#include <bits/stdc++.h>
using namespace std;


int main() {
 int n;
    cin>>n;
 int freq[101] = {};
 for(int i = 0; i < n; i++) {
        int c;
        cin >> c;
        freq[c]++;
    }

 int res = 0;
 for(int i = 0; i <= 100; i++){
         res += freq[i] / 2;
     }
 cout << res << endl;
 return 0;
}

Python 2.7

from itertools import groupby
n = int(raw_input())
c = map(int, raw_input().split())

ans = 0
for val in [len(list(group)) for key, group in groupby(sorted(c))]:
    ans = ans + val/2
print ans

Tested by 

AllisonP
Problem Tester's code:

Java

import java.util.*;

class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        HashMap<Integer, Integer> colors = new HashMap<Integer, Integer>();
        
        while(n-- > 0) {
            int c = scan.nextInt();
            Integer frequency = colors.get(c);
            
            // If new color, add to map
            if(frequency == null) {
                colors.put(c, 1);
            }
            else { // Increment frequency of existing color
                colors.put(c, frequency + 1);
            }
        }
        scan.close();
        
        // Count and print the number of pairs
        int pairs = 0;
        for(Integer frequency : colors.values()) {
            pairs += frequency >> 1;
        }
        System.out.println(pairs);
    }
}

48 comments:

  1. This isn't a good solution. If the input is suppose [1000,1005,1000,1002]. Will you create an array of 1005 ?

    ReplyDelete
    Replies
    1. you will have to implement a hash table then.

      Delete
    2. A better approach

      int sockMerchant(int n, vector ar) {
      int total_pair = 0 ;
      int i = 0 , j = 0 ;
      int sock_count = 0 ;
      vector sock;
      sort(ar.begin(), ar.end());
      while(i < ar.size()-1){
      sock_count = 1;
      for( j = i + 1 ; j < ar.size() ; j++){
      if(ar[i] == ar[j]){
      sock_count++;
      }
      else{
      i = j;
      break;
      }
      }
      sock.push_back(sock_count);
      if(i != j){
      i = j;
      }
      cout<<i<<endl;

      }

      for(int i = 0 ; i < sock.size() ; i ++){
      total_pair+=(sock[i]/2);
      }

      return total_pair;
      }

      Delete
    3. try with this one no need to use two arrays ...


      import java.io.*;
      import java.math.*;
      import java.security.*;
      import java.text.*;
      import java.util.*;
      import java.util.concurrent.*;
      import java.util.regex.*;

      public class Solution {

      // Complete the sockMerchant function below.
      static int sockMerchant(int n, int[] ar) {
      int i;
      int count=0;
      int[] vr = new int[n];
      int visited=-1;
      int pairs = 0;
      for(i=0;i<n;i++)
      {
      for(int j=i+1;j<n-1;j++)
      {
      if(ar[i]!=visited && ar[j]!=visited)
      {
      if(ar[i]==ar[j])
      {
      count=count+1;
      ar[i]=visited;
      ar[j]=visited;
      }
      }

      }

      }

      return(count);


      }

      private static final Scanner scanner = new Scanner(System.in);

      public static void main(String[] args) throws IOException {
      BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

      int n = scanner.nextInt();
      scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

      int[] ar = new int[n];

      String[] arItems = scanner.nextLine().split(" ");
      scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

      for (int i = 0; i < n; i++) {
      int arItem = Integer.parseInt(arItems[i]);
      ar[i] = arItem;
      }

      int result = sockMerchant(n, ar);

      bufferedWriter.write(String.valueOf(result));
      bufferedWriter.newLine();

      bufferedWriter.close();

      scanner.close();
      }
      }

      Delete
    4. Sir can explain the role of visited in this code

      Delete
    5. im pretty sure, its becuase when comparing and counting the socks, we dont want a repetition in the same sock! for example if its 20 20 20 30 50 20, it needs to only count 20 4 times! if we dont keep a variable that counts the numbers we visited, it'll count 20 in seperate occasions like 20=4, 20=3,20=2! atleast that was the issue i encountered while coding!

      Delete
  2. why did yoou do a right shift to pairs? is it some hack?

    ReplyDelete
  3. function sockMerchant($n, $ar) {

    $socks = [];

    //get count of each colors
    for ($i = 0; $i < $n; $i++ ) {
    $color = $ar[$i];
    if (isset($socks[$color])) {
    $socks[$color] = $socks[$color] + 1;
    } else {
    $socks[$color] = 1;
    }
    }

    //find out pairs of colors
    $totalPairs = 0;
    foreach ($socks as $sock) {
    $totalPairs = $totalPairs + floor(($sock / 2));
    }

    return $totalPairs;
    }

    $colors = [10, 20, 20, 10, 10, 30, 50, 10, 20];
    echo sockMerchant(9, $colors);

    ReplyDelete
  4. Can You Please tell me why you use right shift to find pairs in HashMap

    ReplyDelete
  5. I think it's just a division by 2 without a remainder. Because we counted every single sock so we need to divide by 2 to get the number of pairs

    ReplyDelete
  6. int counter=0;
    int count=0;
    for(int i=0;i<ar.length;i++)
    {
    count=1;
    for(int j=i+1;j<ar.length;j++)
    {
    if(ar[i]==ar[j])
    {
    count++;
    }
    }
    if(count==2)
    {
    counter++;
    }
    }

    return counter;

    ReplyDelete
    Replies
    1. if (count % 2 == 0)
      {
      counter++;
      }

      Delete
    2. so the j=i+1 loop counts the number of socks, suppose its 6. counter would count only once rite?

      Delete

  7. 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 socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .



    import java.io.*;
    import java.math.*;
    import java.security.*;
    import java.text.*;
    import java.util.*;
    import java.util.concurrent.*;
    import java.util.regex.*;

    public class Solution {

    // Complete the sockMerchant function below.
    static int sockMerchant(int n, int[] ar) {

    int counter=0;
    int count=0;
    for(int i=0;i<ar.length;i++)
    {
    count=1;
    for(int j=i+1;j<ar.length;j++)
    {
    if(ar[i]==ar[j])
    {
    count++;
    }
    }
    if(count%2==0)
    {
    counter++;
    }
    }

    return counter;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

    int n = scanner.nextInt();
    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

    int[] ar = new int[n];

    String[] arItems = scanner.nextLine().split(" ");
    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

    for (int i = 0; i < n; i++) {
    int arItem = Integer.parseInt(arItems[i]);
    ar[i] = arItem;
    }

    int result = sockMerchant(n, ar);
    System.out.println("Number of pair of socks"+result);

    bufferedWriter.write(String.valueOf(result));
    bufferedWriter.newLine();

    bufferedWriter.close();

    scanner.close();
    }
    }

    ReplyDelete
    Replies
    1. wow...this is so easy and clear. Thank you!!!

      Delete
    2. Any even number divided by 2 will give remainder 0.So, Can u please explain what is actually checked in if(count%2==0) .I didn't understand what is it's purpose

      Delete
  8. static int sockMerchant(int n, int[] ar) {
    int pair=0;
    for (int i = 0; i < n; i++) {
    int count=0;

    for (int j = i + 1; j < n; j++){
    if (ar[i] == ar[j] && ar[i]>=0) {
    count++;
    ar[j]=-1;
    }
    else continue;
    if((count+1)%2==0 && count>0)
    pair++;
    }
    count++;
    }
    return pair;
    }

    ReplyDelete
  9. for python

    def sockMerchant(n, ar):
    result = 0
    ar.sort()
    i = 0
    j = 1
    while i < len(ar):
    if(ar[i] == ar[j]):
    result=result+1
    i=i+1
    j=j+1
    i=i+1
    j=j+1
    if(j == len(ar)):
    break
    return result

    ReplyDelete
  10. Python 3:

    def sockMerchant(n, ar):
    x=[]
    y=[]
    ar.sort()
    while len(ar)>1:
    if ar[0]==ar[1]:
    x.append(ar[:2])
    del ar[:2]
    else:
    del ar[0]
    return len(x)

    ReplyDelete
  11. static int sockMerchant(int n, int[] ar)
    {
    Arrays.sort(ar);
    int count=0;
    int sum=0;
    for(int i=0;i<n-1;i++)
    {
    if(ar[i]==ar[i+1])
    {
    count++;
    }
    if(ar[i]!=ar[i+1])
    {
    if(count%2==1)
    {
    sum=sum+count+1;
    }
    else
    {
    sum=sum+count;
    }

    count=0;
    }
    }
    if(count%2==1)
    {
    sum=sum+count+1;
    }
    else
    {
    sum=sum+count;
    }
    sum=sum/2;

    return sum;

    }

    ReplyDelete
  12. Is there any source which explains codes line to line clearly?

    ReplyDelete
  13. //javascript solution

    function sockMerchant(n, arr) {

    var counter=0;
    var count=0;
    for(var i=0;i<arr.length;i++)
    {
    count=1;
    for(var j=i+1;j<arr.length;j++)
    {
    if(arr[i]==arr[j])
    {
    count++;
    }
    }
    if (count % 2 == 0)
    {
    counter++;
    }
    }

    return counter;
    }

    ReplyDelete
  14. const n = 9;
    let ar = [10, 20, 20, 10, 10, 30, 50, 10, 20];

    function sortAndCount(n, ar) {

    let sorted = ar.sort((a,b) => a - b);

    let pair = 0;

    for(let i = 0; i < n-1; i++ ) {
    console.log(i)
    if(sorted[i] === sorted[i + 1]) {
    pair ++;
    i += 1;
    }
    }
    return pair;
    }


    console.log(sortAndCount(n, ar))

    ReplyDelete
  15. #include

    using namespace std;

    vector split_string(string);

    // Complete the sockMerchant function below.
    int sockMerchant(int n, vector ar) {

    int i, pairs = 0;

    if(n >= 1 && n <= 100){

    sort(ar.begin(), ar.end());

    for(i = 0; i < n; i++){
    if(ar[i] == ar[i+1]){
    pairs = pairs + 1;
    i = i + 1;
    }
    }
    }

    return pairs;
    }

    ReplyDelete
  16. def sockMerchant(n, ar):
    pair=0
    for i in range(n):
    for j in range(i+1,n):
    if ar[i]==ar[j]:
    if ar[i]==ar[j]=="done already":
    continue
    ar[j]="done already"
    pair+=1

    break
    return pair

    ReplyDelete
  17. int sockMerchant(int n, vector ar) {
    set s(ar.begin(),ar.end());
    vector v(s.begin(),s.end());
    int ss=(int)v.size();


    int counter=0;
    int count=0;
    int b=(int)ar.size();

    for(int i=0;i<ss;i++){
    if(v[i]==ar[i])
    count=1;
    cout<<"....\n";
    for(int j=i+1;j<b;j++){
    if(v[i]==ar[j]){
    count++;
    cout<<count<<" \n";
    }
    }

    counter= counter+int(count/2);
    count=0;
    cout<<"----"<<counter<<"\n";

    }


    return counter;
    }

    ReplyDelete
  18. n=int(input())
    list1=[]
    list2=[]
    for i in range(n):
    a=int(input())
    list1.append(a)
    list2.append(0)
    counter=0
    for i in range(len(list1)):
    element=list1[i]
    for j in range(i+1,len(list1)):
    if element==list1[j] and list2[j]==0 and list2[i]==0:
    counter+=1
    list2[j]=1
    list2[i]=1
    print(list2)
    break
    print(counter)

    ReplyDelete
  19. py3 code .def sockMerchant (n, number):
    total = 0
    for i in range(n-1):
    sorted(number)
    total= i//2
    return total
    n = int(input())
    number = list(map(int, input().split()))
    print(sockMerchant(n, number))

    ReplyDelete
  20. def sockMerchant (n, number):
    total = 0
    for i in range(n-1):
    sorted(number)
    total= i//2
    return total
    n = int(input())
    number = list(map(int, input().split()))
    print(sockMerchant(n, number))

    ReplyDelete
  21. from itertools import groupby
    n = int(raw_input())
    c = map(int, raw_input().split())

    ans = 0
    for i in [len(list(group)) for key, group in groupby(sorted(c))]:
    ans = ans + i/2
    print ans

    ReplyDelete
  22. #include
    #include
    using namespace std;
    int sockMerchant(int n,int *ar)
    {
    int count=0;
    int freq[101]={};
    for(int i=0;i<n;i++)
    {
    freq[ar[i]]++;
    }
    for(int j=0;j<101;j++)
    {
    if(freq[j]%2!=0)
    count++;
    }
    return count;
    }
    int main()
    {
    int ar[]={10,20,20,30,10,30,50,10,20,10};
    int n=sizeof(ar)/sizeof(ar[0]);
    cout<<sockMerchant(n,ar);
    return 0;
    }

    ReplyDelete
  23. //Very Basic Javascript Solution

    function sockMerchant(n, ar) {
    var pair = 1;

    for (var i = 0; i < n; i++) {
    for (var j = i + 1; j < n; j++) {
    if (ar[i] == ar[j]) {
    pair += 1;
    ar[j] = 0;
    }
    break;
    }
    }
    return pair
    }

    ReplyDelete
  24. c#:
    static int sockMerchant(int n, int[] ar) {
    int count=0,j=0,pair=0;

    Array.Sort(ar);

    for(int i=0;i0)
    {
    count++;
    pair=pair+(count/2);

    }
    }

    else
    {
    count++;
    pair=pair+(count/2);
    count=0;
    }




    }
    return pair;

    }

    ReplyDelete
    Replies
    1. static int sockMerchant(int n, int[] ar) {
      int count=0,j=0,pair=0;

      Array.Sort(ar);

      for(int i=0;i0)
      {
      count++;
      pair=pair+(count/2);

      }
      }

      else
      {
      count++;
      pair=pair+(count/2);
      count=0;
      }


      }
      return pair;

      }

      Delete
  25. static int sockMerchant(int n, int[] ar) {
    int count=0,j=0,pair=0;

    Array.Sort(ar);

    for(int i=0 ;i< n - 1 ; i++)
    {
    j=i+1;
    if(ar[i]==ar[j])
    {
    count++;

    if(j==n-1&&count>0)
    {
    count++;
    pair=pair+(count/2);

    }
    }

    else
    {
    count++;
    pair=pair+(count/2);
    count=0;
    }




    }
    return pair;

    }

    ReplyDelete
  26. Can someone plz provide the answer in Golang?

    ReplyDelete
  27. C# solution:
    public static int sockMerchant(int n, List ar)
    {
    int count=0;
    int counter=0;
    for(int i=0;i<n-1;i++)
    {
    count=1;
    for(int j=i+1;j<n;j++)
    {
    if(ar[i]==ar[j])

    {
    count++;
    }

    }
    if(count%2==0)
    {
    counter++;
    }
    }
    return counter;

    }

    ReplyDelete
  28. public static int sockMerchant(int n, List ar) {

    Map map = new HashMap<>();
    for (int i = 0; i < n; i++) {
    if(map.containsKey(ar.get(i))){
    map.put(ar.get(i), map.get(ar.get(i))+1);
    }else {
    map.put(ar.get(i), 1);
    }
    }

    //divide value of each key by 2
    int no_of_pairs = 0;

    Iterator> itr = map.entrySet().iterator();
    while (itr.hasNext()){
    Map.Entry entry = itr.next();
    no_of_pairs = no_of_pairs + (entry.getValue() / 2);
    }
    //return (ar.size()- (no_of_pairs*2));
    return no_of_pairs;

    }

    ReplyDelete
  29. //PROPER WAY TO DO THIS PROBLEM!
    int sockMerchant(int n, vector ar) {

    sort(ar.begin(),ar.end());
    int count=0;
    for(int i=0;i<ar.size();i++)
    {
    for(int j=i+1;j<ar.size();j++)
    {
    if(ar.at(i)==ar.at(j))
    {
    // cout<<ar.at(i)<<" and "<<ar.at(j)<<" | "; for refrence
    count++;
    i+=1;
    break;
    }
    }
    }
    return count;

    }

    ReplyDelete
  30. For Complete explanation of C++ please visit - SchoolingAxis

    ReplyDelete
  31. Another approach but complexity is high:
    def sockMerchant(n, ar):
    # Write your code here
    c=0
    for i in range(0,n-1):
    while ar[i]==0:
    i+=1
    for j in range(i+1,n):
    while ar[j]==0:
    j+=1
    if ar[i]==ar[j]:
    c+=1
    ar[i]=0
    ar[j]=0
    break
    return c

    ReplyDelete
  32. I came with this solution in Python, I created a dictionary from array, it takes only unique colors and counts how many of them in the array, then I put the numbers of different colors into the list and loop thru, checking their division by 2 and add result to total.

    def sockMerchant(n, ar):
    count= 0
    #create a dictionary with unique color values and count them
    colours_count=(dict((i, ar.count(i)) for i in ar))

    #create a list of counted colours
    list1 = colours_count.values()

    #loop thru the list
    for x in list1:
    if x>1:
    #only values which greater that 1 can be counted
    y=math.floor(x/2)
    count+=y


    return count

    ReplyDelete
  33. import java.io.*;
    import java.math.*;
    import java.security.*;
    import java.text.*;
    import java.util.*;
    import java.util.concurrent.*;
    import java.util.function.*;
    import java.util.regex.*;
    import java.util.stream.*;
    import static java.util.stream.Collectors.joining;
    import static java.util.stream.Collectors.toList;

    class Result {

    /*
    * 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
    */

    public static int sockMerchant(int n, List ar) {
    // Write your code here
    int count=0;
    Mapmap=new HashMap<>();
    for(Integer i:ar)
    {
    Integer j=map.get(i);

    map.put(i, (j==null)?1:j+1);

    }
    for(Map.Entryval:map.entrySet())
    {

    if(val.getValue()>1)
    {
    count=count+val.getValue()/2;
    }
    }
    return count;
    }

    }

    public class Solution {
    public static void main(String[] args) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

    int n = Integer.parseInt(bufferedReader.readLine().trim());

    List ar = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
    .map(Integer::parseInt)
    .collect(toList());

    int result = Result.sockMerchant(n, ar);

    bufferedWriter.write(String.valueOf(result));
    bufferedWriter.newLine();

    bufferedReader.close();
    bufferedWriter.close();
    }
    }

    ReplyDelete
  34. You're definitely familiar with the best coding language C++ that developers use to develop their projects and they get all their queries like "c++ change console color" answered properly. Developers are finding an appropriate answer about c++ change console color related to the C++ coding language.

    ReplyDelete

Powered by Blogger.