Skip to main content
Back to problems
#189
Medium Algorithms

Rotate array

Array Math Two Pointers
44.5% acceptance
Jan 12, 2026
20882
2177
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn rotate(nums: &mut Vec<i32>, k: i32) {
    let n = nums.len();
    let k = (k as usize) % n;
    
    if k == 0 {
      return;
    }
    
    nums.reverse();
    nums[0..k].reverse();
    nums[k..].reverse();
  }
}