DEV Community

Lokeshwaran S
Lokeshwaran S

Posted on

Array Reverse - CA05

My Thinking and Approach


Introduction

In this problem, I was given an array of integers and asked to reverse the array.

Reversing an array means rearranging the elements such that the first element becomes the last, the second element becomes second last and so on.


Problem Statement

  • Given an array of integers arr

  • Reverse the array

  • After reversing:

    • First element becomes last
    • Second element becomes second last
    • Continue this pattern

My Initial Thought

At first, I considered:

  • Creating a new array
  • Adding elements in reverse order

But this approach uses extra space.


Key Observation

Instead of using extra space:

  • I can swap elements from both ends
  • Move towards the center

Optimized Approach

I decided to:

  • Use two pointers
  • Swap elements in-place

Logic:

  • Start one pointer at beginning
  • Start another pointer at end
  • Swap elements
  • Move both pointers towards center

My Approach (Step-by-Step)

  1. Initialize two pointers:
  • left = 0
  • right = length - 1

    1. While left < right:
  • Swap arr[left] and arr[right]

  • Move left forward

  • Move right backward


Code (Python)

Below is the implementation clearly separated inside a code block:

def reverseArray(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 Walkthrough

Input:

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

Steps:

  • 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]

Output:

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

Complexity Analysis

Type Complexity
Time Complexity O(n)
Space Complexity O(1)

Key Takeaways

  • Two pointer technique is useful
  • No extra space is required
  • In-place operations improve efficiency

Conclusion

This problem helped me understand how to reverse an array efficiently using in-place swapping.

Instead of creating a new array, I used pointer manipulation to achieve optimal performance.


Top comments (0)