S1Q3 · Combine First and Last Two Characters¶
⚡ Quick Reference
Function: combine_edges(s: str) -> str
Core idea: take the first two and last two characters; return empty string if length < 4.
Key rules:
- len(s) < 4 → return ""
- First two: s[:2]
- Last two: s[-2:]
- Concatenate both
Problem Statement¶
Problem
Write a function combine_edges(s) that returns a string made of the first two and last two characters of s. Return "" if len(s) < 4.
Examples:
"Programming"
"Prng"
"abc"
""
"abcd"
"abcd"
Tracing examples¶
| Input | Length | s[:2] |
s[-2:] |
Result |
|---|---|---|---|---|
"Programming" |
11 | "Pr" |
"ng" |
"Prng" ✓ |
"abc" |
3 | - | - | "" ✓ |
"abcd" |
4 | "ab" |
"cd" |
"abcd" ✓ |
"ab" |
2 | - | - | "" ✓ |
Length exactly 4 - slices overlap safely
For "abcd" (length 4): s[:2] = "ab" and s[-2:] = "cd". No overlap - the result is the full string. For length 3: s[:2] = "ab" and s[-2:] = "bc" would overlap - but we return "" before reaching that.
Solution approaches¶
Key takeaways¶
s[:2] and s[-2:] - clean edge slicing
s[:2] always gives the first two characters; s[-2:] always gives the last two. These work for any string of length ≥ 4 without any index arithmetic.
Guard length < 4 before slicing
Without the guard, "ab"[:2] + "ab"[-2:] = "ab" + "ab" = "abab" - wrong. For strings shorter than 4, slices overlap and produce incorrect results. Always check length first.
Exactly length 4 → returns the full string
For "abcd": s[:2]="ab" and s[-2:]="cd" together give "abcd". The slices partition the string without overlap, so the result is the original string.