Advertisement

Reorder List - LeetCode 143 Solution

Reorder List - Complete Solution Guide

Reorder List is LeetCode problem 143, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You are given the head of a singly linked-list. The list can be represented as: L 0 → L 1 → … → L n - 1 → L n Reorder the list to be on the following form: L 0 → L n → L 1 → L n - 1 → L 2 → L n - 2 → … You may not modify the values in the list's nodes. Only nodes themselves may be changed. Example 1: Input: head = [1,2,3,4] Output: [1,4,2,3] Example 2: Input: head = [1,2,3,4,5] Output: [1,5,2,4,3] Constraints: The number of nodes in

Detailed Explanation

The problem asks us to reorder a singly linked list from L0 -> L1 -> ... -> Ln-1 -> Ln to L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 -> ... without modifying the values within the nodes, only rearranging the nodes themselves. Essentially, we need to interweave the first and second halves of the linked list.

Solution Approach

The provided solution uses a three-step approach: 1) Find the middle of the linked list using the fast and slow pointer technique. 2) Reverse the second half of the linked list. 3) Merge the first half and the reversed second half. Finding the middle allows us to divide the list. Reversing the second half prepares it for interweaving. The merging step then creates the final reordered list.

Step-by-Step Algorithm

  1. Step 1: Find the middle of the linked list. Use two pointers, 'slow' and 'fast'. 'Fast' moves twice as fast as 'slow'. When 'fast' reaches the end, 'slow' will be at the middle.
  2. Step 2: Reverse the second half of the linked list starting from 'slow.next'. Set 'slow.next' to null to separate the first and second halves. Iteratively reverse the second half by changing the 'next' pointers.
  3. Step 3: Merge the first half and the reversed second half. Iterate through both halves, interweaving the nodes by updating the 'next' pointers accordingly. Take nodes alternately from each list until one of the lists is exhausted.

Key Insights

  • Insight 1: The core idea is to divide the linked list into two halves, reverse the second half, and then merge (interweave) them.
  • Insight 2: Using the fast and slow pointer technique helps in efficiently finding the middle of the linked list.
  • Insight 3: In-place manipulation is crucial for achieving O(1) space complexity, which requires careful management of pointers during reversal and merging.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: Linked List, Two Pointers, Stack, Recursion.

Companies

Asked at: Arista Networks, Goldman Sachs, LinkedIn, TikTok, Yahoo.