Convert Doubly Linked List to Array II - Problem

You are dropped into the middle of a doubly linked list adventure! ๐Ÿš€

Given an arbitrary node from a doubly linked list (could be anywhere - beginning, middle, or end), your mission is to reconstruct the entire linked list and return it as an integer array in the correct order.

Each node in this doubly linked list has:

  • val: The integer value stored in the node
  • next: Pointer to the next node (or null if it's the tail)
  • prev: Pointer to the previous node (or null if it's the head)

The challenge is that you don't know where you are in the list! You need to navigate both directions to find the complete sequence and return the elements in their natural order from head to tail.

Goal: Return an integer array containing all elements of the doubly linked list in order from head to tail.

Input & Output

example_1.py โ€” Basic case starting from middle
$ Input: node = ListNode(2) # Given node in middle of [1,2,3,4]
โ€บ Output: [1, 2, 3, 4]
๐Ÿ’ก Note: Starting from node with value 2, we navigate backward to find head (1), then traverse forward to collect all values [1,2,3,4]
example_2.py โ€” Starting from head
$ Input: node = ListNode(1) # Given node is the head of [1,2,3]
โ€บ Output: [1, 2, 3]
๐Ÿ’ก Note: Starting from the head node, we don't need to move backward. We simply traverse forward to collect [1,2,3]
example_3.py โ€” Single node list
$ Input: node = ListNode(42) # Single node with no connections
โ€บ Output: [42]
๐Ÿ’ก Note: Single node has no prev or next connections, so the result is simply [42]

Constraints

  • The number of nodes in the list is in the range [1, 104]
  • -105 โ‰ค Node.val โ‰ค 105
  • The given node is guaranteed to be part of a valid doubly linked list
  • All nodes in the list have proper prev and next connections

Visualization

Tap to expand
STARTYou are hereBeginningEndStep 1: Find startStep 2: Walk entire bridgeResult: Complete bridge map (array)[ section1, section2, section3, section4, section5 ]๐ŸŽฏ Key InsightOnce you find either end of the bridge, you can walkthe entire length in one direction without backtracking!
Understanding the Visualization
1
Assess Position
You start at an unknown position on the bridge (arbitrary node)
2
Find Beginning
Walk backward until you reach the start of the bridge (head node)
3
Map Bridge
Walk forward from start to end, recording each section (build result array)
Key Takeaway
๐ŸŽฏ Key Insight: In a doubly linked list, once you reach either endpoint (head or tail), you can traverse the entire structure efficiently in one direction, making this a linear time problem with optimal solution.
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
23.4K Views
Medium Frequency
~15 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