⬅ Previous Topic
Find Second Smallest in ArrayNext Topic ⮕
Check if Array is Sorted⬅ Previous Topic
Find Second Smallest in ArrayNext Topic ⮕
Check if Array is SortedTopic Contents
Given an array of elements, your task is to reverse the array in-place using the two pointers technique.
left
), and one from the end (right
).The goal is to reverse the order of elements in the array without using extra space.
left
) and one at the end (right
) of the array.left
is less than right
, swap the elements at these pointers.left
and decrement right
to move towards the center of the array.left
is no longer less than right
.def reverse_array(arr):
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5]
print("Reversed array:", reverse_array(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | Even in the best case, the algorithm must visit each element once to perform the swap. So the time complexity is linear in all cases. |
Average Case | O(n) | Each pair of elements is visited and swapped once, so the total operations grow linearly with the size of the array. |
Average Case | O(n) | All elements need to be swapped exactly once with their mirror index, requiring n/2 swaps — still considered O(n). |
O(1)
Explanation: Only a constant amount of extra space is used — two pointers and a temporary variable for swapping. The reversal is done in-place.
Let us take the following array and apply the Two Pointers Technique to reverse the array in-place.
left = 0
, right = 5
Swap elements at left index and right index.
After swapping:
left = 1
, right = 4
Swap elements at left index and right index.
After swapping:
left = 2
, right = 3
Swap elements at left index and right index.
After swapping:
left = 3
, right = 2
left pointer crosses right pointer, end of loop.
Array is fully reversed.
⬅ Previous Topic
Find Second Smallest in ArrayNext Topic ⮕
Check if Array is SortedYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.