DEV Community

Christina Sharon S
Christina Sharon S

Posted on • Edited on

Reversing an Array in Python - CA05

Introduction

Reversing an array is a basic and important operation in programming. It involves rearranging the elements of an array so that the first element becomes the last, the second element becomes the second last, and so on. Although this would be much easier when solved using brute force methods, when you are trying to get a job they look at your time and space complexity and that's when the two pointer approach steps in.

Problem Statement

Given an array, reverse its elements.

Example 1

Input:

arr = [1, 4, 3, 2, 6, 5]
Enter fullscreen mode Exit fullscreen mode

Output:

[5, 6, 2, 3, 4, 1]
Enter fullscreen mode Exit fullscreen mode

Concept

Reversing an array means:

  • First element - Last position
  • Second element - Second last position
  • Continue this pattern until the array is fully reversed

We use two pointers:

  • One starting from the beginning
  • One starting from the end

We swap elements until both pointers meet.

Python Implementation

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

    while left < right:
        # Swap elements
        arr[left], arr[right] = arr[right], arr[left]

        left += 1
        right -= 1

    return arr

# Example usage
arr = [1, 4, 3, 2, 6, 5]
print(reverse_array(arr))
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

For:

[1, 4, 3, 2, 6, 5]
Enter fullscreen mode Exit fullscreen mode
  • Swap 1 and 5 = [5, 4, 3, 2, 6, 1]
  • Swap 4 and 6 = [5, 6, 3, 2, 4, 1]
  • Swap 3 and 2 = [5, 6, 2, 3, 4, 1]

Array is now reversed.

Conclusion

Reversing an array is simple but fundamental. The two-pointer method is the most efficient in terms of space, while Python’s built-in methods provide quick and readable solutions.

Understanding this concept is useful for many real-world problems and coding interviews.

Top comments (0)