This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).

Solution Notebook

Problem: Implement SetOfStacks that wraps a list of stacks, where each stack is bound by a capacity.

Constraints

  • Can we assume we already have a stack class that can be used for this problem?
    • Yes
  • If a stack becomes full, we should automatically create one?
    • Yes
  • If a stack becomes empty, should we delete it?
    • Yes

Test Cases

  • Push and pop on an empty stack
  • Push and pop on a non-empty stack
  • Push on a capacity stack to create a new one
  • Pop on a one element stack to destroy it

Algorithm

Push

  • If there are no stacks or the last stack is full
    • Create a new stack
  • Push to the new stack

Complexity:

  • Time: O(1)
  • Space: O(1)

Pop

  • If there are no stacks, return None
  • Else if the last stack has one element
    • Pop the last element's data
    • Delete the now empty stack
    • Update the last stack pointer
  • Else Pop the last element's data
  • Return the last element's data

Complexity:

  • Time: O(1)
  • Space: O(1)

Code


In [1]:
%run ../stack/stack.py

In [2]:
class StackWithCapacity(Stack):

    def __init__(self, top=None, capacity=10):
        self.capacity = capacity
        self.num_items = 0
        super(StackWithCapacity, self).__init__(top)

    def push(self, data):
        if self.num_items < self.capacity:
            super(StackWithCapacity, self).push(data)
            self.num_items += 1
        else:
            raise Exception('Stack full')

    def pop(self):
        data = super(StackWithCapacity, self).pop()
        self.num_items -= 1
        return data

    def is_full(self):
        return self.num_items == self.capacity


class SetOfStacks(object):

    def __init__(self, capacity):
        self.capacity = capacity
        self.stacks = []
        self.last_stack = None

    def push(self, data):
        if self.last_stack is None or self.last_stack.is_full():
            self.last_stack = StackWithCapacity(None, self.capacity)
            self.stacks.append(self.last_stack)
        self.last_stack.push(data)

    def pop(self):
        if self.last_stack is None:
            return
        elif self.last_stack.top.next is None:
            data = self.last_stack.pop()
            self.stacks.pop()
            num_stacks = len(self.stacks)
            if num_stacks == 0:
                self.last_stack = None
            else:
                self.last_stack = self.stacks[num_stacks-1]
        else:
            data = self.last_stack.pop()
        return data

Unit Test


In [3]:
%%writefile test_set_of_stacks.py
from nose.tools import assert_equal


class TestSetOfStacks(object):

    def test_set_of_stacks(self):
        print('Test: Push on an empty stack')
        capacity = 2
        stacks = SetOfStacks(capacity)
        stacks.push(3)

        print('Test: Push on a non-empty stack')
        stacks.push(5)

        print('Test: Push on a capacity stack to create a new one')
        stacks.push('a')

        print('Test: Pop on a one element stack to destroy it')
        assert_equal(stacks.pop(), 'a')

        print('Test: Pop general case')
        assert_equal(stacks.pop(), 5)
        assert_equal(stacks.pop(), 3)

        print('Test: Pop on no elements')
        assert_equal(stacks.pop(), None)

        print('Success: test_set_of_stacks')


def main():
    test = TestSetOfStacks()
    test.test_set_of_stacks()


if __name__ == '__main__':
    main()


Overwriting test_set_of_stacks.py

In [4]:
%run -i test_set_of_stacks.py


Test: Push on an empty stack
Test: Push on a non-empty stack
Test: Push on a capacity stack to create a new one
Test: Pop on a one element stack to destroy it
Test: Pop general case
Test: Pop on no elements
Success: test_set_of_stacks