Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions heaps/heap_sort.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@

from heaps.min_heap import MinHeap

def heap_sort(list):
""" This method uses a heap to sort an array.
Time Complexity: ?
Space Complexity: ?
Time Complexity: O(n log n)
Space Complexity: O(n)
Comment on lines +5 to +6

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✨ Great. Since sorting using a heap reduces down to building up a heap of n items one-by-one (each taking O(log n)), then pulling them back out again (again taking O(log n) for each of n items), we end up with a time complexity of O(2n log n) → O(n log n). While for the space, we do need to worry about the O(log n) space consume during each add and remove, but they aren't cumulative (each is consumed only during the call to add or remove). However, the internal store for the MinHeap does grow with the size of the input list. So the maximum space would be O(n + log n) → O(n), since n is a larger term than log n.

Note that a fully in-place solution (O(1) space complexity) would require both avoiding the recursive calls, as well as working directly with the originally provided list (no internal store).

"""
pass

# Create a min heap
heap = MinHeap()
# Add all elements to the heap
for element in list:
heap.add(element)

# Remove all elements from the heap and add them to a new list
sorted_list = []
while len(heap.store) > 0:
sorted_list.append(heap.remove().value)
Comment on lines +16 to +18

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should treat the internal store as an implementation detail and not check its length directly. Instead, we can make use of the empty helper method. Also, note that the value should be returned by the remove function, not the whole node.

    result = []
    while not heap.empty():
        result.append(heap.remove())

    return result


return sorted(sorted_list)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👀 You already sorted the list by adding and removing with the heap. No need for the sorted call here.

63 changes: 50 additions & 13 deletions heaps/min_heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,33 @@ def __init__(self):
def add(self, key, value = None):
""" This method adds a HeapNode instance to the heap
If value == None the new node's value should be set to key
Time Complexity: ?
Space Complexity: ?
Time Complexity: O(log n)
Space Complexity: O(log n)
Comment on lines +22 to +23

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✨ Great! In the worst case, the new value we're inserting is the new root of the heap, meaning it would need to move up the full height of the heap (which is log n levels deep) leading to O(log n) time complexity. Your implementation of the heap_up helper is recursive, meaning that for each recursive call (up to log n of them) there is stack space being consumed. So the space complexity is also be O(log n). If heap_up were implemented iteratively, this could be reduced to O(1) space complexity.

"""
pass

if value == None:
value = key
node = HeapNode(key, value)
self.store.append(node)
self.heap_up(len(self.store) - 1)

def remove(self):
""" This method removes and returns an element from the heap
maintaining the heap structure
Time Complexity: ?
Space Complexity: ?
Time Complexity: O(log n)
Space Complexity: O(log n)
Comment on lines +35 to +36

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✨ Great! In the worst case, the value that got swapped to the top will need to move all the way back down to a leaf, meaning it would need to move down the full height of the heap (which is log n levels deep) leading to O(log n) time complexity. Your implementation of the heap_down helper is recursive, meaning that for each recursive call (up to log n of them) there is stack space being consumed. So the space complexity is also be O(log n). If heap_down were implemented iteratively, this could be reduced to O(1) space complexity.

"""
pass

if len(self.store) == 0:
return None

# Swap the first element with the last element
self.swap(0, len(self.store) - 1)
# Remove the last element
removed_element = self.store.pop()
# Reheapify the heap
self.heap_down(0)
return removed_element

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👀 We shouldn't return the internal node that we made for the heap. Instead, just return the value here. Returning the entire node was part of what was causing a test failure.

        return removed_element.value


def __str__(self):
""" This method lets you print the heap, when you're testing your app.
Expand All @@ -44,10 +57,10 @@ def __str__(self):

def empty(self):
""" This method returns true if the heap is empty
Time complexity: ?
Space complexity: ?
Time complexity: O(1)
Space complexity: O(1)
"""
pass
return len(self.store) == 0

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remember that an empty list is falsy

        return not self.store



def heap_up(self, index):
Expand All @@ -57,18 +70,42 @@ def heap_up(self, index):
property is reestablished.

This could be **very** helpful for the add method.
Time complexity: ?
Space complexity: ?
Time complexity: O(log n)
Space complexity: O(log n)
Comment on lines +73 to +74

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✨ Yes, this function is where the complexity in add comes from.

"""
pass
if index == 0:
return
if self.store[index].key < self.store[(index - 1) // 2].key:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notice that you repeated the (index - 1) // 2 calculation a few times. Consider performing that once and storing it in a local variable.

self.swap(index, (index - 1) // 2)
self.heap_up((index - 1) // 2)

def heap_down(self, index):
""" This helper method takes an index and
moves the corresponding element down the heap if it's
larger than either of its children and continues until
the heap property is reestablished.
"""
pass

if index * 2 + 1 < len(self.store):
if index * 2 + 2 < len(self.store):
if self.store[index * 2 + 1].key > self.store[index * 2 + 2].key:
if self.store[index * 2 + 1].key < self.store[index].key:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👀 The one we want to swap is the smaller of the two children. This will swap the larger of the two children. This is the other part causing the test failure for the remove ordering.

self.swap(index, index * 2 + 1)
self.heap_down(index * 2 + 1)
else:
return
else:
if self.store[index * 2 + 2].key < self.store[index].key:
self.swap(index, index * 2 + 2)
self.heap_down(index * 2 + 2)
else:
return
else:
if self.store[index * 2 + 1].key < self.store[index].key:
self.swap(index, index * 2 + 1)
self.heap_down(index * 2 + 1)
Comment on lines +105 to +106

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👀 Notice that the branches that do anything all culminate in swapping with an index and the making the recursive heap call on that other index.

Consider restructuring so that we calculate what the other index is, and then we could write the swap and heap calls just once.

else:
return


def swap(self, index_1, index_2):
Expand Down