Doubly Linked List - Problem

Implement a doubly linked list with bidirectional traversal, insertion, and deletion operations at any position.

Your doubly linked list should support the following operations:

  • insertAtHead(val) - Insert a new node with given value at the beginning
  • insertAtTail(val) - Insert a new node with given value at the end
  • insertAtIndex(index, val) - Insert a new node at the specified index
  • deleteAtIndex(index) - Delete the node at the specified index
  • get(index) - Get the value of the node at the specified index
  • toArray() - Return all values as an array for testing

The doubly linked list should maintain both forward and backward pointers, allowing efficient bidirectional traversal.

Input & Output

Example 1 — Basic Operations
$ Input: operations = [["insertAtHead", 1], ["insertAtTail", 2], ["insertAtIndex", 1, 3], ["get", 0], ["toArray"]]
Output: [null, null, null, 1, [1, 3, 2]]
💡 Note: insertAtHead(1) → list: [1], insertAtTail(2) → list: [1,2], insertAtIndex(1,3) → list: [1,3,2], get(0) returns 1, toArray() returns [1,3,2]
Example 2 — Delete Operations
$ Input: operations = [["insertAtHead", 5], ["insertAtTail", 10], ["deleteAtIndex", 0], ["toArray"]]
Output: [null, null, null, [10]]
💡 Note: insertAtHead(5) → list: [5], insertAtTail(10) → list: [5,10], deleteAtIndex(0) removes first element → list: [10], toArray() returns [10]
Example 3 — Invalid Index
$ Input: operations = [["insertAtHead", 7], ["get", 5], ["deleteAtIndex", 10], ["toArray"]]
Output: [null, -1, null, [7]]
💡 Note: insertAtHead(7) → list: [7], get(5) returns -1 (invalid index), deleteAtIndex(10) does nothing (invalid index), toArray() returns [7]

Constraints

  • 1 ≤ operations.length ≤ 1000
  • -1000 ≤ val ≤ 1000
  • 0 ≤ index ≤ size
  • get() returns -1 for invalid indices

Visualization

Tap to expand
INPUT: Node StructureALGORITHM: OperationsRESULT: Linked ListprevVALnextDoubly Linked Nodewith bidirectional pointers1Check index position2Choose head or tail direction3Traverse optimal path4Perform operation123HEADTAILBidirectional LinksKey Insight:Maintaining both forward and backward pointers enables O(n/2) average traversalby choosing the shorter path from either head or tail to target position.TutorialsPoint - Doubly Linked List | Bidirectional Optimization
Asked in
Google 42 Amazon 38 Microsoft 29 Facebook 25
34.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen