Algorithmsstring reverse logic
String Reverse Logic (slice, two pointers)
TT
Testlaa Team
May 14, 2026•1 min read
Reversing can mean slice s[::-1], iterator reversed(s), or in-place reversal of a list of chars. For algorithms, often reverse a substring window with two pointers without allocating a new whole string.
Why this shows up in the real world
Undo stacks replay operations by reversing command lists. Mirrored UI strings flip layout in RTL locales at render time.
Core idea (explained for students)
Reverse indices for i in range(len(s)-1, -1, -1). Reverse slice in place inside array: swap s[l] with s[r] while l < r on a list buffer.
Try this in Python
def reverse_words(s: str) -> str:
return " ".join(s.split()[::-1])
print(reverse_words(" hello world "))
Common mistakes
- Reversing bytes vs Unicode code points—emoji can surprise if you reverse UTF-16 surrogate pairs in other languages; Python
strreversal is code-point safe. - Off-by-one slice
s[i:j]half-open range.
Key takeaways
- Pick slice reversal for readability when you need a new string.
- Two-pointer reversal is the standard interview pattern for char arrays.
Tags:
StringsPythonStudents
