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]
Example 2:
Input: [4, 5, 1, 2]
Output: [2, 1, 5, 4]
π§ 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:
- Set
start = 0 - Set
end = n - 1 - Swap elements at
startandend - Move:
start = start + 1-
end = end - 1- Repeat until
start < end
- Repeat until
π» 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]))
π§Ύ Dry Run (Step-by-Step)
For:
arr = [1, 4, 3, 2, 6, 5]
| 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
β‘ Approach 3: Python Shortcut
arr = [1, 4, 3, 2, 6, 5]
arr.reverse()
print(arr)
or
print(arr[::-1])
π§© 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)