MediumArrayLinked ListDesignQueue

Design Circular Deque

LeetCode
1 approach, code in all languages

Design a double-ended queue with a fixed capacity, commonly called a circular deque. It is created with a maximum size k and must support inserting and removing elements at both ends while never exceeding that capacity.

Implement the MyCircularDeque class with these operations: the constructor MyCircularDeque(k) sets the capacity; insertFront(value) and insertLast(value) add an element at the front or back and return whether the operation succeeded; deleteFront() and deleteLast() remove from the front or back and return whether the operation succeeded; getFront() and getRear() return the front or rear element (or -1 when empty); isEmpty() and isFull() report the current state.

Every operation must run in constant time.

Example 1

Input: ["MyCircularDeque","insertLast","insertLast","insertFront","insertFront","getRear","isFull","deleteLast","insertFront","getFront"] [[3],[1],[2],[3],[4],[],[],[],[4],[]]

Output: [null,true,true,true,false,2,true,true,true,4]

Capacity 3. insertLast(1) and insertLast(2) succeed, insertFront(3) succeeds, insertFront(4) fails because it is full; getRear() is 2, isFull() is true; deleteLast() removes 2; insertFront(4) succeeds; getFront() is 4.

Example 2

Input: ["MyCircularDeque","insertFront","getFront","isEmpty","deleteFront","isEmpty"] [[1],[8],[],[],[],[]]

Output: [null,true,8,false,true,true]

Capacity 1. insertFront(8) succeeds, getFront() is 8, isEmpty() is false; after deleteFront() the deque is empty again.

Constraints

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, and isFull.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now