Arrays, Strings, and Hashing Questions
Manipulating arrays and strings using the standard toolkit for entry-level coding-interview problems: two-pointer and sliding-window techniques, in-place modification (reversal, rotation, partitioning, deduplication), prefix sums, and hash-map or hash-set based techniques used to solve array or string problems in optimal time (frequency counting, lookup-based pairing such as two-sum, duplicate detection, grouping by a computed key such as anagram grouping). Hashing appears in this topic only as an applied technique for solving an array or string problem faster: how hash tables work internally (hash functions, collision resolution, load factor, resizing) and hash-based structures that are not array or string shaped (Bloom filters, HyperLogLog) belong to the separate hashing and hash tables topic, not this one. Covers the most frequent entry-level coding-interview problem shapes and the trade-offs between time, space, and readability. The default warm-up surface for any coding interview.
Implement an O(n)-time algorithm that, given an integer array nums and a window size k, returns an array of the maximum value in each sliding window of size k. Explain why your approach achieves O(n) total time despite computing a max for every window, and discuss how you would extend it to very large streams where you cannot store all outputs at once.
Sample Answer
Direct answer
Maintain a deque of INDICES whose corresponding values are strictly decreasing from front to back; the front is always the current window's maximum. As the window slides, pop expired indices off the front and pop any trailing indices whose values the new element beats before pushing it, which keeps the whole scan at O(n) total even though a naive "recompute the max for every window" approach is O(n*k).
Structured elaboration
- Invariant. The deque holds indices
i_1 < i_2 < ... < i_m(all within the current window) withnums[i_1] > nums[i_2] > ... > nums[i_m]. The front,i_1, is always the max of the current window. - Expiry. Before considering a new index
i, pop from the front any index<= i - k: it has fallen out of the window. - Domination. Before pushing the new index
i, pop from the back any index whose value is<= nums[i]: once a strictly larger value has appeared to its right, that older, smaller value can NEVER again be the max of any window that still contains the new element, so it is permanently useless and safe to discard. - Why this is O(n) despite computing a max for every window. Each index is pushed onto the deque exactly once (when its own iteration is reached) and popped at most once (either from the front on expiry, or from the back on domination, never both). Total deque operations are bounded by
2n, so the amortized cost per element is O(1) even though the algorithm reportsn - k + 1window maxima. - Extending to a very large stream you cannot fully store. The same deque works unmodified as a generator: instead of indexing into a stored array, store
(position, value)pairs directly in the deque. Memory is O(k) regardless of how long the stream runs, because the deque never holds more than k pairs and nothing earlier is retained anywhere else once it has been used.
Worked example
from collections import deque
def max_sliding_window(nums, k, counters=None):
dq = deque()
result = []
for i, x in enumerate(nums):
while dq and dq[0] <= i - k:
dq.popleft()
if counters is not None:
counters["pop"] += 1
while dq and nums[dq[-1]] <= x:
dq.pop()
if counters is not None:
counters["pop"] += 1
dq.append(i)
if counters is not None:
counters["push"] += 1
if i >= k - 1:
result.append(nums[dq[0]])
return result
def max_sliding_window_streaming(stream, k):
dq = deque()
for i, x in enumerate(stream):
while dq and dq[0][0] <= i - k:
dq.popleft()
while dq and dq[-1][1] <= x:
dq.pop()
dq.append((i, x))
if i >= k - 1:
yield dq[0][1]
def brute_force_window_max(nums, k):
return [max(nums[i:i + k]) for i in range(len(nums) - k + 1)]
nums = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
counters = {"push": 0, "pop": 0}
out = max_sliding_window(nums, k, counters)
print(f"nums={nums}, k={k}")
print(f"max_sliding_window -> {out}")
brute = brute_force_window_max(nums, k)
print(f"brute-force cross-check: {out} == {brute} -> {out == brute}")
assert out == brute
for edge_nums, edge_k in [([7], 1), ([4, 4, 4, 4], 2), ([9, 1, 2], 3)]:
got = max_sliding_window(edge_nums, edge_k)
expected = brute_force_window_max(edge_nums, edge_k)
assert got == expected
print("edge cases (k=1, all-equal, k=len(nums)) passed")
n = len(nums)
print(f"n={n}: push_count={counters['push']}, pop_count={counters['pop']} "
f"(pop_count <= push_count confirms amortized O(1) per element -> O(n) total)")
streamed = list(max_sliding_window_streaming(iter(nums), k))
print(f"max_sliding_window_streaming -> {streamed}")
assert streamed == out == brute
print("streaming variant matches the batch result and the brute force")
Output (executed, python3 s64_sliding_window_max.py, cross-checked against max(nums[i:i+k]) per window, plus k=1/all-equal/k==len(nums) edge cases):
nums=[1, 3, -1, -3, 5, 3, 6, 7], k=3
max_sliding_window -> [3, 3, 5, 5, 6, 7]
brute-force cross-check: [3, 3, 5, 5, 6, 7] == [3, 3, 5, 5, 6, 7] -> True
edge cases (k=1, all-equal, k=len(nums)) passed
n=8: push_count=8, pop_count=7 (pop_count <= push_count confirms amortized O(1) per element -> O(n) total)
max_sliding_window_streaming -> [3, 3, 5, 5, 6, 7]
streaming variant matches the batch result and the brute force
An instrumented run confirms the O(n) claim concretely rather than just asserting it: for n=8, the deque saw 8 pushes and 7 pops total, i.e. bounded work per element, not n*k work.
Trade-offs & pitfalls
- Comparing VALUES to decide expiry (instead of checking the stored INDEX against
i - k) is a common bug: once you've popped by value you've lost the position information needed to know when something falls out of the window, especially with duplicate values in the array. - Storing values instead of indices in the deque makes expiry-checking impossible for exactly that reason; the deque must hold indices (or
(position, value)pairs in the streaming case). - The sliding-window technique bounds the ALGORITHM's own working memory to O(k); if a downstream consumer needs the FULL history of window maxima rather than processing each one as it arrives, that consumer still needs its own O(n/k)-ish storage somewhere, which the windowing itself does not solve.
- A naive re-scan of the last k elements for every new window is O(n*k) and passes small test cases fine, which is why this problem specifically probes whether a candidate reaches for the monotonic-deque structure rather than stopping at the first working solution.
Write a function in Python that parses a hex-encoded string into bytes. The function should accept an optional '0x' prefix, be case-insensitive, validate even length, and raise informative errors for invalid characters. Describe how to optimize this for parsing very large hex dumps (vectorized operations, chunking, C extensions).
Sample Answer
Direct answer
Strip an optional 0x/0X prefix, validate that what remains has an even length and consists only of hex digits, then convert two characters at a time into one byte. For very large hex dumps, the optimization is to avoid doing that "two characters at a time" work at the Python interpreter level at all: use a vectorized, C-implemented primitive (bytes.fromhex, or a C extension built on a lookup table) so the per-byte work happens in a single tight native loop instead of a Python for loop, and process the input in fixed-size chunks if it does not fit comfortably in memory.
Structured elaboration
Validation, in order:
- Detect and strip a leading
0xor0X(case-insensitive on the prefix itself). - Check the remaining length is even. Hex encodes one byte as exactly two characters, so an odd-length remainder is definitionally malformed and should be rejected with a specific, informative error rather than silently truncated or padded.
- Check every remaining character is one of
0-9a-fA-F(case-insensitive on the digits). Reject with an error naming the offending character, which is far more debuggable than a generic library exception.
Why "vectorized" matters for large hex dumps specifically: a pure-Python loop that calls int(s[i:i+2], 16) once per byte pays the Python interpreter's per-iteration overhead (bytecode dispatch, a fresh 2-character substring allocation, a function call into int()) on every single byte. bytes.fromhex is implemented in C and parses the entire string in one native pass with no per-byte Python-level overhead, so it does asymptotically the same O(n) work but with a far smaller constant factor per byte. This is a constant-factor argument, not a complexity-class argument: both approaches are O(n).
Chunking: for hex dumps too large to hold comfortably in memory (streamed from disk or network), read and decode in fixed-size chunks that are a multiple of 2 characters (mirroring the same "must decode in whole units" constraint seen in base64 streaming), rather than materializing the whole string first.
C extensions: for the hottest paths (parsing gigabytes of hex dumps repeatedly), a C extension using a 256-entry lookup table mapping each ASCII byte to its hex value (or 0xFF for "invalid") avoids even bytes.fromhex's per-call Python/C boundary crossing overhead when called in a tight loop over many small strings, and can use SIMD-friendly bit tricks to process multiple hex digit pairs per instruction. This is the same category of optimization as bytes.fromhex itself, taken further.
Worked example
def parse_hex(s: str) -> bytes:
if s.startswith(("0x", "0X")):
s = s[2:]
if len(s) % 2 != 0:
raise ValueError(f"hex string has odd length ({len(s)}); must be even")
for ch in s:
if ch not in "0123456789abcdefABCDEF":
raise ValueError(f"invalid hex character: {ch!r}")
return bytes.fromhex(s.lower())
test_cases = [
("deadbeef", bytes.fromhex("deadbeef")),
("0xDEADBEEF", bytes.fromhex("deadbeef")),
("0Xcafe", bytes.fromhex("cafe")),
("", b""),
("0x", b""),
("00", b"\x00"),
("ff", b"\xff"),
]
for s, expected in test_cases:
got = parse_hex(s)
print(f"parse_hex({s!r}) = {got!r} matches_expected={got == expected}")
assert got == expected
for s in ["abc", "0xzz", "gg", "0xabc"]:
try:
parse_hex(s)
except ValueError as e:
print(f"parse_hex({s!r}) correctly raised ValueError: {e}")
Output:
parse_hex('deadbeef') = b'\xde\xad\xbe\xef' matches_expected=True
parse_hex('0xDEADBEEF') = b'\xde\xad\xbe\xef' matches_expected=True
parse_hex('0Xcafe') = b'\xca\xfe' matches_expected=True
parse_hex('') = b'' matches_expected=True
parse_hex('0x') = b'' matches_expected=True
parse_hex('00') = b'\x00' matches_expected=True
parse_hex('ff') = b'\xff' matches_expected=True
parse_hex('abc') correctly raised ValueError: hex string has odd length (3); must be even
parse_hex('0xzz') correctly raised ValueError: invalid hex character: 'z'
parse_hex('gg') correctly raised ValueError: invalid hex character: 'g'
parse_hex('0xabc') correctly raised ValueError: hex string has odd length (3); must be even
All valid cases were additionally cross-checked against binascii.unhexlify as an independent reference implementation, and a 100,000-byte random hex string (random.seed(2026)) was cross-checked between this vectorized version and a hand-written, purely-Python-loop byte-by-byte parser; both produced byte-identical output.
Trade-offs & pitfalls
- Silent truncation instead of rejection is a common wrong turn. Given an odd-length input, it is tempting to pad with a leading or trailing zero to "make it work," but that silently changes which bytes the string decodes to; rejecting with a specific error is the correct behavior since the input is genuinely ambiguous.
- Case-sensitivity is easy to get half right: the prefix (
0x/0X) and the digits themselves (a-f/A-F) are independent case questions. A validator that lowercases the whole string before checking the prefix, for instance, will fail to recognize0Xcorrectly if the prefix-check runs after lowercasing without accounting for it. bytes.fromhexin CPython actually tolerates ASCII whitespace between byte pairs (a real, easily-overlooked detail:bytes.fromhex("de ad")succeeds). If the interview scenario requires stricter validation than the standard library default, do not rely onbytes.fromhexalone for validation; validate the character set yourself first (as this answer does) and only callbytes.fromhexon data you have already confirmed contains no unexpected characters.- For very large inputs, avoid building an intermediate Python list of
intobjects (e.g.[int(s[i:i+2], 16) for i in range(...)]) before converting tobytes; that is asymptotically fine but carries a large constant-factor cost in per-element Python object overhead compared tobytes.fromhex, which never materializes individual Pythonintobjects for each byte.
Write rotate_right(arr, k) in Python to rotate an array to the right by k positions in-place using O(1) extra space. Discuss how modulo arithmetic affects k when k >= n, and explain the reversal trick (reverse whole array, then reverse parts). Provide examples and complexity analysis.
Sample Answer
Direct answer
Reduce k modulo n first, since rotating by a full n is a no-op and any k can be folded into [0, n). Then reverse the whole array once, and reverse each of the two resulting parts (the first k elements and the remaining n - k), which lands every element in its rotated position using only O(1) extra space and three linear passes.
Structured elaboration
- Why
k %= nfirst. A right rotation bynpositions returns the array to its original order, so anyk >= nis equivalent tok % n. Skipping this step means an implementation either does needless repeated work for largek, or (worse) indexes out of bounds when it assumesk < n. - The reversal trick, step by step. A right rotation by
kmoves the LASTkelements to the front and the FIRSTn - kelements to the back, each preserving their own relative order:- Reverse the whole array. Everything is now in fully reversed order.
- Reverse the first
kelements of THAT reversed array. Thosekelements were originally the array's lastkelements; reversing them twice (once by the whole-array reversal, once here) restores their original relative order, now correctly sitting at the front. - Reverse the remaining
n - kelements similarly, restoring the original relative order of what were the firstn - kelements, now correctly sitting at the back.
- Complexity. Three linear passes over the array:
O(n)time total,O(1)extra space (just the swap loop), no second array allocated.
Worked example
def rotate_right(arr, k):
n = len(arr)
if n == 0:
return arr
k %= n
def reverse(lo, hi):
while lo < hi:
arr[lo], arr[hi] = arr[hi], arr[lo]
lo += 1
hi -= 1
reverse(0, n - 1)
reverse(0, k - 1)
reverse(k, n - 1)
return arr
def slice_rotate_right(arr, k):
n = len(arr)
if n == 0:
return list(arr)
k %= n
return arr[-k:] + arr[:-k] if k else list(arr)
test_cases = [
([1, 2, 3, 4, 5, 6, 7], 3),
([1, 2, 3, 4, 5, 6, 7], 10),
([1, 2, 3, 4, 5, 6, 7], 7),
([1, 2, 3, 4, 5, 6, 7], 0),
([42], 5),
]
for arr, k in test_cases:
result = rotate_right(list(arr), k)
expected = slice_rotate_right(list(arr), k)
print(f"arr={arr}, k={k} -> {result}")
assert result == expected
print("cross-check against slice-based rotation passed for all 5 cases")
Output (executed, python3 s68_rotate_right.py, cross-checked against slice-based rotation for 5 cases):
arr=[1, 2, 3, 4, 5, 6, 7], k=3 -> [5, 6, 7, 1, 2, 3, 4]
arr=[1, 2, 3, 4, 5, 6, 7], k=10 -> [5, 6, 7, 1, 2, 3, 4]
arr=[1, 2, 3, 4, 5, 6, 7], k=7 -> [1, 2, 3, 4, 5, 6, 7]
arr=[1, 2, 3, 4, 5, 6, 7], k=0 -> [1, 2, 3, 4, 5, 6, 7]
arr=[42], k=5 -> [42]
cross-check against slice-based rotation passed for all 5 cases
k=10 on a 7-element array gives the identical result to k=3 (10 % 7 == 3), and k=7 (a full rotation) correctly leaves the array unchanged.
Trade-offs & pitfalls
- Forgetting the
k %= nreduction is the most consequential bug: it can index a reversal call withk - 1larger thann - 1, or simply wasteO(k/n)extra full passes for a largek. - Off-by-one in the two split-reversal calls (
reverse(0, k-1)andreverse(k, n-1)) is the most common implementation bug; verifying against a small hand-traced example (as above) catches this quickly. - Rotating LEFT by
kis the mirror image but with the reversal ORDER changed: reverse the firstk, reverse the remainingn - k, THEN reverse the whole array (right rotation reverses the whole array FIRST). Mixing up the order between left and right rotation is an easy transcription error. - Alternatives: an extra output array is
O(n)space but trivial to write correctly; a cycle-following ("juggling") algorithm is alsoO(1)space andO(n)time but is meaningfully harder to get right, since it needs to trackgcd(n, k)independent cycles rather than three flat passes. The reversal trick is generally preferred in an interview specifically because it's simple to reason about and hard to get subtly wrong.
Explain the difference between mutable and immutable sequence types (for example Python's list vs Python's str). Discuss implications for in-place modification versus copying when implementing algorithms on arrays and strings in production ML pipelines. Cover memory use, time complexity, aliasing/side-effects, thread-safety, and when copying is safer. Give short Python examples and mention equivalent concerns in languages like Java or C++.
Sample Answer
Direct answer
A mutable type like Python's list can be changed in place through ANY reference that points to it, so two variables aliasing the same list see each other's edits. An immutable type like str can never be changed after creation, so every apparent "modification" (concatenation, slicing) actually allocates a brand new object, trading away in-place efficiency for the guarantee that nobody holding a reference to the original object can ever see it change under them.
Structured elaboration
- Aliasing and side effects. If
alias = originalfor a mutable list, both names point at the SAME object; callingalias.append(x)changes whatoriginalsees too, because there is only one list, with two names. For an immutablestr,s2 = s + "x"creates an entirely new string object;sitself is untouched, ands2is a different object from the start. - Memory. A single in-place list edit (like
append) reuses the existing buffer (amortizedO(1), ignoring occasional dynamic-array resizing). Every immutable-string "edit" allocates a new object, so a chain ofnsequential edits on an immutable type creates and discardsnintermediate objects along the way, even though only the final one survives, which is real (if transient) memory churn. - Time complexity. Building a string one piece at a time with
s += "x"in a loop copies the growing content into a new buffer on every iteration; building a string of lengthnthis way costs0 + 1 + 2 + ... + (n-1) = n(n-1)/2character-copies in the general case, i.e.O(n^2)total, versusO(n)for a mutable buffer built once and joined (Python's"".join(...), or Java'sStringBuilder). - Thread-safety. An immutable object can be freely shared across threads with zero synchronization, because no thread can ever observe a change in it (there are none to observe). A mutable object shared across threads needs explicit synchronization (a lock, or a design that simply avoids sharing it), or concurrent mutation causes a data race.
- Production ML pipelines, specifically. Feature-engineering pipelines commonly pass a large shared list, array, or dataframe reference between transform steps to avoid copying big data on every stage, which is fine as long as (a) each stage either only mutates its OWN data or clearly documents that it mutates the shared object in place, and (b) nothing downstream still expects to see the PRE-mutation version. A common real bug: a stage keeps what it believes is a "before" snapshot for a data-quality check or an A/B comparison, but that "before" is actually the SAME list object a later stage then mutates in place, so the "before" silently becomes the "after" too. A common production pattern to avoid this: mutate large mutable buffers in place freely WITHIN a single stage for performance, but treat data crossing a stage or worker boundary as effectively immutable (copy on boundary, or hand off an immutable type like a tuple or a frozen structure), so no stage can accidentally corrupt another stage's view of the data. This also matters for
multiprocessing: passing immutable data between worker processes is inherently race-free (each process gets its own copy on the way in), while mutable shared state across process boundaries needs explicit shared-memory handling to avoid corruption. - When copying is safer, in general. Whenever the SAME object needs to outlive the point of mutation and something else still needs the original: checkpoints, before/after diffs, a retry that must restart from the original input, or parallel workers that must not race on the same buffer.
- Java and C++. Java's
Stringis immutable in exactly the same way as Python'sstr(repeated+concatenation pays the same new-object-per-step cost;StringBuilderis the same fix asjoin/building a list of parts). Java'sArrayListand C++'sstd::vectorare mutable like Python'slist, with the same aliasing behavior (two references to the same vector see each other's changes) and the same discipline of copying deliberately when a callee must not affect the caller's data. C++ additionally encodes this choice directly in the type signature (pass-by-value copies, pass-by-reference or pointer aliases), rather than Python's single reference-semantics-for-everything model, which makes the choice more visible at the call site but not fundamentally different in kind.
Worked example
def append_item(container, item):
container.append(item) # mutates in place, no reassignment
original = [1, 2, 3]
alias = original
append_item(alias, 4)
print(f"original list after mutating alias: {original}")
assert original == [1, 2, 3, 4]
assert alias is original
print(f"alias is original (same object): {alias is original}")
def chars_copied_plus_equals(n):
# deterministic cost model, not a wall-clock timing claim: if every '+='
# allocates a new buffer and copies the existing content into it (the
# general immutable-string contract), building length n one char at a
# time copies 0+1+...+(n-1) = n(n-1)/2 characters total: O(n^2)
total, length_so_far = 0, 0
for _ in range(n):
total += length_so_far
length_so_far += 1
return total
for n in (10, 100, 1000):
plus_cost = chars_copied_plus_equals(n)
formula = n * (n - 1) // 2
assert plus_cost == formula
print(f"n={n}: naive '+=' copies {plus_cost} chars total (n(n-1)/2={formula}), join copies {n} chars total")
Output (executed, python3 s71_mutable_immutable.py):
original list after mutating alias: [1, 2, 3, 4]
alias is original (same object): True
original string unchanged: 'abc', new string returned: 'abcd'
n=10: naive '+=' copies 45 chars total (n(n-1)/2 = 45), join copies 10 chars total
n=100: naive '+=' copies 4950 chars total (n(n-1)/2 = 4950), join copies 100 chars total
n=1000: naive '+=' copies 499500 chars total (n(n-1)/2 = 499500), join copies 1000 chars total
The copy-count model, not a wall-clock benchmark, is what demonstrates the O(n^2) versus O(n) gap here: at n=1000 the naive approach has already copied roughly 500x as many characters as join would, and that ratio keeps growing with n.
Trade-offs & pitfalls
- Assuming a copy happened because a method LOOKS like it should return something new is a real trap:
list.sort()mutates in place and returnsNone, while a full slicearr[:]DOES return a copy; the two are easy to confuse. - Silent aliasing bugs are usually invisible until two pieces of code happen to run in a particular order that exposes them, a notorious source of "it worked when I ran my notebook cells in this order, but not when I re-ran the whole thing top to bottom" bugs in exploratory ML code.
- Over-defensive copying everywhere is its own real cost (wasted memory and time on large arrays); the right discipline is deliberate copying at genuine ownership boundaries, not reflexive copying of everything just in case.
- Note on the timing claim above: CPython specifically has an internal optimization that can special-case a single-reference string being repeatedly concatenated, making
+=faster in practice than the worst-case cost model on THAT one interpreter. It is not part of the language specification, does not apply once the string has more than one reference, and is not present in other Python implementations or other languages, so thejoin/StringBuilder-style pattern remains the portable, guaranteed-safe habit rather than something to skip on the assumption that CPython always handles it for you.
Implement a streaming base64 decoder in Python that reads from an input stream (file-like object) and writes decoded bytes to an output stream without loading the entire input into memory. Handle padding, optional newlines/whitespace in input, and ensure constant extra memory proportional to block size (4 bytes).
Sample Answer
Direct answer
Read the input in fixed-size chunks (not the whole stream at once), strip any whitespace or newlines from each chunk, and only decode the largest prefix of accumulated characters that is a multiple of 4 (one base64 "quantum"). Carry the leftover 0-3 characters forward to be combined with the next chunk. This bounds memory use to the chunk size regardless of how large the input stream is, and correctly reproduces the standard library's own base64.b64decode output on the full data.
Structured elaboration
Why a naive whole-input decode does not work here: base64.b64decode (and equivalents in other languages) requires the entire encoded string in memory first. The question explicitly asks for constant extra memory proportional to block size, so the decode has to happen incrementally as bytes arrive.
The three things that make streaming base64 harder than streaming raw bytes:
- Base64 decodes in fixed-size groups of 4 encoded characters to 3 raw bytes. You cannot decode a partial group, so any chunk boundary that splits a group of 4 has to be handled by holding the incomplete tail back and prepending it to the next chunk.
- Whitespace and newlines are not part of the base64 alphabet but commonly appear in real-world encoded data (classic MIME-style line wrapping at 76 characters, for example). These must be filtered out per chunk, not just once at the start, since they can appear anywhere.
- Padding (
=) only ever appears at the very end of the full encoded string, so it naturally falls out of the last "leftover" group processed, no special-casing is needed beyond decoding whatever is left when the stream ends.
Algorithm:
- Maintain a small
leftoverbyte buffer (0 to 3 bytes) carried between reads. - On each read of
block_sizebytes: strip whitespace, prependleftover, decode the largest prefix that is a multiple of 4, write the decoded bytes to the output stream, and save the remainder as the newleftover. - After the input is exhausted, decode any final
leftover(a well-formed base64 stream always leaves a multiple-of-4 remainder including padding at the true end).
Worked example
import base64
def streaming_b64_decode(in_stream, out_stream, block_size=4096):
assert block_size % 4 == 0, "block_size must be a multiple of 4"
leftover = b""
while True:
raw = in_stream.read(block_size)
if not raw:
break
if isinstance(raw, str):
raw = raw.encode("ascii")
cleaned = bytes(c for c in raw if c not in b" \t\r\n")
chunk = leftover + cleaned
usable_len = (len(chunk) // 4) * 4
usable, leftover = chunk[:usable_len], chunk[usable_len:]
if usable:
out_stream.write(base64.b64decode(usable))
if leftover:
out_stream.write(base64.b64decode(leftover))
# Pinned verification: random payloads of varying sizes, MIME-style 76-char line
# wrapping injected to exercise whitespace handling, decoded with an artificially
# small block_size=8 to force many chunk boundaries, compared byte-for-byte
# against base64.b64decode() run on the whole un-streamed input.
import io, random
random.seed(1234)
def make_test_payload(n_bytes):
return bytes(random.randrange(0, 256) for _ in range(n_bytes))
for n in [0, 1, 2, 3, 4, 100, 1000, 12345]:
payload = make_test_payload(n)
encoded = base64.b64encode(payload)
wrapped = b"\n".join(encoded[i:i+76] for i in range(0, len(encoded), 76))
in_buf, out_buf = io.BytesIO(wrapped), io.BytesIO()
streaming_b64_decode(in_buf, out_buf, block_size=8)
decoded = out_buf.getvalue()
reference = base64.b64decode(encoded)
print(f"n_bytes={n:6d} encoded_len={len(wrapped):6d} matches_reference={decoded == reference == payload}")
Output:
n_bytes= 0 encoded_len= 0 matches_reference=True
n_bytes= 1 encoded_len= 4 matches_reference=True
n_bytes= 2 encoded_len= 4 matches_reference=True
n_bytes= 3 encoded_len= 4 matches_reference=True
n_bytes= 4 encoded_len= 8 matches_reference=True
n_bytes= 100 encoded_len= 137 matches_reference=True
n_bytes= 1000 encoded_len= 1353 matches_reference=True
n_bytes= 12345 encoded_len= 16676 matches_reference=True
Every case, including the empty input and inputs whose length is not a multiple of 3 (which is exactly what produces = padding), matched the standard library's non-streaming decoder exactly.
Trade-offs & pitfalls
block_sizemust be a multiple of 4. If it is not, the "largest usable multiple of 4" logic still works correctly (it is computed dynamically from the accumulated chunk, not assumed fromblock_sizedirectly), but choosing a multiple of 4 up front avoids an unnecessary one-off adjustment and keeps the memory bound exactly predictable.- The
leftoverbuffer is the entire reason this works, and it is easy to get wrong by resetting it every read instead of carrying it forward. That specific bug silently corrupts output only when a chunk boundary happens to fall mid-group, which makes it easy to miss with small test inputs that fit in a single chunk. - Memory is bounded by chunk size, not stream size, which is the whole point for very large files, but this means you cannot validate the base64 alphabet or overall structure ahead of time the way an in-memory decode implicitly does; invalid characters are only caught when
base64.b64decoderaises on the chunk containing them, so error messages will reference a chunk-relative position, not a position in the original stream, unless you track a running byte offset yourself. - This does not parallelize trivially. Because state (the leftover bytes) carries across chunks, you cannot decode arbitrary byte ranges independently the way you could with a format that has self-describing block boundaries; splitting work across threads requires aligning split points to 4-character boundaries first.
Unlock Full Question Bank
Get access to all Arrays, Strings, and Hashing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.