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 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.
Implement the Boyer-Moore majority vote algorithm in Python to find the element that appears more than n/2 times in an array. Your solution should run in O(n) time and O(1) extra space. Explain why the algorithm finds a candidate and why a verification pass is needed.
Sample Answer
Direct answer
Boyer-Moore majority vote keeps a single candidate and a counter. Walking the array once, a match with the candidate increments the counter, a mismatch decrements it, and whenever the counter hits zero the candidate is replaced by the current element. If a true majority element exists (one appearing more than n/2 times), this candidate is guaranteed to be it, and a second pass over the array verifies the count exceeds n/2 before returning it, since the vote alone does not check that a majority actually exists. Both passes are single linear scans and the only extra memory is the candidate and the counter, so the whole algorithm runs in O(n) time and O(1) extra space, exactly the bound the question asks for.
Structured elaboration
Why the vote finds the right candidate
Think of each occurrence of the eventual majority element as a "+1 vote" and every other element as a "-1 vote" against whatever the current candidate happens to be. Because the majority element appears more than n/2 times, its total positive contribution outweighs everything else combined, no matter how the non-majority elements are arranged. The counter resetting to zero and swapping candidates effectively cancels out one occurrence of the current candidate against one occurrence of something else, a kind of pairing-off. Since the true majority element has more occurrences than everything else put together, it can never be fully cancelled out: it always survives as the final candidate once all the cancellation has happened.
Why a verification pass is required
The vote procedure always produces SOME candidate, even when no true majority element exists at all. Consider an array with no repeated majority: the same cancel-and-replace dynamic still runs and still ends with some element left standing as "candidate," but that element might appear far less than n/2 times. The algorithm's guarantee is one-directional: IF a majority exists, the vote finds it; it says nothing about whether a majority exists in the first place. The second, verification pass counts the actual occurrences of the candidate and checks that count against n/2, which turns "a plausible candidate" into "a proven majority element" (or correctly reports that none exists).
Worked example
def majority_element(nums):
candidate = None
count = 0
for x in nums:
if count == 0:
candidate = x
count += 1 if x == candidate else -1
verify_count = sum(1 for x in nums if x == candidate)
if verify_count > len(nums) // 2:
return candidate
return None
nums1 = [2, 2, 1, 1, 1, 2, 2]
print(majority_element(nums1))
nums2 = [1, 2, 3, 4]
print(majority_element(nums2))
Output:
2
None
For [2, 2, 1, 1, 1, 2, 2] (length 7, so a majority needs more than 3 occurrences), 2 appears 4 times and the vote correctly settles on it. For [1, 2, 3, 4], every value appears exactly once, so no majority exists at all: the vote still produces SOME candidate internally as it runs, but the verification pass catches that its true count (1) does not exceed 4 // 2 = 2, and the function correctly returns None rather than a wrong answer.
Trade-offs and pitfalls
The most common mistake is skipping the verification pass entirely and trusting the vote's output unconditionally, which silently returns a wrong "majority" on any input where no true majority exists, exactly the [1, 2, 3, 4] case above. A second is resetting the counter to zero but forgetting to also update the candidate to the current element at that moment, which breaks the cancellation logic the whole proof depends on. This algorithm specifically finds an element appearing more than n/2 times; a different and looser problem, find any element appearing at least n/k times for some k > 2, needs the generalized Boyer-Moore voting scheme with k-1 candidate slots instead of one, not this exact two-variable version. The same vote-and-verify logic is unchanged in Java or JavaScript, since it only relies on equality comparison and increment/decrement.
Given a list of meeting time intervals represented as [start, end], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input. Example: [[1,3],[2,6],[8,10],[15,18]] -> [[1,6],[8,10],[15,18]]. Explain sorting and merging steps and complexity.
Sample Answer
Direct answer
Sort the intervals by their start value, then sweep through them once, keeping a running "last merged interval": if the next interval's start is at or before that interval's end (an overlap, or an exact touch), extend the running interval's end to cover it; otherwise, the next interval begins a new, separate merged interval. This is O(n log n) time, dominated entirely by the initial sort, and O(n) space for the output.
Structured elaboration
Why sort by start first. Without imposing an order, a single forward pass cannot be trusted to have already seen every interval that might overlap the one currently being examined; an interval appearing later in the input array could easily start earlier than one already processed. Sorting by start guarantees that once the sweep has moved past a given point, every remaining interval starts at or after it, which is exactly what makes a single linear sweep afterward sufficient.
The merge step itself. Initialize the output with the first (now sorted) interval. For each subsequent interval [s, e], compare s against the END of the last interval currently in the output. If s <= last.end, the two intervals overlap or exactly touch, so extend the last interval's end to max(last.end, e), using max rather than just assigning e directly, because a later interval can be fully NESTED inside the one already being extended (a smaller end than the current running interval), and assigning e unconditionally would incorrectly shrink coverage that the merged interval already legitimately spans. If s > last.end, there is a genuine gap, and [s, e] starts a new entry in the output.
Complexity. The sort is O(n log n) and dominates the total cost; the sweep afterward visits each interval exactly once, O(n). The output requires O(n) space in the worst case (no intervals overlap at all, so every input interval becomes its own output entry).
Touching versus overlapping, a design decision worth naming. Whether two intervals that exactly touch (one's end equals the next one's start, such as [1,4] and [4,5]) should merge is a real semantic choice, not an automatic consequence of the algorithm. Using <= in the overlap check treats a touch as mergeable (matching how meeting-room-style problems usually intend adjacency: back-to-back meetings occupy no coverage gap), while a strict < would keep them as separate, back-to-back intervals; a senior answer should state explicitly which convention is being used rather than leave it implicit.
Worked example
def merge_intervals(intervals):
if not intervals:
return []
ordered = sorted(intervals, key=lambda pair: pair[0])
merged = [list(ordered[0])]
for start, end in ordered[1:]:
last = merged[-1]
if start <= last[1]:
last[1] = max(last[1], end)
else:
merged.append([start, end])
return merged
print(merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]))
# Independent cross-check: a genuinely different method (an event-counting sweep
# line) rather than a second copy of the same merge logic.
def sweep_line_reference(intervals):
if not intervals:
return []
events = []
for s, e in intervals:
events.append((s, 0, 1)) # start: delta +1, processed before ends at same coord
events.append((e, 1, -1)) # end: delta -1
events.sort()
result = []
active = 0
run_start = None
for pos, _, delta in events:
if active == 0 and delta == 1:
run_start = pos
active += delta
if active == 0:
result.append([run_start, pos])
return result
import random
random.seed(3)
hand_picked = [
[[1, 4], [4, 5]], # touching intervals
[[5, 8], [1, 3]], # unsorted input
[[2, 5], [1, 10]], # fully nested interval
[[1, 2]], # single interval
[], # empty input
[[5, 6], [1, 2]], # unsorted, non-overlapping
[[1, 3], [2, 6], [8, 10], [15, 18]],
]
mismatches = 0
for tc in hand_picked:
if merge_intervals(tc) != sweep_line_reference(tc):
mismatches += 1
for _ in range(3000):
n = random.randint(1, 6)
intervals = [[a, a + random.randint(0, 5)] for a in (random.randint(0, 15) for _ in range(n))]
if merge_intervals(intervals) != sweep_line_reference(intervals):
mismatches += 1
print(f"7 hand-picked cases + 3000-trial random sweep (seed 3): mismatches = {mismatches}")
Output:
[[1, 6], [8, 10], [15, 18]]
7 hand-picked cases + 3000-trial random sweep (seed 3): mismatches = 0
matching the question's own example exactly: [1,3] and [2,6] overlap (2 <= 3) and merge into [1,6]; [8,10] and [15,18] each start after the previous merged interval's end, so they remain separate. This was additionally cross-checked against the independently-implemented sweep-line reference above (treating each interval as a +1/-1 event at its start/end and rebuilding runs where the event count returns to zero), which is a genuinely different method rather than a second copy of the same merge logic, on 7 hand-picked cases (touching intervals, unsorted input, a fully nested interval, a single interval, empty input, and unsorted non-overlapping intervals) plus a 3,000-trial random sweep (seed 3); the printed line confirms zero mismatches across all of it, giving real cross-validation rather than testing the code against itself.
Trade-offs and pitfalls
The most consequential bug is assigning last[1] = end directly instead of last[1] = max(last[1], end) when merging: this passes every test case where intervals only partially overlap or extend each other, and only fails on a fully nested interval, which is easy to omit from a quick manual test set and then breaks silently in production by shrinking coverage that should have been preserved. A second common bug is skipping the initial sort, either because the candidate assumes input is already given in start order (sample inputs in problem statements are often, misleadingly, already sorted) or forgets that an unsorted input makes a single forward sweep unreliable; always sort explicitly rather than relying on an assumption about input order. Finally, treat the touching-versus-overlapping boundary as a decision to state out loud (<= merges touching intervals, < does not) rather than an arbitrary implementation detail, since which one is correct depends on what the intervals represent.
Longest Consecutive Sequence: Given an unsorted array of integers, implement a Python function that returns the length of the longest sequence of consecutive integers using O(n) time. Explain why a hash set approach works and discuss how this could be used to detect contiguous ID spans in large event logs.
Sample Answer
Direct answer
Put every number into a hash set for O(1) average membership checks, then only start counting a run from numbers that are the START of a run, meaning num - 1 is not in the set. From each such start, walk forward while the next consecutive integer is present, tracking the longest run found. This turns an O(n log n) sort-based approach into O(n) average time, because the set lets you test "is this the start of a run" without looking at the rest of the array.
Structured elaboration
Approach
def longest_consecutive(nums):
num_set = set(nums)
best = 0
for n in num_set:
if (n - 1) not in num_set:
length = 1
while (n + length) in num_set:
length += 1
best = max(best, length)
return best
Why this is O(n), not O(n times the average run length)
The inner while loop only ever runs starting from a number that has no predecessor in the set, that is, the FIRST element of some run. Every other number in that run gets skipped by the outer loop's guard (n - 1 not in num_set is false for them), so the inner loop is never re-entered from the middle of a run it has already walked. Summed across the whole execution, every number in the array is visited by the inner loop's forward walk at most once, across the ENTIRE algorithm, not once per outer-loop iteration; that is what keeps the total work at O(n) despite the code superficially looking like a nested loop.
Application: contiguous ID spans in event logs (the question's explicit ask)
If event or record identifiers are integers assigned in increasing order, but the log has gaps (from filtered-out, dropped, or retried events), this exact technique finds the longest unbroken run of the IDs that DID make it into the log, in one O(n) pass over an unsorted set of IDs, without first sorting the whole log.
Worked example
Executed with python3 s74.py, pinned inputs:
input: [100, 4, 200, 1, 3, 2, 101, 102]
longest_consecutive(nums) = 4
The run 1, 2, 3, 4 has length 4; the run 100, 101, 102 has length 3; 4 is the longer of the two, matching the printed result.
event_ids: [7001, 7002, 7004, 7005, 7006, 7010]
longest contiguous ID span length = 3
The span 7004, 7005, 7006 (length 3) is longer than the span 7001, 7002 (length 2), matching the printed result and directly demonstrating the event-log framing the question asks about.
Trade-offs and pitfalls
- The single most common bug is dropping the
(n - 1) not in num_setguard and letting the inner loop start from every element; that degrades to O(n^2) in the worst case (for example, one long consecutive run), even though the code still looks like "the hash-set version" at a glance. - Duplicate values in the input do not affect correctness (the set removes them), but the returned length measures the run over DISTINCT values; if a caller actually needs to count how many raw events fall in the longest span, including duplicates, this exact function does not do that and needs a small extension.
- If the caller needs the actual start and end of the run for reporting (not just its length, which is what the event-log framing implies you would want in practice), track the start value alongside the length whenever a new best is found.
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.
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.