Reverse One Slice Segment
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Practice workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Practice workspace
Problem
Implement reverse_slice_segment(text, start, end). Return a new string in which only text[start:end] is reversed; characters before start and from end onward stay in their original positions. Inputs satisfy 0 <= start <= end <= len(text).
Starter code
def reverse_slice_segment(text, start, end):
passTest cases
middle-segment
{
"args": [
"abcdef",
1,
5
]
}Expected: "aedcbf"
empty-segment
{
"args": [
"python",
3,
3
]
}Expected: "python"
Wizard outline
- Step 1: Preserve an empty segment
Return the original string when the half-open interval contains no characters. The start-equals-end case fixes the meaning of a half-open slice before any reversal is introduced.
- Step 2: Reverse the whole selected range
Use a negative slice step when the selected interval spans the complete string. A whole-string case isolates reversal syntax without yet requiring three-part composition.
- Step 3: Compose prefix, reversed middle, and suffix
Generalize the boundary cases into one expression that changes only text[start:end]. The final contract requires the same partition for every valid start and end pair.
Footguns and prerequisites
- The end index is excluded, so reversing through end would move one extra character.
- Strings are immutable; build and return a new string instead of trying to assign into text.
- strings
Reviewed references
Prepared Interview Problems
- Encode and Decode Strings(opens in a new tab)
Reverse One Slice Segment isolates the result is the unchanged prefix, the reversed half-open segment, and the unchanged suffix in that exact order. That focused state discipline is required when implementing encode decode strings as a complete Interview Problem.
Recommended approach and implementation
Use this drill when a transformation affects one contiguous string region while both outer regions remain unchanged. The result is the unchanged prefix, the reversed half-open segment, and the unchanged suffix in that exact order.
Why it works: The three slices partition text without overlap or omission. Reversing only the middle slice changes exactly text[start:end], so concatenating the unchanged outer slices satisfies the contract.
def reverse_slice_segment(text, start, end):
return text[:start] + text[start:end][::-1] + text[end:]