Start learning free

LESSON 152 OF 410 · LOOPING OVER LIST INDICES

Reverse Array in Python (Time Complexity: O(n))

Practice Read the full explanation

Given a list of integers nums, return a list containing the integers in reverse order, without using built-in functions.

Example:

Input: nums = [2, 9, 1, 5, 8]
Output: [8, 5, 1, 9, 2]

Note:

Do not use builtin functions such as reverse(), it would defy the purpose of the challenge. Write the whole code yourself.

STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · LOOPING OVER LIST INDICES

    Reverse Array in Python, explained

    Understanding the Problem

    The core challenge of this problem is to reverse the elements of an array without using any built-in functions like reverse(). This is a common problem that helps in understanding array manipulation and indexing.

    Reversing an array is a fundamental operation with applications in various algorithms and data processing tasks. It is essential to understand how to manipulate arrays manually, as it builds a strong foundation for more complex operations.

    Potential pitfalls include misunderstanding the indexing or trying to use built-in functions, which are not allowed in this problem.

    Approach

    To solve this problem, we can use a two-pointer technique. This approach involves swapping elements from the beginning and end of the array until we reach the middle. This method is efficient and has a time complexity of O(n), where n is the number of elements in the array.

    Naive Solution

    A naive solution might involve creating a new array and copying elements from the original array in reverse order. However, this approach uses extra space and is not optimal.

    Optimized Solution

    The optimized solution uses the two-pointer technique:

    • Initialize two pointers: one at the start (left) and one at the end (right) of the array.
    • Swap the elements at these pointers.
    • Move the left pointer one step to the right and the right pointer one step to the left.
    • Repeat the process until the pointers meet or cross each other.

    Algorithm

    Here is a step-by-step breakdown of the algorithm:

    1. Initialize two pointers: left at 0 and right at the last index of the array.
    2. While left is less than right:
      • Swap the elements at nums[left] and nums[right].
      • Increment left by 1.
      • Decrement right by 1.
    3. Return the modified array.

    Code Implementation

    def reverse_array(nums):
        # Initialize two pointers
        left = 0
        right = len(nums) - 1
        
        # Loop until the two pointers meet
        while left < right:
            # Swap the elements at the left and right pointers
            nums[left], nums[right] = nums[right], nums[left]
            
            # Move the pointers towards the center
            left += 1
            right -= 1
        
        return nums
    
    # Example usage
    nums = [2, 9, 1, 5, 8]
    print(reverse_array(nums))  # Output: [8, 5, 1, 9, 2]
    

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the number of elements in the array. This is because we are iterating through the array once, swapping elements. The space complexity is O(1) since we are not using any extra space proportional to the input size.

    Edge Cases

    Consider the following edge cases:

    • An empty array: The function should return an empty array.
    • An array with one element: The function should return the same array.
    • An array with two elements: The function should swap the two elements.

    Examples:

    reverse_array([])  # Output: []
    reverse_array([1])  # Output: [1]
    reverse_array([1, 2])  # Output: [2, 1]
    

    Testing

    To test the solution comprehensively, consider a variety of test cases:

    • Simple cases with a few elements.
    • Edge cases as mentioned above.
    • Larger arrays to ensure performance.

    Example test cases:

    assert reverse_array([2, 9, 1, 5, 8]) == [8, 5, 1, 9, 2]
    assert reverse_array([]) == []
    assert reverse_array([1]) == [1]
    assert reverse_array([1, 2]) == [2, 1]
    assert reverse_array([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
    

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Understand the problem requirements and constraints thoroughly.
    • Think about different approaches and their trade-offs.
    • Start with a simple solution and then optimize it.
    • Practice similar problems to improve your problem-solving skills.

    Conclusion

    Reversing an array is a fundamental problem that helps in understanding array manipulation and indexing. By using the two-pointer technique, we can achieve an efficient solution with a time complexity of O(n) and space complexity of O(1). Practicing such problems enhances problem-solving skills and prepares you for more complex challenges.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free