0

In particular without modifying the input.

I've so far been unable to find anything on this, I wonder if it has a solution better than the obvious O(n log n) time.

U2EF1
  • 12,907
  • 3
  • 35
  • 37
  • How do you define equality of two heaps? The most obvious definition of equality would be O(n) since you would just check if the two arrays are equal. Or do you mean by equality that sorting both heaps would result in equal sequences? – Mo B. Dec 27 '20 at 15:31
  • @MoB. That repeated `pop_max` operations would yield the same values. Sorting and comparing would work. Direct comparison doesn't work, because the heaps represented by arrays `3 1 2` and `3 2 1` should compare equal. Still there is some shared structure, I am wondering if it has been exploited. – U2EF1 Dec 27 '20 at 18:20

1 Answers1

1

According to your definition, two heaps are equal if they yield the same sequence of elements when extracting their maximum element repeatedly. Since that amounts to destructively sorting the elements in the heap, equality is also equivalent to saying that the two sequences of heap elements when sorted are equal. But that is equivalent to multiset equality between the two heaps.

Checking multiset equality can be done in O(n) (amortized), e.g. by using a hash table to map each element of the first heap to its frequency, which can be done non-destructively in O(n), and then checking the elements of the second heap against the hash table, which can also be done in O(n).

Since it is not possible to check equality without considering each element at least once, O(n) is also the tightest bound on checking equality of two binary heaps.

Mo B.
  • 5,307
  • 3
  • 25
  • 42