Convert Doubly Linked List to Array II Problem
#3294
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3294.
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.
Example 1:
Input: head = [1,2,3,4,5], node = 5
Output: [1,2,3,4,5]
Example 2:
Input: head = [4,5,6,7,8], node = 8
Output: [4,5,6,7,8]
Constraints:
- The number of nodes in the given list is in the range
[1, 500]. 1 <= Node.val <= 1000- All nodes have unique
Node.val.
Solution
Approach: Walk to the Head, Then Traverse
The given node can be anywhere in the list. Move backwards through prev until reaching the head (the node with no prev), then walk forward through next, appending each value to the answer.
Complexity:
- Time complexity:
O(n) - Space complexity:
O(1), ignoring the output
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev=None, next=None):
self.val = val
self.prev = prev
self.next = next
"""
class Solution:
def toArray(self, node: "Optional[Node]") -> List[int]:
while node.prev:
node = node.prev
ans = []
while node:
ans.append(node.val)
node = node.next
return ans