DEV Community

Cover image for Advanced Array Manipulation Techniques in Python
Peter Muthama
Peter Muthama

Posted on

Advanced Array Manipulation Techniques in Python

In today’s blog, we will look at more advanced methods of manipulating arrays in Python without using any inbuilt functions or shortcuts like reversed() or slicing. These problems will help you understand the logic behind common operations and improve your problem-solving skills.


Problem One: Reverse an Array In-Place

Problem

You are given an array of n integers. Your task is to reverse the array without using any additional lists or the built-in reversed() function.

Amend the array in-place, which means you are not allowed to use any additional lists in your solution.

Breakdown

We are required to reverse the array in-place. This means we’ll need to use two pointers:

  • One starting from the left, and one from the right.
  • We swap the values at those positions.
  • As long as left is less than right, we continue swapping.
  • We do this until the array is fully reversed.

Code

def solution(arr):
    left = 0
    right = len(arr) - 1

    while left < right:
        arr[left], arr[right] = arr[right], arr[left]
        left += 1
        right -= 1
    return arr
Enter fullscreen mode Exit fullscreen mode

Example

print(solution([1, 2, 3, 4, 5]))  # Output: [5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Problem Two: Rotate an Array Anti-Clockwise by k Steps

Problem

You are provided with an array of n integers and a number k. Your task is to perform an anti-clockwise rotation (towards the front) of the array by k positions. The rotation should be done in-place, which means you have to directly manipulate the input array without creating a new one.

Note: k might be bigger than the array length.

For example, if the input array is [1, 2, 3, 4, 5, 6, 7] and k = 3, then after the operation, the array should look like [4, 5, 6, 7, 1, 2, 3].

Breakdown

  • Since rotating the array by its length results in the same array, you can take k % n (modulo) to handle cases where k is greater than the array length.
  • To rotate the array anti-clockwise, we use reversal in three steps:
  1. Reverse the entire array.
  2. Reverse the first n - k elements.
  3. Reverse the last k elements.

Code

def anti_rotate_array(nums, k):
    n = len(nums)
    k = k % n
    if k == 0:
        return nums

    def reverse(left, right):
        while left < right:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1

    reverse(0, n - 1)
    reverse(0, n - k - 1)
    reverse(n - k, n - 1)
    return nums
Enter fullscreen mode Exit fullscreen mode

Example

print(anti_rotate_array([1, 2, 3, 4, 5, 6, 7], 3))  
# Output: [4, 5, 6, 7, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)