Sales by Match

Sort by

recency

|

225 Discussions

|

  • + 0 comments

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn sales_by_match(n: i32, ar: &[i32]) -> i32 {
        //Time complexity: O(n)
        //Space complexity (ignoring input): O(n)
        let mut socks_hash = std::collections::HashMap::new();
        for sock in ar {
            match socks_hash.get(sock) {
                Some(v) => socks_hash.insert(sock, v + 1),
                None => socks_hash.insert(sock, 1),
            };
        }
        let mut total_pairs = 0;
        for values in socks_hash.values() {
            total_pairs += values / 2;
        }
        total_pairs
    }
    
  • + 0 comments

    Python best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    def sales_by_match(n, ar):
        #Time complexity: O(n)
        #Space complexity (ignoring input): O(n)
        socks_dict = {}
        for sock in ar:
            if sock in socks_dict:
                socks_dict[sock] += 1
            else:
                socks_dict[sock] = 1
    
        total_pairs = 0
        for values in socks_dict.values():
            total_pairs += values // 2
    
        return total_pairs
    
  • + 0 comments
    #Python Solution
    def sockMerchant(n, ar):
        pairs = 0
        colors = set(ar)
        
        for color in colors:
            pairs += math.floor(ar.count(color)/2)
        
        return pairs
    
  • + 0 comments

    this should work for C as the problem says: 1 <= ar[i] <=100

    int i, res = 0;
    int map[101] = {0};
    
    for(i = 0; i < n; i++) {
        map[ar[i]]++;
        if (map[ar[i]] == 2) {
            res++;
            map[ar[i]] = 0;
        }
    }
    return res;
    
  • + 0 comments

    My 3 Python solutions - two O(n) and one O(n^2)

    # O(n^2)
    def sockMerchant(n, ar):
        cnt = 0
        seen = set()
        for num in ar:
            if num not in seen:
                seen.add(num)
                cnt += ar.count(num) // 2
        
        return cnt
    
    
    # O(n)
    def sockMerchant(n, ar):
        ar.sort()
        idx = 0
        cnt = 0
        while idx < len(ar) - 1:
            if ar[idx] == ar[idx + 1]:
                cnt += 1
                idx += 2
            else:
                idx += 1
        return cnt
    
    
    # O(n)
    def sockMerchant(n, ar):
        cnt = [0] * (max(ar) + 1)
        for num in ar:
            cnt[num] += 1
        return sum([num // 2 for num in cnt])