With stay-at-home orders having no end in sight, I decided to use this time to focus on all the things I've been putting off because of lacking time. In order to hold myself accountable, I'm using daily blogs to track what I learned that day, no matter how small or basic it might be.


Me, sitting in front of the computer



Udemy: The Coding Interview boot camp:
Algorithms + Data Structures

Solidified stacks and queues knowledge by solving the 'queue from stacks' problem. The problem has you building a queue class that has all the functionality of a queue, but is built on two stacks (instead of using a single array, like you typically would in JavaScript). It's wacky. It's the most impractical thing ever. But it's yet another problem to keep you on your toes, and (allegedly) it demonstrates that you know how both queues and stacks work. It's definitely fun to do just for the heck of it, but I'd legit be so confused if the first time I ever heard of this problem was in an interview.

So, here it is! The code snippet below is assuming a stack class has already been created in another file and is being imported for use in this file. Instances of this Queue class will be able to call .add("record") to add a new record to the rear, .peek() to see what element is at the front, and .pop() to return the element from the front. Note that 'front' and 'rear' are referring to the queue, not the two stacks this queue class is being built with.

This is where it really gets confusing. Queues are first in, first out. Stacks are first in, last out. So, in order to have the methods that were mentioned above work, there is going to have to be a lot of moving around of the elements. See if you can wrap your brain around this doozy:

const stack = require(./stack);

class Queue {
  constructor() {
    this.first = new Stack();
    this.second = new Stack();
  }

  add(record) {
    this.first.push(record);
  }

  remove() {
    while(this.first.peek()) {
      this.second.push(this.first.pop());
    }

    const record = this.second.pop();

    while(this.second.peek()) {
      this.first.push(this.first.pop());
    }

    return record;
  }

  peek() {
    while(this.first.peek()) {
      this.second.push(this.first.pop());
    }

    const record = this.second.peek();

    while(this.second.peek()) {
      this.first.push(this.second.pop());
    }

    return record;
  }
}

See what I mean, it's wacky! And yes, you read it right, to remove or peek at an element, it has to move all elements in the first stack before it can access the element that is in front of the queue. Then, it has to move everything back to the first, so that it is ready for whatever next method is called on it.


Codecademy: SQL

BRB. Learning now!