• + 1 comment

    Succint python solution using priority queue and dictionary. O(N) runtime. O(N) space.

        import heapq as hq
        from collections import defaultdict
        pq = []
        d = defaultdict(lambda : 0)
        total = 0
        
        for n in arr:
            if n in d:
                total += 2 * d[n]
            while pq and n>pq[0]:
                d.pop(hq.heappop(pq), None)
            hq.heappush(pq, n)
            d[n] += 1
            
        return total