Display middle character or characters of a string
Filed under Optum (UnitedHealth Group)
Free read 1 of 3Verify expected output format for even vs odd length strings.
The question
Write a program to find and output the central character of an odd-length string or the middle two characters of an even-length string.
Constraints
- String length >= 1
- Input contains standard ASCII characters
Examples
- Input
- "test"
- Output
- "es"
- Why
- Length is 4 (even), so the middle two characters are returned.
- Input
- "hello"
- Output
- "l"
- Why
- Length is 5 (odd), so the single middle character is returned.
Approach
Verify expected output format for even vs odd length strings.
Check length parity using modulo operator. If odd, return index length/2. If even, return indices (length/2 - 1) to length/2.
Direct index slicing: mid = len(s) // 2; return s[mid-1:mid+1] if len(s) % 2 == 0 else s[mid].
Single character string should return the character itself.
Solution
O(N) time to slice/access, O(N) space for output
def get_middle(s: str) -> str:
length = len(s)
mid = length // 2
if length % 2 == 0:
return s[mid - 1:mid + 1]
else:
return s[mid]
Tips
- What they are testing: Test strings of length 1, even lengths (2, 4), and odd lengths (1, 3, 5).
- Common mistake: Off-by-one errors in index calculation when dividing string length by 2.
Related Optum (UnitedHealth Group) questions
Collected from public candidate posts and coding forums. Updated Nov 2026.