S1Q1 · Reverse First Half¶
⚡ Quick Reference
Function: reverse_first_half(s: str) -> str
Core idea: Split at len(s) // 2, reverse the left half, keep the right half as-is.
Key rules:
- mid = len(s) // 2 (integer division -- rounds down for odd lengths)
- Odd length: middle character falls in the second half (s[mid:])
- s[:mid][::-1] reverses the first half slice
Problem Statement¶
Problem
Write a function reverse_first_half(s) that returns a new string formed by reversing only the first half of s, keeping the second half unchanged. For odd-length strings, the middle character belongs to the second half.
Examples:
reverse_first_half("abcdef")
'cbadef'
reverse_first_half("python")
'typhon'
Understanding the problem¶
mid = len(s) // 2 uses integer (floor) division, which rounds down for odd lengths -- so the middle character always falls into the second half.
| Input | Length | mid |
First half | Reversed | Second half | Result |
|---|---|---|---|---|---|---|
"abcdef" |
6 | 3 | "abc" |
"cba" |
"def" |
"cbadef" |
"python" |
6 | 3 | "pyt" |
"typ" |
"hon" |
"typhon" |
"abcde" |
5 | 2 | "ab" |
"ba" |
"cde" |
"bacde" |
"a" |
1 | 0 | "" |
"" |
"a" |
"a" |
Floor division handles odd lengths automatically
len("abcde") // 2 = 2, so s[:2] = "ab" is the first half and s[2:] = "cde" (including the middle "c") is the second half. No special-case needed for odd lengths -- // takes care of it.
Solution approaches¶
Key takeaways¶
Floor division for midpoint
len(s) // 2 always gives the index of the midpoint rounded down. For even lengths it splits exactly in half; for odd lengths the left half is one character shorter, so the middle character lands in the right half.
Slice reversal: s[::-1]
The step -1 in a slice reverses any sequence. s[:mid][::-1] first slices the first half, then reverses it. This works on strings, lists, and tuples alike.
String concatenation to reassemble
After reversing the first half, concatenate it with the unchanged second half using +. No join or loop needed -- slicing produces strings that can be directly combined.