Reorder List — LeetCode 143 Python Solution
- Problem
- #143
- Pattern
- Linked List
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … You may not modify the values in the list's nodes.
Example
L0 → L1 → … → Ln - 1 → Ln
Python solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
fast = slow = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
cur = slow.next
slow.next = None
pre = None
while cur:
t = cur.next
cur.next = pre
pre, cur = cur, t
cur = head
while pre:
t = pre.next
pre.next = cur.next
cur.next = pre
cur, pre = pre.next, tComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the linked list |
| Space | O(1) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 143. Reorder List is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75 and NeetCode 150.
Frequently asked questions
- How hard is LeetCode 143. Reorder List?
- LeetCode 143. Reorder List is rated Medium on LeetCode.
- What is the time complexity of LeetCode 143. Reorder List?
- The Python solution on this page runs in O(n), where n is the length of the linked list.
- What is the space complexity of LeetCode 143. Reorder List?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 143. Reorder List cover?
- LeetCode 143. Reorder List is tagged Stack, Recursion, Linked List and Two Pointers on LeetCode.