Algorithm LogbookAlgorithm Logbook

Array Manipulation

Month 1Week 1Day 4

๐Ÿ“‹ 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 requires the Two-Pointer Technique. Place one pointer at the start and another at the end, then swap and move inward. This avoids allocating a new array, achieving O(1) space. The pattern of "shrinking the window from both ends" is reusable in many problems.

๐Ÿ”ง 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) where N is the length of the array โ€” each element is visited at most once
Space
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 the element with itself is harmless but unnecessary) - Creating a new array (e.g., arr[::-1]) instead of modifying in-place โ€” this uses 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 you for harder problems like palindrome checking, container with most water, and two-sum on sorted arrays. Always think "Can I use two pointers?" when dealing with arrays.