Sort by

recency

|

6060 Discussions

|

  • + 0 comments

    Initial solution in JS. I will post an optimized solution later.

    function sockMerchant(n, ar){
      
        let pairCount = 0;
        
        while(ar.length>1) {
          for(let i = 1; i < ar.length; i++) {
            if(ar[0] === ar[i]) {
              pairCount += 1
              ar.splice(0, 1)
              ar.splice(i-1, 1)
              i = 0
            }
          }
          ar.splice(0, 1)
        }
        return pairCount
    
    }
    
  • + 0 comments

    Easy to read code, concise and efficient

    def sockMerchant(n, ar): Sum = 0 for i in list(set(ar)): Sum += ar.count(i)//2 return Sum `

  • + 0 comments
     public static int sockMerchant(int n, List<Integer> ar) {
        // Write your code here
            Map<Integer,Integer> colorCount =new HashMap<>();
            for(int sock : ar ){
                colorCount.put(sock, colorCount.getOrDefault(sock,0)+1);
            }
            
            Integer pairs = 0;
            for(Integer c : colorCount.values()){
                pairs+=c/2;
                
    
            }
            return pairs;
    
        }
    
    }
    
  • + 1 comment

    Java using Collections frequency utility:

    public static int sockMerchant(int n, List<Integer> ar) {
        Set<Integer> unique = new HashSet<>(ar);
    
        int pairs = 0;
        for(Integer i : unique){
            Integer frequency = Collections.frequency(ar, i);
            pairs = pairs + (frequency / 2);
        }
        return pairs;
    }
    
  • + 0 comments

    This is my solution in JS:

    function sockMerchant(n, ar) {
            
        let pairCounter=0;
        
        while(ar.length>1){
            let color= ar.shift();
            for(let i=0; i<ar.length; i++){
                if(color===ar[i]) {
                 pairCounter++;
                 ar.splice(i,1);
                 break;   
                }
            }
        }
        return pairCounter;
    }