Reversal and Rotation
24 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A reversed list, a rotated rota, a sentence with its words flipped: these small tasks hide one tool, two pointers moving inward. Learn it once and use it again for palindromes and partitions.
Reverse with two pointers
Two pointers means using two indexes that move through a list, often from opposite ends. One pass solves the problem without building extra lists.
To reverse a list of tickets without a second list, swap the first and last items, then move both ends inward. Stop when the two ends meet.
items = [1, 2, 3, 4, 5, 6]left, right = 0, len(items) - 1while left < right: items[left], items[right] = items[right], items[left] left += 1 right -= 1print(items)Example 1 · Reverse only a part of a list
def reverse(items, lo, hi): while lo < hi: items[lo], items[hi] = items[hi], items[lo] lo += 1 hi -= 1
data = [1, 2, 3, 4, 5, 6, 7, 8]reverse(data, 2, 5)print(data)[1, 2, 6, 5, 4, 3, 7, 8]
What this code does
- The helper takes the first and last positions to reverse.
- Positions 2 to 5 hold 3, 4, 5, 6, which become 6, 5, 4, 3.
- This helper is the building block of rotation.
Three swaps reverse six items. For an odd length the middle item stays, because it is its own mirror.
Python's built-in ways
Python already reverses. reverse() works in place and returns None. [::-1] builds a new list, and reversed() gives an iterator. In an interview, write the pointer version unless told otherwise.
names = ["Asha", "Ravi", "Meena"]print(names[::-1])print(list(reversed(names)))names.reverse()print(names)Example 2 · Reverse the words of a sentence
message = "login failed twice"print(" ".join(message.split()[::-1]))twice failed login
What this code does
split()makes a list of words, and[::-1]reverses it.joinglues the words back with single spaces.- Extra spaces in the input disappear, because split() ignores them.
Use [::-1] or reversed() in everyday code. Use the pointer loop when the problem forbids extra space.
Rotate with slicing
Rotation means moving every item k places in one direction. Items that fall off one end re-enter at the other end.
A duty rota moves everyone k places to the right, and the last people wrap to the front. Slices cut the list at the right place. Use k % len(items) so a large k still works.
def rotate_right(items, k): k %= len(items) cut = len(items) - k return items[cut:] + items[:cut]
print(rotate_right([1, 2, 3, 4, 5], 2))Example 3 · Rotation by brute force
data = [1, 2, 3, 4, 5]for _ in range(2): data.insert(0, data.pop())print(data)[4, 5, 1, 2, 3]
What this code does
- Each pass moves the last item to the front.
insert(0, ...)shifts every item, so each step is O(n) and k steps cost O(n * k).- It works for small k but is too slow when k is large.
Example 4 · Rotate left by k with slicing
def rotate_left(items, k): k %= len(items) return items[k:] + items[:k]
print(rotate_left([10, 20, 30, 40, 50], 7))[30, 40, 50, 10, 20]
What this code does
- 7 % 5 is 2, so rotating by 7 is the same as rotating by 2.
items[k:]is the part that moves to the front,items[:k]goes behind it.- O(n) time and O(n) extra space.
It builds a new list, so it costs O(n) extra space. It is the clearest answer when extra space is allowed.
Rotate in place with three reversals
Interviews ask for rotation with no extra list. Reverse the whole list, then reverse the first k items, then reverse the rest. Each step is the two-pointer loop you already know.
Example 5 · Is one text a rotation of another
def is_rotation(a, b): return len(a) == len(b) and b in a + a
print(is_rotation("abcde", "cdeab"))print(is_rotation("abcde", "abced"))True False
What this code does
- Every rotation of a text appears inside the text written twice.
- The length check stops a short text such as "cd" matching by accident.
- One pass over the doubled text finds the match.
Example 6 · Rotate in place with three reversals
def reverse(items, lo, hi): while lo < hi: items[lo], items[hi] = items[hi], items[lo] lo += 1 hi -= 1
def rotate_right(items, k): k %= len(items) reverse(items, 0, len(items) - 1) reverse(items, 0, k - 1) reverse(items, k, len(items) - 1)
data = [1, 2, 3, 4, 5, 6, 7]rotate_right(data, 3)print(data)[5, 6, 7, 1, 2, 3, 4]
What this code does
- Three passes, each O(n), so O(n) time and O(1) extra space.
- Running it prints
[5, 6, 7, 1, 2, 3, 4].
Next step
Check your understanding
12 quick questions