Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; String itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)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…
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.
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.
def count_vowels(text):
vowels = set('aeiou')
return sum(character.casefold() in vowels for character in text)Implement count_vowels(text). Count ASCII vowels without changing the input, treating uppercase and lowercase letters equally.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def count_vowels(text):
vowels = set('aeiou')
return sum(character.casefold() in vowels for character in text)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.
def normalize_words(words):
parts = []
for word in words:
normalized = word.strip().lower()
if normalized:
parts.append(normalized)
return ' '.join(parts)Implement normalize_words(words). Strip and lowercase each non-empty word, then join the results with one space.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def normalize_words(words):
parts = []
for word in words:
normalized = word.strip().lower()
if normalized:
parts.append(normalized)
return ' '.join(parts)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.
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 valuesImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 valuesCall 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. |
| 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.
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.
strip() without a specification can remove meaningful leading or trailing characters.text[left:right] can add quadratic copying.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 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; String itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Count ASCII vowels | O(n) | O(n) | n input code points; the fixed vowel set and current normalized character use constant auxiliary space. |
| Normalize and join words | O(n + k) | O(n + k) | n total input/output text and k words; stores normalized pieces before one join. |
| Encode or decode framed strings | O(n + k) | O(n + k) | n payload code points and k records; includes length metadata and output. Decoder receives valid encoder-format data. |
O(1) working space for count_vowels; O(n + k) for normalize_words and the codec's constructed text/record output.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
text[0] = 'b'text = 'b' + text[1:]Where you will hit this: Count Vowels(opens in a new tab)
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.
count = sum(character in 'aeiou' for character in text)count = sum(character.casefold() in 'aeiou' for character in text)Where you will hit this: Count Vowels(opens in a new tab)
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.
fields = payload.split('#')[1:]separator = payload.index('#')
length = int(payload[:separator])
start = separator + 1
fields = [payload[start:start + length]]Where you will hit this: Encode and Decode Strings(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-12