šŸŽ’
Technical Interview Study Guide
  • šŸ•Welcome!
  • šŸ„Getting Started
    • Study Plan
    • Optimizing Revision
    • Summer 2024 Timeline
    • FAQs
  • 🄨Algorithms
    • Binary Search
    • Sorting
    • Recursion
    • Graph
    • Quick Select
    • Intervals
    • Binary
    • Geometry
    • Dynamic Programming
  • šŸ„žData Structures
    • Arrays
      • Matrices
    • Strings
    • Linked Lists
      • Doubly Linked Lists
    • Hash Tables
    • Graphs
      • Trees
        • Binary Search Trees
        • Heaps
        • Tries
        • Segment Trees
    • Stacks
    • Queues
      • Double Ended Queues
    • Union-Find Disjoint Set (UFDS)
  • šŸ”Problems Guide
    • Dynamic Programming Roadmap
      • Warmup
        • Climbing Stairs
        • Nth Tribonacci Number
        • Perfect Squares
      • Linear Sequence
        • Min Cost to Climb Stairs
        • Minimum Time to Make Rope Colorful
        • House Robber
        • Decode Ways
        • Minimum Cost for Tickets
        • Solving Questions with Brainpower
  • šŸ£Other Technical Topics
    • General Problem Solving
    • Runtime Predictions
    • System Design
      • SQL
      • Accessing APIs
    • Operating Systems
  • šŸæNon-technical Topics
    • Behavioral Interviews
    • Resumes
Powered by GitBook
On this page
  • Runtime analysis
  • Techniques
  • Max heaps
  • K-smallest/largest
  • Using quick select instead
  • Finding the median of data
  1. Data Structures
  2. Graphs
  3. Trees

Heaps

Heaps or priority queues are a very powerful data structure that can be used to easily store information that has some intrinsic order

PreviousBinary Search TreesNextTries

Last updated 1 year ago

Heaps can be implemented as trees under the hood, but some are also implemented using arrays. I have chosen to stick to the implementation I was taught and park heaps under Trees

Runtime analysis

  1. Find min/max: O(1)O(1)O(1)

  2. Insert: O(log⁔n)O(\log n)O(logn)

  3. Remove: O(log⁔n)O(\log n)O(logn)

  4. Heapify: O(n)O(n)O(n)

Techniques

Max heaps

In Python, heapq is defaults to using a min heap. This might not be what you want by default. The only way to make heapq work as a max heap is by inverting the values inserted

K-smallest/largest

K-smallest implies using a k-sized max heap, removing the maximum element if the size becomes > k

K-largest implies using a k-sized min heap instead

Using quick select instead

Finding the median of data

Simulate the median by having a max heap for the elements to the left of the median and a min heap for the elements to the right of the median

Sometimes, the information required from a k-sized heap can be replicated by using Quick Select. The benefit of doing so is that the runtime can be reduced to O(n)O(n)O(n) whereas with heaps, it would be O(nlog⁔n)O(n \log n)O(nlogn)

šŸ„ž