1.Reverse an Array
Problem:
Reversing an array means rearranging elements so the last element becomes first and vice versa.
Approach Used: Using Temporary Array
•Instead of modifying the array directly, we:
•Create a new array of same size
•Fill it in reverse order
Copy it back to original array
Step-by-step explanation
Step 1: Get array size
n = len(arr)
Step 2: Create temporary array
temp = [0] * n
--> This stores reversed elements
Step 3: Reverse logic
for i in range(n):
temp[i] = arr[n - i - 1]
Explanation:
n - i - 1 gives index from end
So elements are picked from back to front
Step 4: Copy back to original array
for i in range(n):
arr[i] = temp[i]
`def reverseArray(arr):
n = len(arr)
# Temporary array to store elements
# in reversed order
temp = [0] * n
# Copy elements from original array
# to temp in reverse order
for i in range(n):
temp[i] = arr[n - i - 1]
# Copy elements back to original array
for i in range(n):
arr[i] = temp[i]
if name == "main":
arr = [1, 4, 3, 2, 6, 5]
reverseArray(arr)
for i in range(len(arr)):
print(arr[i], end=" ")`
OUTPUT:
5 6 2 3 4 1
Complexity
Time Complexity: O(n)
Space Complexity: O(n) (because of temp array)
Conclusion
This approach is simple and beginner-friendly, but not memory efficient. For real-world use, in-place reversal is preferred.
Top comments (0)