Heap Concept Structure and Properties in DSA Go - Time & Space Complexity
We want to understand how the time to perform operations on a heap changes as the heap grows.
Specifically, how fast can we add or remove elements in a heap?
Analyze the time complexity of inserting an element into a heap.
func insert(heap []int, value int) []int {
heap = append(heap, value)
i := len(heap) - 1
for i > 0 {
parent := (i - 1) / 2
if heap[parent] <= heap[i] {
break
}
heap[parent], heap[i] = heap[i], heap[parent]
i = parent
}
return heap
}
This code adds a new value to a min-heap and moves it up to keep the heap property.
Look for loops or repeated steps.
- Primary operation: The loop that moves the new element up the heap.
- How many times: At most once per level of the heap, from bottom to top.
Each time we add an element, it might move up several levels.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 moves (levels) |
| 100 | About 7 moves |
| 1000 | About 10 moves |
Pattern observation: The number of moves grows slowly, roughly with the height of the heap, which increases as the logarithm of n.
Time Complexity: O(log n)
This means adding an element takes time proportional to the height of the heap, which grows slowly as the heap gets bigger.
[X] Wrong: "Inserting into a heap takes constant time because we just add at the end."
[OK] Correct: After adding, we must move the element up to keep order, which can take multiple steps depending on heap size.
Knowing heap operation times helps you explain why heaps are good for priority tasks and efficient sorting.
"What if we changed the heap to a max-heap? Would the time complexity of insertion change?"