Skip to content

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.

def reverse_first_half(s):
    mid = len(s) // 2
    return s[:mid][::-1] + s[mid:]

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:

Call
reverse_first_half("abcdef")
Output
'cbadef'
Call
reverse_first_half("python")
Output
'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

def reverse_first_half(s: str) -> str:
    mid = len(s) // 2          # floor division: middle char goes to second half
    first_half  = s[:mid]      # characters before the midpoint
    second_half = s[mid:]      # midpoint onwards (includes middle char if odd)
    return first_half[::-1] + second_half
def reverse_first_half(s: str) -> str:
    mid = len(s) // 2
    return s[:mid][::-1] + s[mid:]
reverse_first_half = lambda s: s[:len(s)//2][::-1] + s[len(s)//2:]

Key takeaways

01

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.

02

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.

03

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.