Close the ring, walk to the new tail, then break it.
Time O(n)Space O(1)
How it works
1Measure the length and ring the tail to head.
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.
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 →