DayTourGuides logo
      HomeToursDestinationsBlogAbout Us
      Adventure & Extreme

      Right Rotate an Array by K places | Explained with Examples

      Admin
      October 11, 2025
      Right Rotate an Array by K places | Explained with Examples

      In this article we’ll guide you through the Python program to Right Rotate an Array by K places (in-place) [Problem Link]. We will see brute force, better and optimal solution to Right Rotate an Array by K places and dry run with images to understand the solution properly. So let’s begin. Visit DayTourGuide

      Content: [hide] Understand the problem What Does Rotation Mean? Examples to Understand Rotation Example 1 Example 2 Example 3 (Large k value)

      1. Brute Force Solution (Using Pop and Insert) Intuition and Approach Code Code Explanation (Stey by Step) Dry Run (with images) Edge cases to consider Time and Space Complexity
      2. Better Solution (Using Slicing) Intuition and Approach Code Code Explanation (Step by Step) Dry Run Edge cases to consider Time and Space Complexity
      3. Optimal Solution (Using While Loop and Reversing Array) Intuition and Approach Code Code Explanation (Step by Step) Dry Run (with images) Edge cases to consider Time and Space Complexity Understand the problem The problem is asking us to rotate an array to the right by k positions. This means that each element in the array will shift to the right, and the last k elements will move behind the beginning element.

      What Does Rotation Mean? If k = 1, the last element moves to the first position. If k = 2, the last two elements move to the front, shifting everything else. If k is greater than the array length, we rotate it as if k % n times (where n is the length of the array). Examples to Understand Rotation Example 1 Input:

      nums = [1, 2, 3, 4, 5, 6, 7] k = 3 Step-by-Step Rotation:

      Move last 3 elements [5,6,7] to the front. Shift the remaining [1,2,3,4] to the right. Output:

      nums = [5, 6, 7, 1, 2, 3, 4] Example 2 Input:

      nums = [-1, -100, 3, 99] k = 2 Step-by-Step Rotation:

      Move last 2 elements [3, 99] to the front. Shift the remaining [-1, -100] to the right. Output:

      nums = [3, 99, -1, -100] Example 3 (Large k value) Input:

      nums = [10, 20, 30, 40, 50, 60, 70, 80] k = 10 Since k > n (array length is 8), we take k % n = 10 % 8 = 2. So, we rotate by 2 places instead of 10.

      Output:

      nums = [70, 80, 10, 20, 30, 40, 50, 60] Constraints: 1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1 0 <= k <= 105 Also read about the Python Program to Move Zeros to End of the Array.

      1. Brute Force Solution (Using Pop and Insert) This solution will contain pop method which removes the last element from the array and then use insert method to put the element at first. Doing so, we rotated our array by 1 time. Let’s see multiple rotations can lead to our answer.

      Intuition and Approach Given that rotating an array of length n by n times (or a multiple of n) results in the array looking the same as the original, the actual number of effective rotations needed is k % len(nums). This approach ensures the minimal number of steps required to achieve our result, optimizing performance when k is larger than len(nums).

      The logic we will apply is pretty simple:

      Determine the number of necessary rotations using k % len(nums). For each rotation, remove the last element of the array (nums.pop()) and insert it at the beginning (nums.insert(0, last)). This simulates a single right rotation. Code class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ # Becuase if k = 8 and length = 7, means # we should only rotate 1 time instead of 8 times rotations = k % len(nums)

          for _ in range(rotations):
              last = nums.pop()
              nums.insert(0, last)
      

      Code Explanation (Stey by Step) Calculating Actual Rotations Needed: The rotations variable is assigned the value of k % len(nums) to ensure only the necessary number of rotations are performed. Rotation Loop: The loop runs rotations times. Each iteration performs one right rotation. last = nums.pop(): Removes the last element of the array and stores it in last. nums.insert(0, last): Inserts the last element at the start of the array, thus rotating the array right by one position. Dry Run (with images) Let’s go through the code step by step, using images to illustrate the detailed dry run process.

      Dry of Right rotate an array by K places using a brute force solution Edge cases to consider k Equal to Zero: If k is 0, the array should remain unchanged. Our code handles this naturally since rotations would be 0, and no loop iterations would occur. k Greater than Array Length: As shown in the example, our code recalculates k to ensure only necessary rotations are done. Empty Array: If nums is empty, our code should handle it properly, performing no actions. Array of Length One: An array with one element remains unchanged regardless of k, which our code will handle correctly since popping and inserting the same element does not alter the array. Time and Space Complexity Time Complexity: The complexity is O(k×n), where k is the number of rotations (after modulo operation) and n is the number of elements in the array. Each rotation involves a pop operation (O(1)) and an insert operation at the beginning of the array (O(n)), making it inefficient for large arrays or high values of k. Space Complexity: The space complexity is O(1) since no additional space is used and it does not depend on the size of the array. Join our FREE dsa course 2. Better Solution (Using Slicing) This solution will contain slice method which is available in python to achieve our rotation and get our answer. You need to have a basic understanding of how slicing works in Python to understand the solution.

      Intuition and Approach The approach used here takes advantage of slicing in Python to rearrange segments of the array rather than manually moving elements. The core idea involves:

      Modifying k to be within the range of the array’s length using the modulus operation (k %= n). This handles cases where k is greater than the length of the array, reducing unnecessary full rotations. Slicing the array into two segments: The last k elements: nums[n-k:] The first n-k elements: nums[:n-k] Concatenating these two list/array in reverse order to achieve the desired right rotation. Code class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) k %= n

          # Rotate the list in-place
          nums[:] = nums[n - k :] + nums[: n - k]
      

      Code Explanation (Step by Step) Initialization: n is set to the length of the array nums. k is recalculated as k % n to ensure there isn’t any unnecessary rotations. Rotation via Slicing: The array nums is updated by slicing and concatenating: nums[n-k:] captures the last k elements which will move to the front of the array. nums[:n-k] captures the remaining elements which will shift rightwards. These slices are concatenated to form the new order of elements in nums. Dry Run Let’s use the input nums = [1, 2, 3, 4, 5] and k = 3 as an example:

      Initial State: nums = [1, 2, 3, 4, 5], n = 5, k = 3 Calculate Effective Rotations: k = 3 % 5 = 3 Rotate Operation: The last k elements are nums[5-3:5] = nums[2:5] = [3, 4, 5]. The first n-k elements are nums[0:5-3] = nums[0:2] = [1, 2]. Concatenation results in nums[:] = [3, 4, 5] + [1, 2] = [3, 4, 5, 1, 2]. Final State: nums = [3, 4, 5, 1, 2] Edge cases to consider k Equal to Zero: If k is 0, the array remains unchanged. The method adjusts for this since nums[n-k:] and nums[:n-k] simply makes the original array. k Greater than Array Length: The method correctly recalculates k to fit within the array bounds, preventing unnecessary rotations. Empty Array: If nums is empty, our code handles this by not performing any actions since slicing an empty array remains empty. Array of Length One: An array with one element remains unchanged regardless of k, which our code handles correctly as slicing and concatenating a single element array does not change it. Time and Space Complexity Time Complexity: The complexity is O(n) due to the slicing operations, where each slice operation handles all elements. Space Complexity: The complexity is O(n) as the slicing operation creates new slices which are then used to overwrite the original array in-place. Efficiency: This method is more efficient than manually rotating each element or using additional arrays. It takes advantage of Python’s powerful slicing capabilities to perform the rotation cleanly and efficiently. However, space usage could be a concern due to the temporary slices, although the operation itself is performed in-place.

      Join our advance python with dsa course 3. Optimal Solution (Using While Loop and Reversing Array) Before jumping on to this solution, please refer How to Reverse an Array using Loops.

      Intuition and Approach The approach we will apply uses reversals of array or a part of array to achieve the rotation without extra space for another array. The process is as follows:

      Normalize k to be less than the length of the array using k %= n. This handles cases where k is larger than the array size, reducing rotations. Reverse the last k elements of the array. This positions these elements as they should appear after a complete rotation. Reverse the first n-k elements. This prepares the front part of the array for a reversal. Reverse the entire array to finalize the positions of the elements for the right rotation. Code class Solution: def reverse(self, nums: List[int], l: int, r: int) -> None: """ Reverse the portion of nums starting at index l up to index r in-place. """ while l < r: nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1

      def rotate(self, nums: List[int], k: int) -> None:
          """
          Do not return anything, modify nums in-place instead.
          """
          n = len(nums)
          k %= n  # Handle cases where k might be larger than n
      
          # 1. Reverse the last k elements
          self.reverse(nums, n - k, n - 1)
      
          # 2. Reverse the first n-k elements
          self.reverse(nums, 0, n - k - 1)
      
          # 3. Reverse the entire array
          self.reverse(nums, 0, n - 1)
      

      Code Explanation (Step by Step) Helper Function – Reverse: A helper function reverse(l, r) is defined to reverse the elements of nums between indices l and r, inclusive. This function swaps elements from the outermost until it reaches the middle of the specified segment. Initialization and Normalization: n is set to the length of nums. k is recalculated as k % n to ensure rotations are within bounds. Rotation Steps: reverse(n – k, n – 1): Reverse the segment of the array that contains the last k elements. reverse(0, n – k – 1): Reverse the segment of the array before the last k elements. reverse(0, n – 1): Finally, reverse the entire array to align all elements correctly after the rotation. Dry Run (with images) Let’s go through the code step by step, using images to illustrate the detailed dry run process.

      A dry run of right rotate an array by K places optimally by reversing arrays Edge cases to consider k Equal to Zero: If k is 0, the array remains unchanged. Our code handles this as the reversals will effectively leave the array as is. k Greater than Array Length: Our code correctly recalculates k to fit within the array bounds, ensuring efficient rotations. Empty Array: If nums is empty, our code avoids any operations, preserving the empty state. Array of Length One: An array with one element remains unchanged regardless of k, which our code correctly handles since the operations do not change a single-element array. Time and Space Complexity Time Complexity: The complexity is O(n) because each element is touched a constant number of times across the three reversal operations. Space Complexity: The complexity is O(1) as the solution modifies the array in place and does not use additional space proportional to the input size. Efficiency: This method is efficient in terms of both time and space. By using reversals, it avoids the need for extra storage and minimizes the number of operations, making it suitable for large datasets. The reversals ensure that each element is moved directly to its final position, optimizing the process compared to other methods that might involve multiple shifts or rotations.

      Join our advance python with dsa course For any changes to the document, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

      Array Easy Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Previous Article Remove duplicates from Sorted array – Leetcode 26 Next Article Python Program to Reverse Array Using Recursion and While Loop

      codeanddebug Website Related Posts Data Structures & Algorithms Symmetric Tree | Leetcode 101 | Recursive DFS Approach 2 September 2025 Data Structures & Algorithms Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches 2 September 2025 Data Structures & Algorithms Bottom View of Binary Tree | BFS with Horizontal Distance Mapping 2 September 2025 Add A Comment Categories Data Structures & Algorithms(240) Beginner(82) Expert(52) Intermediate(106) Uncategorised(1) Recent Posts Symmetric Tree | Leetcode 101 | Recursive DFS Approach 2 September 2025 Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches 2 September 2025 Bottom View of Binary Tree | BFS with Horizontal Distance Mapping 2 September 2025 Top View of Binary Tree | BFS with Horizontal Distance Mapping 2 September 2025 Vertical Order Traversal of a Binary Tree | Leetcode 987 | BFS + Sorting Solution 2 September 2025 Data Structures & Algorithms Remove duplicates from Sorted array – Leetcode 26 codeanddebugBy codeanddebug8 May 2025Updated:8 May 2025No Comments6 Mins Read Share

      Share Hi everyone, in this article we’ll guide you through the Python program to Remove Duplicates from Soroted Array (in-place) [Problem Link]. We will see both the brute-force and optimal solution and dry run. So let’s begin.

      [hide] Understand the problem Simple Question Explanation: Example: Input: Output: Key Constraints:

      1. Brute Force Solution (With Dictionary) Intuition and Approach Code Code Explanation Dry Run (with images) Edge cases to consider Time and Space Complexity
      2. Optimal Solution (With Two Pointers) Intuition and Approach Code Code Explanation Dry Run (with images) Edge cases to consider Time and Space Complexity Understand the problem This problem “Remove Duplicates from Sorted Array” is about modifying a sorted array in place to remove duplicate values while keeping the original order. The goal is to return the number of unique elements.

      Simple Question Explanation: You are given a sorted array (non-decreasing order). You need to remove duplicate values so that each unique number appears only once. The remaining unique elements should be placed at the beginning of the array. You cannot use extra space (i.e., no new array), so the changes must be done in place. The function should return the count of unique numbers. Example: Input: nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] Output: nums = [0, 1, 2, 3, 4, _, _, _, _, _] Explanation: The first 5 elements are the unique values, and the remaining elements are ignored.

      Return value: 5 (since there are 5 unique numbers).

      Key Constraints: The array is already sorted. You must modify the array in place (without using extra space). The function should return the count of unique elements. Also read about the Python Program to Rotate an Array by K Places.

      1. Brute Force Solution (With Dictionary) This approach will use dictionary to store unique elements and then use it to put it back into the original array. This might not be the most optimal solution, but we can still get to our answer.

      Intuition and Approach The solution uses a dictionary (my_dict) to track the unique elements of the array. Since dictionary keys in Python are unique, inserting each element of the array as a key in the dictionary automatically removes any duplicates. The approach is straightforward:

      Populate the dictionary with the elements of the array. Iterate through the dictionary keys, which are guaranteed to be unique, and copy them back into the original array nums. The new length of the array without duplicates is then the count of these unique keys. Code class Solution: def removeDuplicates(self, nums: List[int]) -> int: my_dict = dict() for i in nums: my_dict[i] = 0

          j = 0
          for n in my_dict:
              nums[j] = n
              j += 1
          return j
      

      Code Explanation Initialization: A dictionary my_dict is initialized to store each unique element of nums. First Loop – Removing Duplicates: Iterates over each element i in nums. Adds i to my_dict as a key. If i is already a key in the dictionary, it does nothing (ignoring duplicates). Second Loop – Reassigning to nums: j is initialized to 0 to act as the index for the next unique element in nums. Iterates through the keys in my_dict (which are the unique elements). Each key n is placed back into nums[j], and j is incremented. Return Statement: Returns j, the number of unique elements placed back into nums. Dry Run (with images) Let’s walk through a step-by-step dry run with a sample input:

      1st image of Dry run of brute force solution to remove duplicates from the array 2nd image of Dry run of brute force solution to remove duplicates from the array Edge cases to consider Empty Array: If nums is empty (nums = []), our code correctly returns 0 and makes no changes. Array with No Duplicates: If the array already contains no duplicates (e.g., nums = [1, 2, 3]), our function will return the original length of the array. All Elements Identical: For an array where all elements are identical (e.g., nums = [1, 1, 1]), our function will return 1, with the first element being the unique one. Time and Space Complexity Time Complexity: The time complexity is O(n + n), where n is the length of the array. This is because of one pass to fill the dictionary and another to update the array. Space Complexity: The space complexity is O(k), where k is the number of unique elements in nums. In the worst case (all elements are unique), this is O(n). Join our advance python with dsa course 2. Optimal Solution (With Two Pointers) To solve this problem we will be using two pointers as i and j. Check out the solution below to understand what are we trying to do and understand through the images via dry run.

      Intuition and Approach Given that the array is sorted, our solution utilizes the two-pointer technique to effectively filter out duplicates in-place. The main idea is to maintain two pointers:

      i points to the last position of the unique elements encountered so far. j will loop through the array giving us non duplicates. If nums[j] is not equal to nums[i], it means nums[j] is a unique element that hasn’t been recorded yet. Therefore, nums[j] is swapped with nums[i+1], effectively growing the list of unique elements by one. The process ensures that all unique elements are shifted to the front of the array in their original order.

      Code class Solution: def removeDuplicates(self, nums: List[int]) -> int: if len(nums) == 1: return 1 i = 0 j = i + 1 while j < len(nums): if nums[j] != nums[i]: i += 1 nums[j], nums[i] = nums[i], nums[j] j += 1 return i + 1 Code Explanation Initial Checks: If the array has only one element, it immediately returns 1 since a single element is inherently unique. Initialization: Two pointers, i and j, are initialized where i starts at 0 and j starts at i + 1. While Loop: The loop continues as long as j is less than the length of the array. Inside the loop: If nums[j] is different from nums[i], this indicates a new unique element. i is incremented to extend the segment of unique elements. nums[j] is then swapped with nums[i], positioning it within the unique segment. j is incremented on every iteration to continue scanning the array. Return Statement: Returns i + 1, which is the count of unique elements since i is the index of the last unique element. Dry Run (with images) Let’s walk through a step-by-step dry run with a sample input:

      Dry run of optimal solution to remove duplicates from the array using two pointers Edge cases to consider Empty Array: If nums is empty, our function will handle this and return 0. All Elements Identical: For nums = [1, 1, 1], our function should return 1, correctly identifying the single unique element. Array with No Duplicates: For an array like nums = [1, 2, 3], our function should return the length of the array, which is 3. Time and Space Complexity Time Complexity: The complexity is O(n), where n is the length of the array. Our code iterates through the list once with the j pointer.

      Space Complexity: The complexity is O(1) as the solution modifies the array in place and does not use additional space.

      Join our FREE dsa course For any changes to the document, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

      Array Easy Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Previous Article Find the Largest Element in an Array Next Article Right Rotate an Array by K places | Explained with Examples

      codeanddebug

      A

      Written by Admin

      Author

      DayTourGuides logo

      Day Tour Guides

      Your gateway to unforgettable adventures in the heart of the Caucasus.

      Follow Us

      Explore

      • All Tours
      • Destinations
      • Categories
      • Special Offers
      • Blog

      Company

      • About Us
      • Contact Us
      • FAQ

      Career

      • For Tour Providers

      Legal

      • Terms of Service
      • Privacy Policy
      • Cancellation Policy

      © 2025 DayTourGuides. All rights reserved.

      Georgia•+995 XXX XXX XXX•info@daytourguides.com