Algorithm LogbookAlgorithm Logbook

Array Manipulation

Array

๐Ÿ“‹ 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 O(1)O(1) space.

๐Ÿ”ง Approach

  1. Initialize two pointers: left = 0, right = len(arr) - 1.
  2. While left < right, swap arr[left] and arr[right].
  3. Move left one step right and right one step left.
  4. Stop when the pointers meet or cross โ€” the array is now reversed.

โšก Complexity Analysis

Time

O(N)O(N) where NN is the length of the array โ€” each element is visited at most once

Space

O(1)O(1) โ€” the reversal is done in-place using only two pointer variables

โš ๏ธ Common Mistakes

  • Using left <= right instead of left < 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 O(N)O(N) 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.