Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Citlalli Z (Cedar) #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
19 changes: 14 additions & 5 deletions heaps/heap_sort.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@


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 logn)
Space Complexity: O(n)
Comment on lines +4 to +5

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
heap = MinHeap()

for num in list:
heap.add(num)

index = 0
while not heap.empty():
list[index] = heap.remove()
index += 1
Comment on lines +12 to +15

Choose a reason for hiding this comment

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

Note the since this isn't a fully in-place solution (the MinHeap has a O(n) internal store), we don't necessarily need to modify the passed in list. The tests are written to check the return value, so we could unpack the heap into a new result list to avoid mutating the input.

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

    return result


return list
59 changes: 46 additions & 13 deletions heaps/min_heap.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@


class HeapNode:

def __init__(self, key, value):
Expand All @@ -19,18 +21,29 @@ 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 +24 to +25

Choose a reason for hiding this comment

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

✨ Great. We should note that it's due to the recursive call in heap_up that the space complexity is O(log n). If heap_up were implemented iteratively, this would only require O(1) space complexity since the stack size wouldn't depend on the heap depth.

"""
pass
if value == None:

Choose a reason for hiding this comment

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

👀 Prefer using is to compare to None

value = key
new_node =HeapNode(key, value)

self.store.append(new_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 +38 to +39

Choose a reason for hiding this comment

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

✨ Nice. Just as for add, the log space complexity remove is due to the recursive heap_down implementation. We could achieve O(1) space complexity if we used an iterative approach.

"""
pass
if len(self.store) ==0:

Choose a reason for hiding this comment

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

👀 We have an empty helper we could use here

return None
self.swap(0, len(self.store) -1)
min = self.store.pop()
self.heap_down(0)
return min.value



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)
Comment on lines +60 to +61

Choose a reason for hiding this comment

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

"""
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,38 @@ 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.

✨ Here's where the O(log n) space complexity in add comes from. Since heap_up calls itself recursively, the worst case for the stack growth will be when the value needs to be moved all the way up the heap, which will have a height of log n. So the space complexity (due to the stack growth) is also O(log n). If we implemented this instead with an iterative approach, the space complexity would be O(1).

"""
pass
if index == 0:
return

parent = (index -1) // 2
if self.store[parent].key > self.store[index].key:
self.swap(index, parent)
self.heap_up(parent)

def heap_down(self, index):

Choose a reason for hiding this comment

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

✨ Nice approach of first determining the candidate child, then deciding whether the swap is required.

Though not prompted, like heap_up, heap_down is also O(log n) in both time and space complexity. The worst case for re-heapifying is if the new root need to move back down to a leaf, and so the stack growth will be the height of the heap, which is log n. If we implemented this instead with an iterative approach, the space complexity would instead be O(1).

""" 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
left_child = index * 2 + 1
right_child = index * 2 + 2

if left_child < len(self.store):
if right_child < len(self.store):
if self.store[left_child].key < self.store[right_child].key:
child = left_child
else:
child = right_child
else:
child = left_child

if self.store[child].key < self.store[index].key:
self.swap(child, index)
self.heap_down(child)


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