DEV Community

Discussion on: Daily Coding Puzzles - Nov 11th - Nov 16th

Collapse
 
aspittel profile image
Ali Spittel

Thursday - Queue from two stacks (Hacker Rank Medium)

Complete the put, pop, and peek methods in the editor below. They must perform the actions as described above.

hackerrank.com/challenges/ctci-que...

Collapse
 
clandau profile image
Courtney
function processData(input) {
    class Node {...}
    class Stack {...}
    const inputArray = input.split('\n');
    let stackIn = new Stack();
    let stackOut = new Stack();
    let valArry, result = '';
    for(let i=1; i<=inputArray[0]; i++) {
        valArry = inputArray[i].split(' ');
        switch(valArry[0]) {
            case '1':
                enqueue(valArry[1]);
                break;
            case '2':
                dequeue();
                break;
            case '3':
                result += `${front()}\n`;
                break;
        }
    } 

    function enqueue(val) {
        stackIn.push(val);
    }

    function dequeue() {
        if(stackOut.size === 0) {
            while(stackIn.size > 0) {
                let item = stackIn.pop();
                stackOut.push(item);
            }
        }
        stackOut.pop();
    }

    function front() {
        if(stackOut.size === 0) {
            while(stackIn.size > 0) {
                let item = stackIn.pop();
                stackOut.push(item);
            }
        }
        return stackOut.peek();
    }
    return process.stdout.write(result);
} 
Collapse
 
jay profile image
Jay

Rust Solution:

struct MyQueue {
    stack1: Vec<i32>,
    stack2: Vec<i32>,
}

impl MyQueue {
    pub fn new() -> Self {
        MyQueue {
            stack1: vec![],
            stack2: vec![],
        }
    }

    pub fn push(&mut self, x: i32) {
        self.stack1.push(x);
    }

    pub fn pop(&mut self) {
        if self.stack2.is_empty() {
            while !self.stack1.is_empty() {
                self.stack2.push(self.stack1.pop().unwrap());
            }
        }
        self.stack2.pop();
    }

    pub fn peek(&mut self) -> i32 {
        if self.stack2.is_empty() {
            while !self.stack1.is_empty() {
                self.stack2.push(self.stack1.pop().unwrap());
            }
        }
        *self.stack2.last().unwrap()
    }
}
Collapse
 
susickypavel profile image
Pavel Susicky
const Queue = {
    in: [],
    out: [],
    enqueue: function(x) {
        this.in.push(x);
    },
    dequeue: function() {
        if (this.out.length == 0) {
            while (this.in.length != 0) {
                this.out.push(this.in.pop());
            }
        }
        return this.out.length == 0 ? "Cannot dequeue" : this.out.pop();
    },
    front: function() {
        if (this.out.length == 0) {
            while (this.in.length != 0) {
                this.out.push(this.in.pop());
            }
        }
        return this.out.length == 0 ? "Cannot show front value" : this.out[this.out.length - 1];
    }
};
Collapse
 
choroba profile image
E. Choroba

Perl solution. Passes all the tests on HackerRank.

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

{   package Queue;

    use enum qw( LIFO FIFO );

    sub new  { bless [[], []], shift }
    sub Push { push @{ $_[0][LIFO] }, $_[1]; }
    sub Pop  { @{ $_[0][FIFO] } or $_[0]->_restack; pop @{ $_[0][FIFO] }; }
    sub Peek { @{ $_[0][FIFO] } or $_[0]->_restack; say $_[0][FIFO][-1]; }
    sub _restack {
        push @{ $_[0][FIFO] }, pop @{ $_[0][LIFO] } while @{ $_[0][LIFO] };
    }
}

my %dispatch = (
    1 => 'Push',
    2 => 'Pop',
    3 => 'Peek',
);

my $q = 'Queue'->new;

<>;  # skip the 1st line.
while (<>) {
    my ($operation, $argument) = split;
    $q->${\$dispatch{$operation}}($argument);
}
Collapse
 
aspittel profile image
Ali Spittel
class MyQueue(object):
    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def peek(self):
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]

    def pop(self):
        if not self.stack2: 
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()

    def put(self, value):
        self.stack1.append(value)