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 nodenext: Pointer to the next node (ornullif it's the tail)prev: Pointer to the previous node (ornullif 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
prevandnextconnections
Visualization
Tap to expand
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code