MediumArrayLinked ListDesignQueue

Design Circular Deque

1 approach, code in every language

Problem description

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.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free