Convert Doubly Linked List to Array II - Problem

You are given an arbitrary node from a doubly linked list, which contains nodes that have a next pointer and a previous pointer. Return an integer array which contains the elements of the linked list in order.

Since you start from an arbitrary node (not necessarily the head), you need to first find the beginning of the list, then traverse from head to tail to collect all values.

Input & Output

Example 1 — Starting from Middle
$ Input: node pointing to value 3 in list [1,2,3,4,5]
Output: [1,2,3,4,5]
💡 Note: Starting from node with value 3, we move backward to find head (value 1), then traverse forward collecting all values: 1→2→3→4→5
Example 2 — Starting from Head
$ Input: node pointing to value 10 in list [10,20,30]
Output: [10,20,30]
💡 Note: Starting from head node (value 10), no backward movement needed, just traverse forward: 10→20→30
Example 3 — Single Node
$ Input: node pointing to value 42 in list [42]
Output: [42]
💡 Note: List has only one node, so it's both head and tail. 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 doubly linked list

Visualization

Tap to expand
Convert Doubly Linked List to Array II INPUT Doubly Linked List 1 2 3 4 5 Current Node Input Node node = 3 (arbitrary position) Node Structure node.prev (previous) node.val (value) node.next (next) ALGORITHM STEPS 1 Find Head Traverse backwards using node.prev until null 3 --> 2 --> 1 --> null (HEAD!) 2 Initialize Result Create empty array result = [] 3 Traverse Forward From head, use node.next to visit all nodes 1 --> 2 --> 3 --> 4 --> 5 4 Collect Values Add each node.val to result array FINAL RESULT Output Array 1 [0] 2 [1] 3 [2] 4 [3] 5 [4] Output: [1, 2, 3, 4, 5] OK - Array in Order! Complexity Time: O(n) Space: O(n) n = number of nodes Key Insight: Since we start from an arbitrary node (not necessarily the head), we must first navigate backwards using the prev pointers until we reach the head (where prev is null). Only then can we traverse forward from head to tail, collecting all values in the correct order for our result array. TutorialsPoint - Convert Doubly Linked List to Array II | Single Pass with Size Calculation
Asked in
Microsoft 25 Amazon 20 Google 15
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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