jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
20 stars 3 forks source link

Queue using Stack #104

Closed jsartisan closed 5 days ago

jsartisan commented 6 days ago

Info

difficulty: easy
title: Queue using Stack
type: question
template: javascript
tags: javascript

Question

Certainly! Here is the question, boilerplate implementation, and Jest tests for implementing a queue using two stacks:

Implement a queue data structure using stacks in JavaScript. A queue follows the First-In-First-Out (FIFO) principle. Your queue should have the following methods:

Use the following example to understand how the queue should work:

class QueueUsingStacks {
  // Your implementation here
}

const queue = new QueueUsingStacks();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.front()); // 1
console.log(queue.dequeue()); // 1
console.log(queue.size()); // 1
console.log(queue.isEmpty()); // false
queue.dequeue();
console.log(queue.isEmpty()); // true

Template

index.js

export class QueueUsingStacks {
  // Your code here
}

index.test.js

import { QueueUsingStacks } from './index';

describe('QueueUsingStacks class', () => {
  let queue;

  beforeEach(() => {
    queue = new QueueUsingStacks();
  });

  test('should enqueue elements to the queue', () => {
    queue.enqueue(1);
    queue.enqueue(2);
    expect(queue.size()).toBe(2);
    expect(queue.front()).toBe(1);
  });

  test('should dequeue elements from the queue', () => {
    queue.enqueue(1);
    queue.enqueue(2);
    expect(queue.dequeue()).toBe(1);
    expect(queue.size()).toBe(1);
    expect(queue.dequeue()).toBe(2);
    expect(queue.size()).toBe(0);
  });

  test('should return undefined when dequeuing from an empty queue', () => {
    expect(queue.dequeue()).toBe(undefined);
  });

  test('should return the front element without removing it', () => {
    queue.enqueue(1);
    queue.enqueue(2);
    expect(queue.front()).toBe(1);
    expect(queue.size()).toBe(2);
  });

  test('should return undefined when peeking the front element of an empty queue', () => {
    expect(queue.front()).toBe(undefined);
  });

  test('should check if the queue is empty', () => {
    expect(queue.isEmpty()).toBe(true);
    queue.enqueue(1);
    expect(queue.isEmpty()).toBe(false);
  });

  test('should return the correct size of the queue', () => {
    expect(queue.size()).toBe(0);
    queue.enqueue(1);
    queue.enqueue(2);
    expect(queue.size()).toBe(2);
  });
});

package.json

{
  "dependencies": {},
  "main": "/index.js",
  "devDependencies": {}
}
github-actions[bot] commented 6 days ago

105 - Pull Request updated.