Skip to content

Instantly share code, notes, and snippets.

@seanchen1991
Last active May 19, 2021 19:49
Show Gist options
  • Save seanchen1991/4a2c000548c76ddfb09426a343de3f18 to your computer and use it in GitHub Desktop.
Save seanchen1991/4a2c000548c76ddfb09426a343de3f18 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