The 'no built-in heap' constraint is what made this non-trivial.
Start by clarifying requirements and edge cases, then outline the array-based binary heap structure and the sift-up/sift-down algorithms. Implement push, pop, and peek with the required complexities, and discuss min-heap vs max-heap and custom comparators. Finally, analyze trade-offs and potential optimizations.
Pro tip: Mention that using a dynamic array (like Python's list) with amortized O(1) append and O(1) index access is ideal for the heap, and that you can avoid swaps by using hole-based sift operations for efficiency.
Ask about expected operations, data types, and whether the heap should be min or max by default. Discuss handling empty heap, duplicate priorities, and custom comparators.
Explain that the heap is an array where for index i, children are at 2i+1 and 2i+2, and parent at (i-1)//2. Mention that this structure ensures the heap property and enables O(log n) operations.
Describe push: append to array, then sift-up. Pop: replace root with last element, remove last, then sift-down. Peek: return root. Highlight O(log n) for push/pop and O(1) for peek.
Explain that min-heap has smallest at root, max-heap largest. For custom comparators, either invert the comparator for min-heap or use a wrapper class. Mention that Python's heapq is min-heap, so for max-heap you can negate keys.
Discuss time/space complexity, stability, and alternatives like d-ary heaps. Mention that array-based heap is cache-friendly and that sift operations can be optimized with hole technique.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.