Introduction
Arrays are one of the most basic and widely used data structures in programming.
A common operation performed on arrays is reversing the elements, which means rearranging the elements in opposite order.
This problem helps us understand indexing, swapping, and basic logic building.
Problem Statement
Given an array, reverse its elements such 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]
Example 2:
Input: [4, 5, 1, 2]
Output: [2, 1, 5, 4]
Intuition
To reverse an array, we need to swap elements from both ends:
- First element ↔ Last element
- Second element ↔ Second-last element
We continue this until we reach the middle of the array.
Approach
- Initialize two pointers:
start= 0end= n - 1 - Swap elements at start and end
- Move:
start++end-- - Repeat until start < end
Code (Python)
def reverse_array(arr):
start = 0
end = len(arr) - 1
while start < end:
# Swap elements
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
Step-by-Step Explanation
For array:
[1, 4, 3, 2, 6, 5]
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]
Now start >= end, so we stop.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1) (in-place reversal)
Conclusion
Reversing an array is a simple yet important problem that builds a strong foundation in problem-solving. It introduces concepts like two-pointer technique and in-place operations, which are widely used in coding interviews.
Top comments (0)