DEV Community

Manoj Kumar
Manoj Kumar

Posted on

Reverse an Array – Python Solution

🔄 Reverse an Array – Python Solution

Hi All,

Today I worked on a basic but important problem: Reversing an Array.


📌 Problem Statement

Given an array, reverse its elements such that:

  • First element becomes last
  • Second element becomes second-last
  • And so on

🔍 Example

Example 1:

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

Example 2:

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

Output:

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

💡 Approach

🔹 Method 1: Using Two Pointers (Optimal)

  • Use two pointers:
    • start → beginning of array
    • end → last index
  • Swap elements until they meet

💻 Python Code (Two Pointer Method)

def reverse_array(arr):
    start = 0
    end = len(arr) - 1

    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1

    return arr
Enter fullscreen mode Exit fullscreen mode

🔍 Dry Run

For:

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

Steps:

  • Swap 1 and 2 → [2, 4, 3, 1]
  • Swap 4 and 3 → [2, 3, 4, 1]

Final Output:

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

🖥️ Sample Output

Input: [1, 4, 3, 2, 6, 5]
Output: [5, 6, 2, 3, 4, 1]

Input: [4, 5, 1, 2]
Output: [2, 1, 5, 4]
Enter fullscreen mode Exit fullscreen mode

🧠 Alternative Methods

🔹 Method 2: Using Slicing

def reverse_array(arr):
    return arr[::-1]
Enter fullscreen mode Exit fullscreen mode

👉 Very simple but uses extra space


🔹 Method 3: Using reverse()

arr.reverse()
Enter fullscreen mode Exit fullscreen mode

👉 Modifies the original array


⚡ Complexity Analysis

Method Time Space
Two Pointer O(n) O(1) ✅
Slicing O(n) O(n) ❌

✅ Conclusion

This problem helped me understand:

  • Two pointer technique
  • In-place array manipulation
  • Different ways to reverse data

🚀 This is a fundamental concept used in many problems!


Top comments (0)