1683. Flip Deque

Easy1.5 points estimatedQueueDesign

A card dealer keeps a row of cards that can be extended and trimmed at both ends, and sometimes the whole row is turned around. Design a class FlipDeque that supports these operations on a sequence of non-negative integers, initially empty.

pushFront(x) inserts x before the first element and pushBack(x) inserts it after the last. popFront() removes and returns the first element and popBack() removes and returns the last element; both return -1 when the sequence is empty. reverse() reverses the order of the sequence, and size() returns the number of elements. Every operation, including reverse, must run in O(1) amortised time, so do not move the elements when reversing; just remember which end is currently the front.

Example 1

Input:
operations = ["FlipDeque","pushBack","pushBack","pushFront","reverse","popFront","popBack","size"]arguments = [[],[1],[2],[0],[],[],[],[]]
Output:
[null,null,null,null,null,2,0,1]
Explanation:

The deque holds 0,1,2; after reverse it holds 2,1,0, so popFront returns 2 and popBack returns 0, leaving size 1.

Example 2

Input:
operations = ["FlipDeque","pushFront","reverse","pushFront","popBack","popBack","popBack"]arguments = [[],[5],[],[6],[],[],[]]
Output:
[null,null,null,null,5,6,-1]
Explanation:

The sequence is [5]; pushFront(6) gives [6, 5], so popBack returns 5, then 6, and then -1 because the deque is empty.

Example 3

Input:
operations = ["FlipDeque","popFront","reverse","size","popBack"]arguments = [[],[],[],[],[]]
Output:
[null,-1,null,0,-1]
Explanation:

Popping an empty deque returns -1 and reversing an empty deque changes nothing.

Constraints

0 ≤ x ≤ 109; at most 1000 calls in total

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.

Expected complexity

Time
O(1) per call
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.