DSA-VerseLearn by watching code run
DashboardData StructuresAlgorithmsVisualizerCORECoding PlaygroundInterview QuestionsComplexity AnalyzerLearning NotesBookmarksLearning ProgressSettings
Array & Data-Structure Operations algorithms

Array & Data-Structure Operations

Reverse an Array

Reverses an array in place with two pointers: swap the outermost pair, move both pointers inward, and stop when they meet.

Worst O(n)Space O(1)
Open visualizer

1Detailed explanation

Two pointers start at both ends of the array. Swap the elements they point to, move left one step right and right one step left, and repeat until the pointers meet or cross.

Each swap fixes two positions, so ⌊n/2⌋ swaps reverse the whole array in place with O(1) extra memory.

The same two-pointer pattern solves palindrome checks, reversing a string, and many 'pair from both ends' problems.

2Pseudocode

procedure reverse(A)
  left ← 0
  right ← length(A) − 1
  while left < right
    swap A[left] and A[right]
    left ← left + 1
    right ← right − 1
  return A

3Interactive visualization

Reverse an Arrayinteractive Open full visualizer
1
2
3
4
5
6
0
1
2
3
4
5
ComparingSwapping / movingCurrentSorted / finalFound / placed

Reverses an array in place with two pointers: swap the outermost pair, move both pointers inward, and stop when they meet.

1 / 17

4Implementations

Equivalent implementations in four languages — the same code the visualizer highlights line by line. Each is a complete program.

function reverseArray(arr) {
  let left = 0;
  let right = arr.length - 1;
  while (left < right) {
    [arr[left], arr[right]] = [arr[right], arr[left]];
    left++;
    right--;
  }
  return arr;
}

const arr = [1, 2, 3, 4, 5, 6];
console.log("Reversed:", reverseArray(arr));

5Time and space complexity

Time
Best caseO(n)
Average caseO(n)
Worst caseO(n)
Space
AuxiliaryO(1)
InputO(n)
TotalO(n)

Time: Each swap fixes two positions, so exactly ⌊n/2⌋ swaps are made → O(n).

Space: Only the two indexes left and right are stored → O(1) auxiliary space (in place).

6Common interview variations

  • Reverse only a sub-range [l, r].
  • Rotate an array by k positions using three reversals.
  • Check whether a string is a palindrome.
  • Reverse words in a sentence.

On this page

  1. 01Detailed explanation
  2. 02Pseudocode
  3. 03Interactive visualization
  4. 04Implementations (JS · Python · Java · Go)
  5. 05Time and space complexity
  6. 06Common interview variations