AlgoMaster Logo

Rotate List

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Convert to Array

Intuition:

The basic idea in this approach is to first convert the linked list to an array. Once we have the array representation, rotating the list becomes straightforward. After performing the rotation on the array, we convert it back to a linked list.

Steps:

  1. Convert the linked list to an array.
  2. Rotate the array k times to the right.
  3. Convert the array back to a linked list.

Code:

2. Iterative In-Place Rotation

Intuition:

Without converting to an array, we can perform the rotations directly on the linked list. This involves finding the new head and tail of the list after rotation.

Steps:

  1. Count the length of the list.
  2. Adjust k to handle cases where k is greater than the length.
  3. Make the list circular by connecting the tail to the head.
  4. Find the new tail and break the circle to form the new list.

Code: