Array Manipulation
๐ Problem Statement
Given an array arr, reverse the order of elements in-place. You must modify the original array directly without creating a new array. Input: [10, 20, 30, 40, 50] โ Output: [50, 40, 30, 20, 10].
๐ก Intuition
Reversing an array in-place uses the Two-Pointer Technique. Place one pointer at the start (left = 0) and another at the end (right = N-1), then swap and move inward. This avoids allocating a new array, achieving space.
๐ง Approach
- Initialize two pointers:
left = 0,right = len(arr) - 1. - While
left < right, swaparr[left]andarr[right]. - Move
leftone step right andrightone step left. - Stop when the pointers meet or cross โ the array is now reversed.
โก Complexity Analysis
where is the length of the array โ each element is visited at most once
โ the reversal is done in-place using only two pointer variables
โ ๏ธ Common Mistakes
- Using
left <= rightinstead ofleft < right(when pointers meet, swapping an element with itself is harmless but unnecessary) - Creating a new array (e.g.,
arr[::-1]) instead of modifying in-place โ this uses extra space - Forgetting to move both pointers after the swap, causing an infinite loop
๐ฏ Final Thoughts
The two-pointer technique is one of the most important patterns in DSA. Mastering it here on a simple reversal problem prepares for harder problems like palindrome checking, container with most water, and two-sum on sorted arrays.