Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agnel/c6bb7e4d09fa6dbea3d3783da39e81be to your computer and use it in GitHub Desktop.
Save agnel/c6bb7e4d09fa6dbea3d3783da39e81be to your computer and use it in GitHub Desktop.
Leetcode 189. Rotate Array

The official Leetcode page talks about four following approaches:

  1. Approach 1: Brute Force
  2. Approach 2: Using Extra Array
  3. Approach 3: Using Cyclic Replacements
  4. Approach 4: Using Reverse

The second approach can be done like this: (but only works in irb and not on leetcode somehow)

# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
  return nums if k == 0
  
  k = k % nums.size
  
  ans = Array.new(nums.size, 0)
  (nums.size).times do |i|
    ans[(i + k) % nums.size] = nums[i]
  end
  
  ans
end

The forth approach can be done like this:

# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
  return nums if k == 0
  
  k = k % nums.size
  
  def reverse_elements(array, left_idx, right_idx)
    while left_idx < right_idx
      array[left_idx], array[right_idx] = array[right_idx], array[left_idx]
      left_idx += 1
      right_idx -= 1
    end
  end
  
  reverse_elements(nums, 0, nums.size - 1) # this line is much faster than using nums.reverse!
  reverse_elements(nums, k, nums.size - 1)
  reverse_elements(nums, 0, k - 1)
  nums
end

One of my solutions that worked for me is:

# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
  return nums if k == 0
  
  k = k % nums.size
  
  popped = nums.slice!(-k..-1)
  nums.unshift(*popped)
end

Another solution which worked in irb, but failed on leetcode:

# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
  return nums if k == 0
  
  k = k % nums.size
  
  ans = []
  ans.insert(0, *nums[-k..-1])
  ans.insert(k, *nums[0..(-k - 1)])
  
  ans
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment