Foundation drill for this topic
Easy Two Pointers
In plain English: You're given a list of numbers and need to flip the order without creating a new list.
Two pointers converging from opposite ends is the go-to for symmetric array operations — each swap brings both ends closer to the center.
Prompt
Given an array a, reverse it in-place.
Try to write it from scratch before scrolling down.
Solution
def reverse(a):
l, r = 0, len(a) - 1
# converge from both ends
while l < r:
a[l], a[r] = a[r], a[l]
l += 1
r -= 1
return a
# Test: reverse([1,2,3,4,5]) == [5,4,3,2,1]
Quick recall drills to reinforce this pattern.
Write-pointer compaction for sorted arrays. Returns new length.
w = 1
for i in range(1, len(a)):
if a[i] != a[i-1]:
a[w] = a[i]
w += 1
return w
Write-pointer skips unwanted values. O(1) space removal pattern.
w = 0
for r in range(len(a)):
if a[r] != val:
a[w] = a[r]
w += 1
# a[:w] has val removed
Transpose + reverse-rows rotates 90 degrees clockwise in-place. Classic matrix manipulation.
n = len(m)
for i in range(n):
for j in range(i+1, n):
m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m:
row.reverse()