Class Deque<E, R>

Deque implemented with circular buckets allowing O(1) amortized push/pop at both ends.

Time O(1), Space O(1)

// prize roulette
class PrizeRoulette {
private deque: Deque<string>;

constructor(prizes: string[]) {
// Initialize the deque with prizes
this.deque = new Deque<string>(prizes);
}

// Rotate clockwise to the right (forward)
rotateClockwise(steps: number): void {
const n = this.deque.length;
if (n === 0) return;

for (let i = 0; i < steps; i++) {
const last = this.deque.pop(); // Remove the last element
this.deque.unshift(last!); // Add it to the front
}
}

// Rotate counterclockwise to the left (backward)
rotateCounterClockwise(steps: number): void {
const n = this.deque.length;
if (n === 0) return;

for (let i = 0; i < steps; i++) {
const first = this.deque.shift(); // Remove the first element
this.deque.push(first!); // Add it to the back
}
}

// Display the current prize at the head
display() {
return this.deque.first;
}
}

// Example usage
const prizes = ['Car', 'Bike', 'Laptop', 'Phone', 'Watch', 'Headphones']; // Initialize the prize list
const roulette = new PrizeRoulette(prizes);

// Display the initial state
console.log(roulette.display()); // 'Car' // Car

// Rotate clockwise by 3 steps
roulette.rotateClockwise(3);
console.log(roulette.display()); // 'Phone' // Phone

// Rotate counterclockwise by 2 steps
roulette.rotateCounterClockwise(2);
console.log(roulette.display()); // 'Headphones'
// sliding window
// Maximum function of sliding window
function maxSlidingWindow(nums: number[], k: number): number[] {
const n = nums.length;
if (n * k === 0) return [];

const deq = new Deque<number>();
const result: number[] = [];

for (let i = 0; i < n; i++) {
// Delete indexes in the queue that are not within the window range
if (deq.length > 0 && deq.first! === i - k) {
deq.shift();
}

// Remove all indices less than the current value from the tail of the queue
while (deq.length > 0 && nums[deq.last!] < nums[i]) {
deq.pop();
}

// Add the current index to the end of the queue
deq.push(i);

// Add the maximum value of the window to the results
if (i >= k - 1) {
result.push(nums[deq.first!]);
}
}

return result;
}

const nums = [1, 3, -1, -3, 5, 3, 6, 7];
const k = 3;
console.log(maxSlidingWindow(nums, k)); // [3, 3, 5, 5, 6, 7]

Type Parameters

  • E = any
  • R = any
    1. Operations at Both Ends: Supports adding and removing elements at both the front and back of the queue. This allows it to be used as a stack (last in, first out) and a queue (first in, first out).
    2. Efficient Random Access: Being based on an array, it offers fast random access capability, allowing constant time access to any element.
    3. Continuous Memory Allocation: Since it is based on an array, all elements are stored contiguously in memory, which can bring cache friendliness and efficient memory access.
    4. Efficiency: Adding and removing elements at both ends of a deque is usually very fast. However, when the dynamic array needs to expand, it may involve copying the entire array to a larger one, and this operation has a time complexity of O(n).
    5. Performance jitter: Deque may experience performance jitter, but DoublyLinkedList will not

Hierarchy

  • LinearBase<E, R>
    • Deque

Constructors

  • Create a Deque and optionally bulk-insert elements.

    Type Parameters

    • E = any
    • R = any

    Parameters

    • Optionalelements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R> = []

      Iterable (or iterable-like) of elements/records to insert.

    • Optionaloptions: DequeOptions<E, R>

      Options such as bucketSize, toElementFn, and maxLen.

    Returns Deque<E, R>

    New Deque instance.

    Time O(N), Space O(N)

Properties

_toElementFn?: ((rawElement: R) => E)

The converter used to transform a raw element (R) into a public element (E).

Time O(1), Space O(1).

Accessors

  • get bucketFirst(): number
  • Get the index of the first bucket in use.

    Returns number

    Zero-based bucket index.

    Time O(1), Space O(1)

  • get bucketLast(): number
  • Get the index of the last bucket in use.

    Returns number

    Zero-based bucket index.

    Time O(1), Space O(1)

  • get first(): undefined | E
  • Get the first element without removing it.

    Returns undefined | E

    First element or undefined.

    Time O(1), Space O(1)

  • get firstInBucket(): number
  • Get the index inside the first bucket.

    Returns number

    Zero-based index within the first bucket.

    Time O(1), Space O(1)

  • get last(): undefined | E
  • Get the last element without removing it.

    Returns undefined | E

    Last element or undefined.

    Time O(1), Space O(1)

  • get lastInBucket(): number
  • Get the index inside the last bucket.

    Returns number

    Zero-based index within the last bucket.

    Time O(1), Space O(1)

  • get length(): number
  • Get the number of elements in the deque.

    Returns number

    Current length.

    Time O(1), Space O(1)

  • get maxLen(): number
  • Upper bound for length (if positive), or -1 when unbounded.

    Returns number

    Maximum allowed length.

    Time O(1), Space O(1)

  • get toElementFn(): undefined | ((rawElement: R) => E)
  • Exposes the current toElementFn, if configured.

    Returns undefined | ((rawElement: R) => E)

    The converter function or undefined when not set.

    Time O(1), Space O(1).

Methods

  • (Protected) Create an empty instance of the same concrete class.

    Parameters

    • Optionaloptions: LinearBaseOptions<E, R>

      Options forwarded to the constructor.

    Returns this

    An empty like-kind deque instance.

    Time O(1), Space O(1)

  • (Protected) Create a like-kind deque seeded by elements.

    Type Parameters

    • T = E
    • RR = R

    Parameters

    • Optionalelements: IterableWithSizeOrLength<T> | IterableWithSizeOrLength<RR> = []

      Iterable used to seed the new deque.

    • Optionaloptions: DequeOptions<T, RR>

      Options forwarded to the constructor.

    Returns any

    A like-kind Deque instance.

    Time O(N), Space O(N)

  • (Protected) Translate a logical position to bucket/offset.

    Parameters

    • pos: number

      Zero-based position.

    Returns {
        bucketIndex: number;
        indexInBucket: number;
    }

    An object containing bucketIndex and indexInBucket.

    • bucketIndex: number
    • indexInBucket: number

    Time O(1), Space O(1)

  • (Protected) Iterate elements from front to back.

    Returns IterableIterator<E, any, any>

    Iterator of elements.

    Time O(N), Space O(1)

  • (Protected) Iterate elements from back to front.

    Returns IterableIterator<E, any, any>

    Iterator of elements.

    Time O(N), Space O(1)

  • (Protected) Reallocate buckets to make room near the ends.

    Parameters

    • OptionalneedBucketNum: number

      How many extra buckets to add; defaults to half of current.

    Returns void

    void

    Time O(N), Space O(N)

  • (Protected) Set the internal bucket size.

    Parameters

    • size: number

      Bucket capacity to assign.

    Returns void

    void

    Time O(1), Space O(1)

  • Returns an iterator over the structure's elements.

    Parameters

    • Rest...args: unknown[]

      Optional iterator arguments forwarded to the internal iterator.

    Returns IterableIterator<E, any, any>

    An IterableIterator<E> that yields the elements in traversal order.

    Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.

  • Insert repeated copies of an element at a position.

    Parameters

    • pos: number

      Zero-based position from the front.

    • element: E

      Element to insert.

    • Optionalnum: number = 1

      Number of times to insert (default 1).

    Returns boolean

    True if inserted.

    Time O(N), Space O(1)

  • Get the element at a given position.

    Parameters

    • pos: number

      Zero-based position from the front.

    Returns undefined | E

    Element or undefined.

    Time O(1), Space O(1)

  • Remove all elements and reset structure.

    Returns void

    void

    Time O(1), Space O(1)

  • Deep clone this deque, preserving options.

    Returns this

    A new deque with the same content and options.

    Time O(N), Space O(N)

  • Concatenate multiple containers of the same species.

    Parameters

    • Rest...items: Deque<E, R>[]

      Other lists to append.

    Returns this

    New container with combined elements (this type).

    Time O(sum(length)), Space O(sum(length))

  • Cut the deque to keep items up to index; optionally mutate in-place.

    Parameters

    • pos: number

      Last index to keep.

    • OptionalisCutSelf: boolean = false

      When true, mutate this deque; otherwise return a new deque.

    Returns Deque<E, any>

    This deque if in-place; otherwise a new deque of the prefix.

    Time O(N), Space O(1)

  • Cut the deque to keep items from index onward; optionally mutate in-place.

    Parameters

    • pos: number

      First index to keep.

    • OptionalisCutSelf: boolean = false

      When true, mutate this deque; otherwise return a new deque.

    Returns Deque<E, any>

    This deque if in-place; otherwise a new deque of the suffix.

    Time O(N), Space O(1)

  • Delete the first occurrence of a value.

    Parameters

    • element: E

      Element to remove (using the configured equality).

    Returns boolean

    True if an element was removed.

    Time O(N), Space O(1)

  • Delete the element at a given position.

    Parameters

    • pos: number

      Zero-based position from the front.

    Returns undefined | E

    Removed element or undefined.

    Time O(N), Space O(1)

  • Delete the first element matching a predicate.

    Parameters

    • predicate: ((value: E, index: number, deque: this) => boolean)

      Function (value, index, deque) → boolean.

        • (value, index, deque): boolean
        • Parameters

          • value: E
          • index: number
          • deque: this

          Returns boolean

    Returns boolean

    True if a match was removed.

    Time O(N), Space O(1)

  • Tests whether all elements satisfy the predicate.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      Function invoked for each element with signature (value, index, self).

    • OptionalthisArg: unknown

      Optional this binding for the predicate.

    Returns boolean

    true if every element passes; otherwise false.

    Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).

  • Fill a range with a value.

    Parameters

    • value: E

      Value to set.

    • start: number = 0

      Inclusive start.

    • end: number = ...

      Exclusive end.

    Returns this

    This list.

    Time O(n), Space O(1)

  • Filter elements into a new deque of the same class.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      Predicate (value, index, deque) → boolean to keep element.

    • OptionalthisArg: any

      Value for this inside the predicate.

    Returns this

    A new deque with kept elements.

    Time O(N), Space O(N)

  • Finds the first element that satisfies the predicate and returns it.

    Finds the first element of type S (a subtype of E) that satisfies the predicate and returns it.

    Type Parameters

    • S

    Parameters

    • predicate: ElementCallback<E, R, S>

      Type-guard predicate: (value, index, self) => value is S.

    • OptionalthisArg: unknown

      Optional this binding for the predicate.

    Returns undefined | S

    The matched element typed as S, or undefined if not found.

    Time O(n) in the worst case; may exit early on the first match. Space O(1).

  • Find the first index matching a predicate.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      (element, index, self) => boolean.

    • OptionalthisArg: any

      Optional this for callback.

    Returns number

    Index or -1.

    Time O(n), Space O(1)

  • Invokes a callback for each element in iteration order.

    Parameters

    • callbackfn: ElementCallback<E, R, void>

      Function invoked per element with signature (value, index, self).

    • OptionalthisArg: unknown

      Optional this binding for the callback.

    Returns void

    void.

    Time O(n), Space O(1).

  • Checks whether a strictly-equal element exists in the structure.

    Parameters

    • element: E

      The element to test with === equality.

    Returns boolean

    true if an equal element is found; otherwise false.

    Time O(n) in the worst case. Space O(1).

  • First index of a value from the left.

    Parameters

    • searchElement: E

      Value to match.

    • fromIndex: number = 0

      Start position (supports negative index).

    Returns number

    Index or -1 if not found.

    Time O(n), Space O(1)

  • Check whether the deque is empty.

    Returns boolean

    True if length is 0.

    Time O(1), Space O(1)

  • Join all elements into a string.

    Parameters

    • separator: string = ','

      Separator string.

    Returns string

    Concatenated string.

    Time O(n), Space O(n)

  • Last index of a value from the right.

    Parameters

    • searchElement: E

      Value to match.

    • fromIndex: number = ...

      Start position (supports negative index).

    Returns number

    Index or -1 if not found.

    Time O(n), Space O(1)

  • Map elements into a new deque (possibly different element type).

    Type Parameters

    • EM
    • RM

    Parameters

    • callback: ElementCallback<E, R, EM>

      Mapping function (value, index, deque) → newElement.

    • Optionaloptions: IterableElementBaseOptions<EM, RM>

      Options for the output deque (e.g., bucketSize, toElementFn, maxLen).

    • OptionalthisArg: any

      Value for this inside the callback.

    Returns Deque<EM, RM>

    A new Deque with mapped elements.

    Time O(N), Space O(N)

  • Map elements into a new deque of the same element type.

    Parameters

    • callback: ElementCallback<E, R, E>

      Mapping function (value, index, deque) → newValue.

    • OptionalthisArg: any

      Value for this inside the callback.

    Returns this

    A new deque with mapped values.

    Time O(N), Space O(N)

  • Remove and return the last element.

    Returns undefined | E

    Removed element or undefined.

    Time O(1), Space O(1)

  • Prints toVisual() to the console. Intended for quick debugging.

    Returns void

    void.

    Time O(n) due to materialization, Space O(n) for the intermediate representation.

  • Append one element at the back.

    Parameters

    • element: E

      Element to append.

    Returns boolean

    True when appended.

    Time O(1) amortized, Space O(1)

  • Append a sequence of elements.

    Parameters

    • elements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R>

      Iterable (or iterable-like) of elements/records.

    Returns boolean[]

    Array of per-element success flags.

    Time O(N), Space O(1)

  • Right-to-left reduction over elements.

    Type Parameters

    • U

    Parameters

    • callbackfn: ReduceLinearCallback<E, U>

      (acc, element, index, self) => acc.

    • initialValue: U

      Initial accumulator (optional generic overloads supported).

    Returns U

    Final accumulator.

    Time O(n), Space O(1)

  • Reverse the deque by reversing buckets and pointers.

    Returns this

    This deque.

    Time O(N), Space O(N)

  • Replace the element at a given position.

    Parameters

    • pos: number

      Zero-based position from the front.

    • element: E

      New element value.

    Returns boolean

    True if updated.

    Time O(1), Space O(1)

  • Set the equality comparator used by delete operations.

    Parameters

    • equals: ((a: E, b: E) => boolean)

      Equality predicate (a, b) → boolean.

        • (a, b): boolean
        • Parameters

          Returns boolean

    Returns this

    This deque.

    Time O(1), Space O(1)

  • Remove and return the first element.

    Returns undefined | E

    Removed element or undefined.

    Time O(1) amortized, Space O(1)

  • Create a shallow copy of a subrange.

    Parameters

    • start: number = 0

      Inclusive start (supports negative index).

    • end: number = ...

      Exclusive end (supports negative index).

    Returns this

    New list with the range (this type).

    Time O(n), Space O(n)

  • Tests whether at least one element satisfies the predicate.

    Parameters

    • predicate: ElementCallback<E, R, boolean>

      Function invoked for each element with signature (value, index, self).

    • OptionalthisArg: unknown

      Optional this binding for the predicate.

    Returns boolean

    true if any element passes; otherwise false.

    Time O(n) in the worst case; may exit early on first success. Space O(1).

  • In-place stable order via array sort semantics.

    Parameters

    • OptionalcompareFn: ((a: E, b: E) => number)

      Comparator (a, b) => number.

        • (a, b): number
        • Parameters

          Returns number

    Returns this

    This container.

    Time O(n log n), Space O(n) (materializes to array temporarily)

  • Remove and/or insert elements at a position (array-like behavior).

    Parameters

    • start: number

      Start index (clamped to [0, length]).

    • OptionaldeleteCount: number = ...

      Number of elements to remove (default: length - start).

    • Optional Rest...items: E[]

      Elements to insert after start.

    Returns this

    A new deque containing the removed elements (typed as this).

    Time O(N + M), Space O(M)

  • Snapshot elements into a reversed array.

    Returns E[]

    New reversed array.

    Time O(n), Space O(n)

  • Returns a representation of the structure suitable for quick visualization. Defaults to an array of elements; subclasses may override to provide richer visuals.

    Returns E[]

    A visual representation (array by default).

    Time O(n), Space O(n).

  • Prepend one element at the front.

    Parameters

    • element: E

      Element to prepend.

    Returns boolean

    True when prepended.

    Time O(1) amortized, Space O(1)

  • Prepend a sequence of elements.

    Parameters

    • Optionalelements: IterableWithSizeOrLength<E> | IterableWithSizeOrLength<R> = []

      Iterable (or iterable-like) of elements/records.

    Returns boolean[]

    Array of per-element success flags.

    Time O(N), Space O(1)

  • Returns an iterator over the values (alias of the default iterator).

    Returns IterableIterator<E, any, any>

    An IterableIterator<E> over all elements.

    Creating the iterator is O(1); full iteration is Time O(n), Space O(1).

  • Create a Deque from an array of elements.

    Type Parameters

    • E
    • R = any

    Parameters

    • this: Object

      Constructor (subclass) to instantiate.

    • data: E[]

      Array of elements to insert in order.

    • Optionaloptions: DequeOptions<E, R>

      Options forwarded to the constructor.

    Returns any

    A new Deque populated from the array.

    Time O(N), Space O(N)