Sort by

recency

|

6026 Discussions

|

  • + 0 comments

    Java

     public static int sockMerchant(int n, List<Integer> ar) {
            int pairs = 0;
            int size = ar.size();
            while(size-- > 0){
                int sock = ar.get(0);
                ar.remove(0);
    	        if (ar.contains(sock)){
    	            pairs++;
    	            ar.remove(ar.indexOf(sock));
    	            size--;
    	            }
    	        }
            return pairs;
    }
    
  • + 0 comments

    Python Solution

    def sockMerchant(n, ar):
        n_pairs = 0
        pair_dict = Counter(ar)
        for value in pair_dict.values():
            n_pairs += (value//2)
        return n_pairs
    

  • + 0 comments
    def sockMerchant(n, ar):
        sock_counts = {}  
        pairs = 0  
        
        for sock in ar:
            if sock in sock_counts:
                sock_counts[sock] += 1
            else:
                sock_counts[sock] = 1
        
        for count in sock_counts.values():
            pairs += count // 2  
        
        return pairs
    
  • + 0 comments

    Typescript solution. Time O(n), Space O(k). k is the number of colors.

    function sockMerchant(n: number, ar: number[]): number { if (n < 2) return 0;

    const unpairedSocks = new Set<number>();
    let pairs = 0;
    
    for (const color of ar) {
        if (unpairedSocks.has(color)) {
            pairs++;
            unpairedSocks.delete(color);
        } else {
            unpairedSocks.add(color);
        }
    }
    
    return pairs;
    

    }

  • + 0 comments

    C++ Solution:

    int sockMerchant(int n, vector<int> ar) {
        map<int, int> mp;
        int pair = 0;
        for(int color : ar){
            mp[color]++;
            if(mp[color]%2 == 0){
                pair++;
            }
        }
        return pair;
    }