Tutorialspoint
Problem
Solution
Submissions

Reverse an array.

Certification: Basic Level Accuracy: 70% Submissions: 10 Points: 10

Write a C++ program that reverses a given array in place.

Example 1
  • Input: array = [1, 2, 3, 4, 5]
  • Output: [5, 4, 3, 2, 1]
  • Explanation:
    • Step 1: Initialize two pointers, one at the beginning and one at the end of the array.
    • Step 2: Swap the elements pointed by the two pointers.
    • Step 3: Move the left pointer one step right and the right pointer one step left.
    • Step 4: Repeat until the pointers meet or cross each other.
Example 2
  • Input: array = [10, 20, 30, 40]
  • Output: [40, 30, 20, 10]
  • Explanation:
    • Step 1: Initialize two pointers, one at the beginning and one at the end of the array.
    • Step 2: Swap the elements pointed by the two pointers.
    • Step 3: Move the left pointer one step right and the right pointer one step left.
    • Step 4: Repeat until the pointers meet or cross each other.
Constraints
  • 1 ≤ len(array) ≤ 10^6
  • -10^9 ≤ array[i] ≤ 10^9
  • Time Complexity: O(n), where n is the length of the array
  • Space Complexity: O(1)
ArraysControl StructuresTutorialspointGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers, one at the start and one at the end of the array.
  • Swap the elements at the two pointers and move the pointers towards the center.
  • Stop when the pointers meet or cross each other.

Steps to solve by this approach:

 Step 1: Define a function reverseArray that takes a vector of integers by reference.
 Step 2: Initialize two pointers - one at the start and one at the end of the array.
 Step 3: While the start pointer is less than the end pointer, swap the elements they point to.
 Step 4: Increment the start pointer and decrement the end pointer after each swap.
 Step 5: In main, create a vector with values and call reverseArray.
 Step 6: Loop through the reversed array and print the elements.

Submitted Code :