← Uber bank

Uber · Question 23 · Linked Lists

Rotate list

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

Problem

Rotate the list to the right by k places.

Approach

Make the list circular, then break at the right place.

Time O(n)Space O(1)

How it works

  1. 1Measure the length and close the list into a ring.
  2. 2Normalize k and walk length-k steps to the new tail.
  3. 3Break the ring after the new tail and return the new head.

Sample input / output

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

Constraints

0 <= nodes <= 500; -100 <= Node.val <= 100; 0 <= k <= 2 * 10^9.

Solution — read it, then walk it

Time O(n)Space O(1)Loops 4Branches 3Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatyesno↻ repeat↻ repeat↻ repeatyesnoSTARThead, kif not head or k == 0RETURN headlength = 1tail = headwhile tail.nexttail = tail.nextlength += 1k = k % lengthif k == 0RETURN headtail.next = headsteps_to_new_tail = length- knew_tail = headfor _ inrange(steps_to_new_tail- 1)new_tail = new_tail.nextnew_head = new_tail.nextnew_tail.next = NoneRETURN new_headCLASS ListNodeDEFINE __init__(self,val=0, next=None)self.val = valself.next = nextDEFINE build_list(values)dummy = tail = ListNode()for v in valuestail.next = ListNode(v)tail = tail.nextRETURN dummy.nextDEFINE to_list(head)out = []while headout.append(head.val)head = head.nextRETURN outDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); k =int(next(it))values = [int(next(it)) for_ in range(n)]print(to_list(rotateRight(build_list(values),k)))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/45

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