Sort by

recency

|

5978 Discussions

|

  • + 0 comments

    Simple Solution

    Java

            int[] pairs = new int[100];
            int pairCount = 0;
            for (int i: ar)
            pairs[i - 1]++;
            
            for(int i: pairs)
            pairCount += (i / 2);
            
            return pairCount;
        }
    

    C++

    int sockMerchant(int n, vector<int> ar) {
        vector<int> pairs(100, 0);
        for (int i: ar)
        pairs[i - 1]++;
        int pairCount = 0;
        for (int i = 0; i < 100; i++) {
            pairCount += (pairs[i] / 2);
        }
        return pairCount;
    }
    
  • + 0 comments

    Here is my c++ solution , you can find the video explanation here : https://youtu.be/HPIhFXx_DVM

    int sockMerchant(int n, vector<int> ar) {
        map<int, int>mp;
        int result = 0;
        for(int i = 0; i < ar.size(); i++){
            if(mp[ar[i]]){
                result ++;
                mp.erase(ar[i]);
                continue;
            }
            mp[ar[i]]++;
        }
        return result;
    }
    
  • + 0 comments

    java(8)

    public static int sockMerchant(int n, List<Integer> ar) {
        // Write your code here
    
        int sockesPair = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
    
        for (int i : ar) {
            if (map.containsKey(i)) {
                map.put(i, map.get(i) + 1);
            } else {
                map.put(i, 1);
            }
    
        }
    
        for (int i : map.keySet()) {
    
            sockesPair += (map.get(i) / 2);
        }
        return sockesPair;
    }
    
  • + 2 comments
    def sockMerchant(n, ar):
        socks = set()
        pairs = 0
        for sock in ar:
            if sock in socks:
                pairs += 1
                socks.remove(sock)
            else:
                socks.add(sock)
        return pairs
    
  • + 0 comments

    Here my solution in Python

    def sockMerchant(n, ar):
        # Write your code here
        pairs = {}
        for num in ar:
            pairs[num] = pairs.get(num, 0) + 1
        pairs_count = sum(count // 2 for count in pairs.values())
        return pairs_count