Bird
Raised Fist0
DSA Pythonprogramming

Array Reversal Techniques in DSA Python

Choose your learning style10 modes available
Mental Model
Reversing an array means flipping its order so the last element becomes first and the first becomes last.
Analogy: Imagine a row of people standing in line. Reversing the array is like asking them to turn around and stand in the opposite order.
Index: 0   1   2   3   4
Array: [1] -> [2] -> [3] -> [4] -> [5]
Dry Run Walkthrough
Input: array: [1, 2, 3, 4, 5]
Goal: Reverse the array so it becomes [5, 4, 3, 2, 1]
Step 1: Swap first element (1) with last element (5)
[5] -> [2] -> [3] -> [4] -> [1]
Why: Swap ends to start reversing the order
Step 2: Swap second element (2) with second last element (4)
[5] -> [4] -> [3] -> [2] -> [1]
Why: Continue swapping pairs moving inward
Step 3: Middle element (3) stays the same because it's in the center
[5] -> [4] -> [3] -> [2] -> [1]
Why: No need to swap middle element in odd-length array
Result:
[5] -> [4] -> [3] -> [2] -> [1]
Annotated Code
DSA Python
class ArrayReversal:
    def __init__(self, arr):
        self.arr = arr

    def reverse(self):
        left = 0
        right = len(self.arr) - 1
        while left < right:
            # Swap elements at left and right
            self.arr[left], self.arr[right] = self.arr[right], self.arr[left]
            left += 1  # Move left pointer inward
            right -= 1  # Move right pointer inward

    def __str__(self):
        return ' -> '.join(str(x) for x in self.arr) + ' -> null'

# Driver code
array = [1, 2, 3, 4, 5]
reversal = ArrayReversal(array)
print("Before reversal:")
print(reversal)
reversal.reverse()
print("After reversal:")
print(reversal)
while left < right:
loop until pointers meet or cross to cover all pairs
self.arr[left], self.arr[right] = self.arr[right], self.arr[left]
swap elements at left and right to reverse order
left += 1 # Move left pointer inward
advance left pointer to next element
right -= 1 # Move right pointer inward
move right pointer inward to next element
OutputSuccess
Before reversal: 1 -> 2 -> 3 -> 4 -> 5 -> null After reversal: 5 -> 4 -> 3 -> 2 -> 1 -> null
Complexity Analysis
Time: O(n) because we swap pairs moving inward, touching each element once
Space: O(1) because reversal is done in place without extra storage
vs Alternative: Naive approach creates a new reversed array using extra space O(n), this method reverses in place saving memory
Edge Cases
Empty array []
No swaps happen, array remains empty
DSA Python
while left < right:
Single element array [7]
No swaps happen, single element stays the same
DSA Python
while left < right:
Array with duplicates [2, 2, 3, 3]
Duplicates are swapped normally, order reversed correctly
DSA Python
self.arr[left], self.arr[right] = self.arr[right], self.arr[left]
When to Use This Pattern
When you need to reverse the order of elements in a list or array efficiently, use the two-pointer swap technique to reverse in place.
Common Mistakes
Mistake: Swapping elements without moving pointers inward causes infinite loop
Fix: Always increment left and decrement right pointers after swapping
Mistake: Using extra space unnecessarily by creating a new array
Fix: Perform swaps in place to save memory
Summary
Reverses an array by swapping elements from ends moving inward.
Use when you want to reverse the order of elements efficiently without extra space.
The key is swapping pairs from the outside towards the center until pointers meet.

Practice

(1/5)
1. What does reversing an array mean in simple terms?
easy
A. Sorting the array in ascending order
B. Changing the order of elements so the last becomes first and first becomes last
C. Removing duplicate elements from the array
D. Adding new elements to the end of the array

Solution

  1. Step 1: Understand the meaning of reversal

    Reversing means flipping the order of elements so the last element comes first and the first element comes last.
  2. Step 2: Compare with other options

    Sorting arranges elements by value, removing duplicates deletes repeats, and adding elements is insertion, not reversal.
  3. Final Answer:

    Changing the order of elements so the last becomes first and first becomes last -> Option B
  4. Quick Check:

    Reversal = Flip order [OK]
Hint: Reversal flips order, not sorts or removes [OK]
Common Mistakes:
  • Confusing reversal with sorting
  • Thinking reversal removes duplicates
  • Mixing reversal with adding elements
2. Which of the following is the correct Python syntax to reverse a list named arr in-place?
easy
A. arr = arr.reverse()
B. reverse(arr)
C. arr.reverse()
D. arr[::-1]

Solution

  1. Step 1: Identify the in-place reversal method

    In Python, arr.reverse() reverses the list in-place and returns None.
  2. Step 2: Check other options

    reverse(arr) is not a valid function, arr = arr.reverse() assigns None to arr, and arr[::-1] creates a reversed copy but does not change arr in-place.
  3. Final Answer:

    arr.reverse() -> Option C
  4. Quick Check:

    In-place reverse uses arr.reverse() [OK]
Hint: Use arr.reverse() for in-place reversal [OK]
Common Mistakes:
  • Assigning arr = arr.reverse() which sets arr to None
  • Using slicing without assignment for in-place change
  • Calling a non-existent reverse() function
3. What is the output of the following code?
arr = [1, 2, 3, 4, 5]
reversed_arr = arr[::-1]
print(reversed_arr)
print(arr)
medium
A. [5, 4, 3, 2, 1] and [1, 2, 3, 4, 5]
B. [5, 4, 3, 2, 1] and [5, 4, 3, 2, 1]
C. [1, 2, 3, 4, 5] and [1, 2, 3, 4, 5]
D. Error because slicing cannot reverse

Solution

  1. Step 1: Understand slicing with negative step

    The slice arr[::-1] creates a new list with elements in reverse order.
  2. Step 2: Check original list after slicing

    The original list arr remains unchanged because slicing returns a new list.
  3. Final Answer:

    [5, 4, 3, 2, 1] and [1, 2, 3, 4, 5] -> Option A
  4. Quick Check:

    Slicing reverses copy, original unchanged [OK]
Hint: Slicing with [::-1] reverses copy, not original [OK]
Common Mistakes:
  • Thinking slicing changes original list
  • Expecting error from slicing
  • Confusing reversed copy with in-place change
4. Find the error in this code that tries to reverse a list arr in-place:
def reverse_list(arr):
    for i in range(len(arr)):
        arr[i], arr[len(arr)-i] = arr[len(arr)-i], arr[i]

arr = [1, 2, 3, 4]
reverse_list(arr)
print(arr)
medium
A. Syntax error in the for loop
B. No error, code works correctly
C. arr is not modified because function returns nothing
D. Index out of range error due to incorrect index calculation

Solution

  1. Step 1: Analyze index usage in swapping

    The code uses arr[len(arr)-i] which causes index out of range because list indices go from 0 to len(arr)-1.
  2. Step 2: Identify correct index for swapping

    The correct index should be len(arr)-1 - i to avoid going beyond the last index.
  3. Final Answer:

    Index out of range error due to incorrect index calculation -> Option D
  4. Quick Check:

    Index error from len(arr)-i used as index [OK]
Hint: Use len(arr)-1 - i for last index, not len(arr)-i [OK]
Common Mistakes:
  • Using len(arr)-i instead of len(arr)-1 - i
  • Not realizing list indices start at 0
  • Assuming function returns reversed list
5. You have a list of numbers arr = [10, 20, 30, 40, 50]. Write a function that reverses the list without using built-in reverse methods or slicing. Which approach below correctly reverses the list in-place?
hard
A. Swap elements from start and end moving towards center using a while loop
B. Create a new list and append elements from the original list in reverse order
C. Sort the list in descending order
D. Use a for loop to assign arr[i] = arr[len(arr)-1-i] without swapping

Solution

  1. Step 1: Understand in-place reversal without built-ins

    Swapping elements from start and end moving towards the center changes the list in-place without extra space.
  2. Step 2: Evaluate other options

    Creating a new list is not in-place, sorting changes order by value, and assigning without swapping overwrites data incorrectly.
  3. Final Answer:

    Swap elements from start and end moving towards center using a while loop -> Option A
  4. Quick Check:

    In-place reversal = swap ends towards center [OK]
Hint: Swap pairs from ends moving inward for in-place reverse [OK]
Common Mistakes:
  • Using sorting instead of reversal
  • Overwriting elements without swapping
  • Creating new list instead of in-place change
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard