Skip to content

Instantly share code, notes, and snippets.

@iykekings
Forked from seanchen1991/sort_stack.md
Created December 16, 2019 14:01
Show Gist options
  • Save iykekings/1cc2155e0bbd7cb9073209ab2fdd5fd4 to your computer and use it in GitHub Desktop.
Save iykekings/1cc2155e0bbd7cb9073209ab2fdd5fd4 to your computer and use it in GitHub Desktop.
Problem description for the Sort Stack problem in JS

Sort Elements in a Stack

Given a Stack class like the following:

class Stack {
  constructor() {
    this.storage = [];
  }

  push(item) {
    this.storage.push(item);
  }

  pop() {
    return this.storage.pop();
  }

  peek() {
    return this.storage[this.storage.length-1];
  }

  isEmpty() {
    return this.storage.length === 0;
  }

  printContents() {
    this.storage.forEach(elem => console.log(elem));
  }
}

Write a function sortStack that receives a stack of integers and returns another stack containing those same integers in sorted order. You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure.

Example:

const s = new Stack();
s.push(4);
s.push(10);
s.push(8);
s.push(5);
s.push(1);
s.push(6);

const sortedStack = sortStack(s); // sortedStack is also a Stack instance

sortedStack.printContents();  // should print 1, 4, 5, 6, 8, 10

Analyze the time and space complexity of your solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment