← Microsoft bank

Microsoft · Question 24 · Linked Lists

Rotate List

Linked ListsJavacode⏱ O(n)💾 O(1)
Product-based

Problem

Rotate the list to the right by k places.

Approach

Close the ring, walk to the new tail, then break it.

Time O(n)Space O(1)

How it works

  1. 1Measure the length and ring the tail to head.
  2. 2Walk length-k steps to the new tail and break the ring.

Sample input / output

Input:
5 2
1 2 3 4 5
Output:
[4, 5, 1, 2, 3]

Constraints

0 <= nodes <= 500; 0 <= k <= 2 * 10^9.

Solution — read it, then walk it

Time O(n)Space O(1)Loops 5Branches 2Returns 3source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static ListNoderotateRight(ListNode head,int k)if (head == null || k== 0) return headDEFINE length = 1ListNode tail = headwhile (tail.next !=null)tail = tail.nextlength++k = k % lengthif (k == 0) returnheadtail.next = headfor (int i = 0; i <length - k; i++)tail = tail.nextListNode newHead =tail.nexttail.next = nullRETURN newHeadDEFINE class ListNodeDEFINE valListNode nextListNode(int v) { val = v;}DEFINE ListNodebuildList(int[] values)ListNode dummy = newListNode(0), tail = dummyfor (int v : values) {tail.next = newListNode(v); tail …RETURN dummy.nextDEFINE StringtoList(ListNode head)StringBuilder sb = newStringBuilder("[")while (head != null) {sb.append(head.val);head = head.next; i…RETURNsb.append("]").toString()DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n = sc.nextInt();int k = sc.nextInt()DEFINE [] vals = new int[n]for (int i = 0; i <vals.length; i++)vals[i] = sc.nextInt()System.out.println(toList(rotateRight(buildList(vals),k)))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/36

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits