Skip to content

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.

def combine_edges(s: str) -> str:
    if len(s) < 4:
        return ""
    return s[:2] + s[-2:]

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:

Input
"Programming"
Output
"Prng"
Input
"abc"
Output
""
Input
"abcd"
Output
"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

def combine_edges(s: str) -> str:
    if len(s) < 4:
        return ""
    return s[:2] + s[-2:]
def combine_edges(s: str) -> str:
    if len(s) < 4:
        return ""
    first_two = s[:2]
    last_two  = s[-2:]
    return first_two + last_two
def combine_edges(s: str) -> str:
    return s[:2] + s[-2:] if len(s) >= 4 else ""
combine_edges = lambda s: s[:2] + s[-2:] if len(s) >= 4 else ""

Key takeaways

01

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.

02

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.

03

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.