DEV Community

Navin S
Navin S

Posted on

πŸ” Reverse an Array

Reversing an array is one of the most fundamental problems in programming.
It’s simple to understand but extremely useful in real-world applications and coding interviews.


πŸ“Œ What Does "Reverse an Array" Mean?

Reversing an array means rearranging its elements so that:

  • The first element becomes the last
  • The second element becomes the second-last
  • And so on...

πŸ” Examples

Example 1:

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

Example 2:

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

🧠 Concept Behind Reversing

We use the two-pointer technique:

  • One pointer starts at the beginning
  • One pointer starts at the end
  • Swap elements and move inward

πŸ”„ Approach 1: Two-Pointer Method (Most Efficient)

Step-by-Step:

  1. Set start = 0
  2. Set end = n - 1
  3. Swap elements at start and end
  4. Move:
  • start = start + 1
  • end = end - 1
    1. Repeat until start < end

πŸ’» Python Code:

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

print(reverse_array([1, 4, 3, 2, 6, 5]))
Enter fullscreen mode Exit fullscreen mode

🧾 Dry Run (Step-by-Step)

For:

arr = [1, 4, 3, 2, 6, 5]
Enter fullscreen mode Exit fullscreen mode
Step Start End Array After Swap
1 0 5 [5, 4, 3, 2, 6, 1]
2 1 4 [5, 6, 3, 2, 4, 1]
3 2 3 [5, 6, 2, 3, 4, 1]

Loop stops when start >= end


⚑ Time and Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1) (in-place)

πŸ” Approach 2: Using Loop (Extra Space)

def reverse_array(arr):
    reversed_arr = []
    for i in range(len(arr) - 1, -1, -1):
        reversed_arr.append(arr[i])
    return reversed_arr
Enter fullscreen mode Exit fullscreen mode

⚑ Approach 3: Python Shortcut

arr = [1, 4, 3, 2, 6, 5]
arr.reverse()
print(arr)
Enter fullscreen mode Exit fullscreen mode

or

print(arr[::-1])
Enter fullscreen mode Exit fullscreen mode

🧩 Where Is This Used?

  • Data processing
  • Algorithm design
  • Palindrome problems
  • Interview questions

🏁 Conclusion

Reversing an array is a basic yet powerful operation.
The two-pointer approach is the most efficient and commonly used method.

Once you understand this, you can move on to more advanced problems like:

  • Array rotation
  • String reversal
  • Palindrome checking

πŸ’¬ What’s your favorite way to reverse an array? Let me know in the comments!

Top comments (0)