Rotate a LL

Linked-List FAQs (Hard) Hard

Given the head of a singly linked list containing integers, shift the elements of the linked list to the right by k places and return the head of the modified list. Do not change the values of the nodes, only change the links between nodes.

Examples:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5, k = 2

Output: head -> 4 -> 5 -> 1 -> 2 -> 3

Explanation:

List after 1 shift to right: head -> 5 -> 1 -> 2 -> 3 -> 4.

List after 2 shift to right: head -> 4 -> 5 -> 1 -> 2 -> 3.

Input: head -> 1 -> 2 -> 3 -> 4 -> 5, k = 4

Output: head -> 2 -> 3 -> 4 -> 5 -> 1

Explanation:

List after 1 shift to right: head -> 5 -> 1 -> 2 -> 3 -> 4.

List after 2 shift to right: head -> 4 -> 5 -> 1 -> 2 -> 3.

List after 3 shift to right: head -> 3 -> 4 -> 5 -> 1 -> 2.

List after 4 shift to right: head -> 2 -> 3 -> 4 -> 5 -> 1.

Input: head -> 1 -> 2 -> 3 -> 4 -> 5, k = 7

Constraints

  • 0 <= number of nodes in the linked list <= 105
  • -104 <= ListNode.val <= 104
  • 0 <= k <= 5 * 105
  • k may have values greater than number of nodes in the linked list.

Hints

  • A brute-force approach would: Perform k shifts one by one, moving the last node to the front (O(k * n) time). Use extra space (O(n)) by converting the list to an array, shifting elements, and reconstructing the list.
  • Find the Length of the List (O(n)) Determine n (number of nodes) to optimize shifts (k = k % n). Locate the New Tail (O(n)) The new tail is at (n - k)th node. The new head is at (n - k + 1)th node. Modify Links (O(1)) Set new_tail.next = NULL to break the list. Connect the old tail to the old head.

Company Tags

Shopify HCL Technologies American Express Medtronic Pinterest Databricks Activision Blizzard Micron Technology Qualcomm HashiCorp DoorDash Johnson & Johnson Docker Salesforce GE Healthcare Bloomberg MongoDB Target Roche Square McKinsey & Company JPMorgan Chase Mastercard Cloudflare Boston Consulting Group Google Microsoft Amazon Meta Apple Netflix Adobe