Rotate Array with Java Solution

day 10: LeetCode 189. Rotate Array Approach Use an extra result array. Copy the last k elements first (they wrap to the front), then copy the remaining elements after them. Why k = k % n? 7 rotations on size-7 array → same array 14 rotations → same array 22 rotations → 21 cancel out, only 1 real rotation So any multiple of n rotations = no change, only the remainder matters. Code Walkthrough Loop 1 — copy last k elements to front of res i starts at n-k, goes to n Loop 2 — copy remaining elements right after, ptr continues where loop 1 left off i starts at 0, goes to n-k Loop 3 — copy res back into nums (since rotate is void) Key Trick ptr++ inside the assignment — assigns first, then increments. Keeps both loops flowing into res seamlessly without overlap or gap. #day10of150daysofcode #150daysofcode #Java #leetcode #dailycode

  • text

To view or add a comment, sign in

Explore content categories