Reverse a sequence of Unicode code points
BeginnerFreshers · 0 yearsStrings
Python 3.10+; standard library only. GIL discussion refers to conventional CPython builds, not optional free-threaded builds.
Problem statement
Return the code points of a string in reverse order.
A text exercise reverses code points; user-perceived grapheme clusters are intentionally outside scope.
Input: A Python str.
Output: A new Python str.
- 0 <= length <= 100000.
- No grapheme-cluster normalization requirement.
Sample 1
Input: campus Output: supmac
Read characters from the end.
Sample 2
Input: Output: empty string
Empty input remains empty.
Brute-force solution
Repeatedly prepend each character, potentially copying the growing output each time.
O(n²) worst-case repeated copying.
def reverse_slow(text):
out=""
for ch in text:
out=ch+out
return outOptimized solution
Build through an iterator and one join rather than repeated string concatenation.
- Iterate reversed code points.
- Join into one string.
def reverse_text(text):
return "".join(reversed(text))
print(reverse_text("campus"))
Complexity analysis
Time: O(n)
Auxiliary space: O(n) result construction.
Test cases
- Empty string.
- One character.
- Combining marks are reversed as separate code points.
assert reverse_text("campus") == "supmac"
assert reverse_text("") == ""
assert reverse_text("aba") == "aba"Common mistakes
- Assuming code points equal grapheme clusters.
- Trying to mutate a str.
Key takeaways
- Strings are immutable.
- Define Unicode semantics.
- Avoid repeated copying.
Follow-up challenges
- How would grapheme-aware reversal differ?
- How would an in-place char array differ?