Skip to contentKEEP THE CRAFTTHE SANCTUARY

String

Treat Python strings as immutable sequences of Unicode code points. Choose character normalization, efficient output construction, or explicit length boundaries according to what the interview problem needs to preserve.

8 practice exercises26 interview problems

Recognize it when The problem compares or transforms characters while preserving a stated text unit.

Checking your account…

String Code Labs

Mental Model

A Python string is an immutable sequence of Unicode code points. An index identifies a position in that sequence, but no operation can replace a character in place. Every transformation must either reuse the original object or construct a new string. This ownership fact explains both the clean API and the hidden cost of careless concatenation.

For a scan, define what the processed prefix means. If count is the number of normalized vowels in text[:index], reading text[index] extends that proof by exactly one character.

Immutability and Python String Costs

Indexing reads one character. A slice copies the selected range, so slicing k characters costs O(k) time and space. Membership in a short fixed literal such as "aeiou" is bounded by that literal’s size, while membership in a long string is linear in the searched text.

Normalization is part of the contract. lower() is often enough for an ASCII interview prompt; casefold() is the stronger Unicode-oriented normalization. Neither operation mutates the source, and both may allocate a new string.

Scan Normalized Characters

Reference
def count_vowels(text):
    vowels = set('aeiou')
    return sum(character.casefold() in vowels for character in text)
Practice

Implement count_vowels(text). Count ASCII vowels without changing the input, treating uppercase and lowercase letters equally.

Public tests

  • Verify mixed-case normalization
  • Verify immutable source semantics

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Scan Normalized Characters

def count_vowels(text):
    vowels = set('aeiou')
    return sum(character.casefold() in vowels for character in text)

Build Output Without Recopying Prefixes

Repeated result += piece can copy the growing prefix on each iteration. Accumulate pieces in a list, then call "".join(parts) once. This makes the construction cost proportional to the total output size rather than the sum of every intermediate prefix.

Use a list comprehension when each input produces one independent piece. Use an explicit loop when the next piece depends on parsing state, escaping, or a previous character.

Build Normalized Words Once

Reference
def normalize_words(words):
    parts = []
    for word in words:
        normalized = word.strip().lower()
        if normalized:
            parts.append(normalized)
    return ' '.join(parts)
Practice

Implement normalize_words(words). Strip and lowercase each non-empty word, then join the results with one space.

Public tests

  • Verify one final joined output

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build Normalized Words Once

def normalize_words(words):
    parts = []
    for word in words:
        normalized = word.strip().lower()
        if normalized:
            parts.append(normalized)
    return ' '.join(parts)

Parse with an Explicit Boundary Contract

A delimiter alone is ambiguous when the original strings may contain that delimiter. A length prefix makes the boundary self-describing: write the decimal length, a separator, then exactly that many characters. During decoding, find the separator, parse the length, and advance by the stated payload size. The invariant is that index always points at the beginning of the next length field.

Encode Explicit String Boundaries

Reference
def encode_strings(values):
    return ''.join(f'{len(value)}#{value}' for value in values)

def decode_strings(payload):
    values = []
    index = 0
    while index < len(payload):
        separator = payload.index('#', index)
        length = int(payload[index:separator])
        start = separator + 1
        end = start + length
        values.append(payload[start:end])
        index = end
    return values
Practice

Implement encode_strings(values) and decode_strings(payload) with decimal length prefixes followed by # and the exact string payload. decode_strings receives only valid encodings: nonnegative decimal lengths followed by # and exactly that many Unicode code points for each payload.

Public tests

  • Verify ambiguous payload boundaries
  • Verify empty collection round trip

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Encode Explicit String Boundaries

def encode_strings(values):
    return ''.join(f'{len(value)}#{value}' for value in values)

def decode_strings(payload):
    values = []
    index = 0
    while index < len(payload):
        separator = payload.index('#', index)
        length = int(payload[index:separator])
        start = separator + 1
        end = start + length
        values.append(payload[start:end])
        index = end
    return values

Trace Length Boundaries and the Decoder Cursor

Call the existing codec with an empty value, text containing #, and one Unicode character. The delimiter identifies only the end of a length prefix. After that point, the stated length determines the payload boundary.

print(encode_strings(['', 'x#y', '雪'])) followed by print(decode_strings('0#3#x#y1#雪')) followed by print(decode_strings(''))

Step Executed statement State Why
1 return ''.join(f'{len(value)}#{value}' for value in values) pieces = '0#', '3#x#y', '1#雪'; payload = '0#3#x#y1#雪' Each prefix describes the following value in code points, including zero.
2 separator = payload.index('#', index); length = int(payload[index:separator]) index = 0; separator = 1; length = 0 The first delimiter ends the prefix, not a payload value.
3 start = separator + 1; end = start + length; values.append(payload[start:end]); index = end start = 2; end = 2; values = ['']; index = 2 An empty slice is a valid empty value, and advancing over its prefix makes progress.
4 separator = payload.index('#', index); length = int(payload[index:separator]) index = 2; separator = 3; length = 3 Only the next prefix delimiter matters; the later delimiter belongs to the payload.
5 start = separator + 1; end = start + length; values.append(payload[start:end]); index = end start = 4; end = 7; values = ['', 'x#y']; index = 7 The exact three-character slice preserves the embedded #.
6 separator = payload.index('#', index); length = int(payload[index:separator]); start = separator + 1; end = start + length; values.append(payload[start:end]); index = end length = 1; start = 9; end = 10; values = ['', 'x#y', '雪'] The final cursor equals payload length, so the loop ends without inventing another value.
Print Output
1 0#3#x#y1#雪
2 ['', 'x#y', '雪']
3 []

The zero-length field still advances past its prefix. The # inside x#y remains payload text, and both len and slicing count the same code-point unit for 雪. This decoder Lab assumes well-formed encoder output; malformed-input validation is a separate contract.

This approach handles empty strings and delimiter characters without escaping. Its work is linear in the encoded output size. Python string lengths count Unicode code points, which is consistent because the encoder and decoder use the same representation in the same runtime.

Choose a String Technique

Use indices when you only need boundaries; taking a slice on every iteration adds copying. Use a list of characters when positions must be edited before producing the final string. Use a set or dictionary for repeated membership/count queries, and a sliding window when the answer concerns a contiguous substring whose state can be updated incrementally.

Do not sort merely to compare strings when a frequency table preserves all required information in linear time. Conversely, sorting can be the clearest canonical signature when the alphabet is not small and the additional O(k log k) work fits the constraints.

Text Normalization and Boundary Mistakes

  • Calling strip() without a specification can remove meaningful leading or trailing characters.
  • Splitting on a delimiter loses information when fields may contain that delimiter or be empty.
  • Building every candidate substring with text[left:right] can add quadratic copying.
  • Treating user-visible grapheme clusters as single Python characters is unsafe for general Unicode text; interview prompts normally define a simpler character model.

Explain It in an Interview

Say which unit the prompt calls a character, whether normalization is required, and whether indices or copied substrings are stored. While coding, state the prefix or parser-boundary invariant. When giving complexity, include every created slice and the size of the final output, not just the number of loop iterations.

Count Vowels(opens in a new tab) practices a normalized scan. Encode and Decode Strings(opens in a new tab) then tests whether the boundary contract survives empty values and payloads containing punctuation.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Count ASCII vowelsO(n)O(n)n input code points; the fixed vowel set and current normalized character use constant auxiliary space.
Normalize and join wordsO(n + k)O(n + k)n total input/output text and k words; stores normalized pieces before one join.
Encode or decode framed stringsO(n + k)O(n + k)n payload code points and k records; includes length metadata and output. Decoder receives valid encoder-format data.

Space

O(1) working space for count_vowels; O(n + k) for normalize_words and the codec's constructed text/record output.

Assumptions

  • n is total input text length; constructed normalized output can require linear space.
  • n payload code points and k records; includes length metadata and output. Decoder receives valid encoder-format data.

Invariants Worth Saying Aloud

  1. A string operation creates a new value; an indexed character cannot be assigned.
  2. Normalization follows the problem's comparison rules rather than removing arbitrary meaningful text.
  3. The decoding cursor points to the next length prefix, and payload length advances it exactly past one value.

When To Use Or Avoid String

Use It When

  • Scan characters for independent predicates such as ASCII vowel membership.
  • Collect normalized non-empty words and join once.
  • Use length prefixes when arbitrary text can contain the separator.

Choose Another Tool When

  • Use a list of characters when the problem needs repeated in-place position updates.
  • Do not assume one code point equals one visible symbol in a Unicode-sensitive problem.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Assigning to an immutable character position

A string supports indexed reads but rejects indexed assignment. A replacement must construct another string and bind that result.

Prevent it: Construct the changed text, or use a mutable character list when many position changes are required.

Avoid

text[0] = 'b'

Use instead

text = 'b' + text[1:]

Forgetting the scan's comparison normalization

Testing uppercase A directly against lowercase vowels misses it. The Lab's predicate normalizes each character before membership.

Prevent it: Apply the agreed normalization at the comparison boundary and test mixed case.

Avoid

count = sum(character in 'aeiou' for character in text)

Use instead

count = sum(character.casefold() in 'aeiou' for character in text)

Splitting a length-framed payload on every delimiter

The delimiter inside x#y is data. Splitting all delimiters destroys the one-value payload even though its prefix states a length of three.

Prevent it: Locate the prefix delimiter once, parse its length, and slice exactly that many characters for this field.

Avoid

fields = payload.split('#')[1:]

Use instead

separator = payload.index('#')
length = int(payload[:separator])
start = separator + 1
fields = [payload[start:start + length]]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.