LeetCode Day-4

Hi there,

Welcome to Day 4 of my LeetCode journey! I'm thrilled to have you here as I embark on my coding journey. As I mentioned before, I'm dedicated to tackling one problem each day and documenting my progress in this blog.

Let's get started!

189. Rotate Array

Intuition :

  • integer array nums

  • rotate the array to the right by k

Approach :

  • Calculate the length of the array. Store it in n.

      n = len(nums)
    
  • If the length of the array is less than k, then there will be a full rotation. So, you can decrement k by n

      if n < k:
          k = k-n
    
  • If k is less than the length of the array, then, the last k elements of the array come first. This can be done by slicing. Then replace the numbers in num with the sliced array.

  • nums[n-k :] give the last k elements

  • nums[:n-k] gives the first k elements

      if (k < n) :
          temp = nums[n-k:] + nums[:n-k]
          for i in range(n):
              nums[i] = temp[i]
    
  • Else, you have to rotate the array to the right by one element, k number of times. This an be done using a while loop and a temporary array

      else :
          temp = nums.copy()
          while (k > 0):
              temp = [temp[-1]] + temp[:-1]
              k -= 1
    
          for i in range(n):
              nums[i] = temp[i]
    

    Here is the full code :

      class Solution:
          def rotate(self, nums: List[int], k: int) -> None:
              """
              Do not return anything, modify nums in-place instead.
              """
    
              n = len(nums)
    
              if n < k:
                  k = k-n
    
              if (k < n) :
                  temp = nums[n-k:] + nums[:n-k]
                  for i in range(n):
                      nums[i] = temp[i]
    
              else :
                  temp = nums.copy()
                  while (k > 0):
                      temp = [temp[-1]] + temp[:-1]
                      k -= 1
    
                  for i in range(n):
                      nums[i] = temp[i]
    

    Time Complexity : O(n)

And that concludes Day 4 of my LeetCode Journey. If you have any ideas for enhancing my progress, don't hesitate to share them. Your encouragement and involvement means a lot to me.

Happy Coding!