Arrays and Iteration
Reverse Array In Place (Two Pointers)
Walk two indices toward each other from the ends of the array, swapping at each step. The two-pointer pattern with the smallest possible state. The loop stops when the indices meet or cross.
Algorithm
The canonical input [1, 2, 3, 4, 5, 6, 7] reverses to
[7, 6, 5, 4, 3, 2, 1] after three swaps. The middle element at index 3
is untouched because the pointers meet there.
two pointers
Indices walk toward each other and swap.
Basic Implementation
basic.dart
Replay: real traced execution (multi-file project)
void main() {
final arr = <int>[1, 2, 3, 4, 5, 6, 7];
var left = 0;
var right = arr.length - 1;
while (left < right) {
final tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left = left + 1;
right = right - 1;
}
print(arr);
}
arr ← [1, 2, 3, 4, 5, 6, 7]
1void main() {2 final arr = <int>[1, 2, 3, 4, 5, 6, 7];3 var left = 0;values this step[1, 2, 3, 4, 5, 6, 7]arrleft ← 0
2final arr = <int>[1, 2, 3, 4, 5, 6, 7];3var left = 0;4var right = arr.length - 1;values this step0left[1, 2, 3, 4, 5, 6, 7]arrright ← 6
3var left = 0;4var right = arr.length - 1;5while (left < right) {values this step6right[1, 2, 3, 4, 5, 6, 7]arr0leftarr ← [7, 2, 3, 4, 5, 6, 1]
6final tmp = arr[left];7arr[left] = arr[right];8arr[right] = tmp;values this step[1, 2, 3, 4, 5, 6, 7] → [7, 2, 3, 4, 5, 6, 1]arr0left6rightleft ← 1
8arr[right] = tmp;9left = left + 1;10right = right - 1;values this step0 → 1leftright ← 5
9 left = left + 1;10 right = right - 1;11}values this step6 → 5rightarr ← [7, 6, 3, 4, 5, 2, 1]
6final tmp = arr[left];7arr[left] = arr[right];8arr[right] = tmp;values this step[7, 2, 3, 4, 5, 6, 1] → [7, 6, 3, 4, 5, 2, 1]arr1left5rightleft ← 2
8arr[right] = tmp;9left = left + 1;10right = right - 1;values this step1 → 2leftright ← 4
9 left = left + 1;10 right = right - 1;11}values this step5 → 4rightarr ← [7, 6, 5, 4, 3, 2, 1]
6final tmp = arr[left];7arr[left] = arr[right];8arr[right] = tmp;values this step[7, 6, 3, 4, 5, 2, 1] → [7, 6, 5, 4, 3, 2, 1]arr2left4rightleft ← 3
8arr[right] = tmp;9left = left + 1;10right = right - 1;values this step2 → 3leftright ← 3
9 left = left + 1;10 right = right - 1;11}values this step4 → 3rightwhile (left < right)
4var right = arr.length - 1;5while (left < right) {6 final tmp = arr[left];values this step[7, 6, 5, 4, 3, 2, 1]arr3left3right
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Dart: use the explicit
tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp;triple. Avoidarr.reversed.toList(),List.from(arr.reversed), or assigning toarrfrom a reversed view; all hide the step-by-step pointer walk the lesson is teaching. - Replay highlights both
leftandrightper frame plus the new array contents after each swap, matching the lesson spec.