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 algorithm to find the length of the longest substring that contains at most k distinct characters. Provide a Python sliding window solution that runs in O(n) time for typical alphabets using a hashmap to track counts. Discuss how such a function could be used to analyze language diversity in user-generated content.
Sample Answer
Direct answer
Maintain a window [left, right] and a hash map of character frequencies inside it. Expand right one character at a time, always incrementing that character's count; whenever the map holds more than k distinct keys, shrink from left (decrementing and removing counts that hit zero) until it's back to at most k. Track the best window length seen after each expansion. Because left only ever moves forward and never resets, the whole scan is O(n), not O(n * k) from re-scanning.
Approach
- Two pointers,
leftandright, both starting at 0, plus adictmapping character to its count within the current window. - For each
right, adds[right]to the frequency map. - While the map has more than
kdistinct keys, removes[left]from the count (deleting the key entirely once its count hits 0, so "distinct key count" stays accurate) and advanceleft. - After the shrink step, the window
[left, right]is valid (at most k distinct); updatebest = max(best, right - left + 1). k == 0is a special case: no window can ever be valid except length 0, so short-circuit and return 0.
Complexity
Time: O(n), since left and right each advance at most n times total across the whole scan (amortized O(1) per character, not per window). Space: O(k) for the frequency map (at most k+1 distinct keys are ever held at once, momentarily, before a shrink).
Edge cases
- Empty string or
k == 0: return 0. kgreater than or equal to the number of distinct characters ins: the whole string is the answer.- All characters identical: the whole string is always a valid window regardless of
k(as long ask >= 1).
def longest_substring_k_distinct(s, k):
if k == 0 or not s:
return 0
freq = {}
left = 0
best = 0
for right, ch in enumerate(s):
freq[ch] = freq.get(ch, 0) + 1
while len(freq) > k:
left_ch = s[left]
freq[left_ch] -= 1
if freq[left_ch] == 0:
del freq[left_ch]
left += 1
best = max(best, right - left + 1)
return best
print(longest_substring_k_distinct("eeeeeaaabbbccd", 3))
print(longest_substring_k_distinct("araaci", 2))
print(longest_substring_k_distinct("", 2))
print(longest_substring_k_distinct("abc", 0))
Output:
11
4
0
0
For "eeeeeaaabbbccd" with k=3: the run "eeeeeaaabbb" (the first 11 characters) uses exactly the 3 distinct characters e, a, b; including either c afterward would push distinct-character count to 4, so 11 is correct and matches the printed value. For "araaci" with k=2, the window "araa" (characters a, r) is the longest 2-distinct window, matching the classic reference answer of 4.
If this were being used to gauge "language diversity" in a stream of characters (say, distinct scripts or token categories represented as characters), this same window answers "what's the longest run of content that only mixes at most k categories," which is a reasonable proxy for local diversity, though a real diversity metric would probably want a normalized measure (e.g. distinct-count / window-length) rather than raw longest-run.
Trade-offs and pitfalls
- Deleting keys once their count hits zero is required, not cosmetic: if you just decrement without deleting,
len(freq)will overcount distinct characters that are no longer actually in the window, and the shrink loop will keep running (or stop too early) based on stale keys. - Off-by-one in the length calculation:
right - left + 1, notright - left, since bothleftandrightare inclusive window bounds. - The same one-pass, maintained-invariant window family applies to time-ordered event streams, not just character strings. Given an unordered stream of
(user_id, timestamp)events, you can reconstruct per-user sessions (a session ends when the gap to the next event from that user exceeds a threshold) with an analogous single sweep once the events are sorted: instead of a frequency-count invariant, the invariant is "gap since the last event for this key is within the threshold."
def build_sessions(events, gap_seconds):
sessions_by_user = {}
for user_id, ts in sorted(events):
user_sessions = sessions_by_user.setdefault(user_id, [])
if user_sessions and ts - user_sessions[-1][-1] <= gap_seconds:
user_sessions[-1].append(ts)
else:
user_sessions.append([ts])
return sessions_by_user
events = [
("u1", 100), ("u1", 130), ("u1", 500),
("u2", 90), ("u2", 640),
("u1", 505),
]
print(build_sessions(events, gap_seconds=60))
Output:
{'u1': [[100, 130], [500, 505]], 'u2': [[90], [640]]}
u1's events at 100 and 130 are 30 seconds apart (within the 60-second gap, same session), 500 is 370 seconds after 130 (new session), and 505 is 5 seconds after 500 (same session as 500). u2's events are 550 seconds apart, so each is its own session. Sorting first costs O(n log n); the sweep itself is O(n), so the whole thing is O(n log n), dominated by the sort rather than the windowing logic.
Implement a Python function that finds all unique triplets in the array which gives the sum of zero (3Sum). Example: nums = [-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]]. Aim for O(n^2) time using sorting + two-pointer and discuss how this pattern generalizes to k-sum problems.
Sample Answer
Direct answer
Sort the array, then fix each element in turn as the "anchor" and use a two-pointer scan over the remaining sorted suffix to find pairs that complete the triplet to zero, skipping over duplicate values at every level to avoid duplicate triplets. This runs in O(n^2) time (O(n log n) sort plus an O(n) two-pointer scan for each of n anchors) and O(1) extra space beyond the output and the sort itself. The same anchor-then-two-pointer idea generalizes to k-sum by recursing: fix one more element per level until only two remain, then solve that base case with two pointers.
Algorithm: 3Sum
- Sort
nums. - For each index
i(the anchor), skip it if it's a duplicate of the previous anchor (nums[i] == nums[i-1]), which prevents emitting the same triplet-starting-value twice. - If
nums[i] > 0, stop entirely: since the array is sorted, every remaining element is also non-negative, so no triplet starting here or later can sum to zero (unless all are zero, already handled by the anchor being the smallest of the three). - Two-pointer scan
left = i+1,right = n-1over the sorted suffix: if the three-element sum is 0, record it and advance both pointers past any duplicate values; if the sum is negative, advanceleft(need a larger value); if positive, retreatright(need a smaller value).
def three_sum(nums):
nums = sorted(nums)
n = len(nums)
result = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
if nums[i] > 0:
break
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
result.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return result
Generalizing to k-sum
The pattern is: fix one element, reduce the target by its value, and recurse on k-1 with the remaining sorted suffix, until k == 2, at which point solve with the same two-pointer scan used above (which is really just 3Sum with the anchor already fixed by the outer recursion). Each recursive level still needs the duplicate-skip at its own position to avoid duplicate combinations, and a similar early-exit prune (if the smallest possible sum of the remaining k elements already exceeds the target, or the largest possible sum is already below it, stop).
def k_sum(nums, target, k):
nums = sorted(nums)
def helper(start, k, target):
n = len(nums)
if k == 2:
res = []
left, right = start, n - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
res.append([nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < target:
left += 1
else:
right -= 1
return res
res = []
for i in range(start, n - k + 1):
if i > start and nums[i] == nums[i - 1]:
continue
for sub in helper(i + 1, k - 1, target - nums[i]):
res.append([nums[i]] + sub)
return res
return helper(0, k, target)
This runs in O(n^(k-1)) time: each of the k-2 outer recursive levels contributes a factor of O(n), and the base case two-pointer scan is O(n), for a total of O(n^(k-1)). 3Sum is exactly this generalization with k=3.
Worked example
import itertools
def brute_force_k_sum(nums, target, k):
nums_sorted = sorted(nums)
seen = set()
result = []
for combo_idx in itertools.combinations(range(len(nums_sorted)), k):
combo_vals = tuple(nums_sorted[i] for i in combo_idx)
if sum(combo_vals) == target and combo_vals not in seen:
seen.add(combo_vals)
result.append(list(combo_vals))
return sorted(result)
print(three_sum([-1, 0, 1, 2, -1, -4]))
k_sum_result = k_sum([1, 0, -1, 0, -2, 2], target=0, k=4)
print(k_sum_result)
brute = brute_force_k_sum([1, 0, -1, 0, -2, 2], target=0, k=4)
print("brute-force cross-check:", brute)
print("agree:", sorted(k_sum_result) == brute)
Output (verified by execution, and k_sum's results were independently cross-checked against a brute-force itertools.combinations scan over every k-subset of indices, so agreement is real validation, not the same logic checked twice):
[[-1, -1, 2], [-1, 0, 1]]
[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
brute-force cross-check: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
agree: True
Tracing why [-1, -1, 2] and [-1, 0, 1] are the only two triplets on the sorted input [-4, -1, -1, 0, 1, 2]: anchor -4 (index 0) needs a pair summing to 4 from [-1,-1,0,1,2], and the two-pointer scan finds none (max reachable pair sum here is -1+2=1, which the pointers converge past without hitting 4). Anchor -1 (index 1) needs a pair summing to 1 from [-1,0,1,2]: the scan finds -1 and 2 first (giving [-1,-1,2]), then continues and finds 0 and 1 (giving [-1,0,1]). The next anchor is also -1 (index 2), but it's skipped as a duplicate of index 1's value, which is exactly what prevents [-1,-1,2] (or a duplicate [-1,0,1]) from being emitted twice.
Trade-offs and pitfalls
- The two duplicate-skip lines are the single most error-prone part of this problem. Skipping the anchor's duplicates prevents duplicate triplet-starts; skipping
left/rightduplicates after recording a match prevents duplicate triplet-ends. Missing either one produces a correct set of values but with duplicate entries in the output. - The
nums[i] > 0: breakearly exit is an optimization, not a correctness requirement for 3Sum specifically (target 0): once sorted, a non-negative anchor means the two-pointer scan can never reach a negative-enough sum to cancel it out to zero. For a general k-sum with a nonzero target, this prune needs to be a real bounds check (is the target reachable at all given the remaining sorted suffix's min/max possible sums), not just a sign check. - k-sum's O(n^(k-1)) complexity grows fast: 4Sum is already O(n^3), and this approach stops being practical well before k gets large; for genuinely large k, a hash-map-based approach (precompute all pair sums for k/2 elements when k is even) trades space for a lower time exponent, at the cost of needing to dedupe combinations across the two halves.
- Common wrong turn: using a hash set of
frozensetor sorted tuples to dedupe triplets after generating all of them (including duplicates) via brute force. This works but is O(n^3) or worse and defeats the purpose of the sorted two-pointer approach, which prevents duplicates from being generated in the first place rather than filtering them out afterward.
Implement a CSV parser in Python that correctly handles quoted fields, escaped quotes, and large files by streaming. Do not use Python's csv module; instead implement a state machine that yields parsed rows one at a time. Explain states and how you handle chunked input.
Sample Answer
Direct answer
Model the parser as an explicit state machine with four states (start of field, inside an unquoted field, inside a quoted field, and "just saw a quote while inside a quoted field"), and drive it one character at a time so it can hold its place between calls. That is what makes it work on chunked input: the state and the current partial row live in an object between feed() calls, so a field, a quote, or even a line ending can be split arbitrarily across chunk boundaries without losing correctness.
Structured elaboration
The four states.
FIELD_START: at the start of a field. A"opens a quoted field; anything else starts an unquoted one.UNQUOTED: scanning an unquoted field.,ends the field,\nends the row, a bare\ris swallowed (so both\nand\r\nline endings work, even if the\rand\nland in different chunks).QUOTED: inside a quoted field. Only"is special; comma and newline are ordinary field content here, which is exactly why a naiveline.split(',')cannot handle quoted CSV: a comma or newline inside quotes must not end the field or row.QUOTE_IN_QUOTED: just saw a"while inside a quoted field. The next character decides what that quote meant: another"is the RFC 4180 escaped-quote convention (""inside quotes decodes to one literal"), while,or\ncloses the field or row.
Escaped quotes. The QUOTE_IN_QUOTED state is precisely the escape mechanism: seeing " there means "was that a closing quote or an escaped one," and the answer is read off the very next character.
Streaming input. feed(chunk) iterates the chunk's characters through _feed_char, appends completed rows to an internal buffer, and returns (and clears) that buffer. A trailing finish() call flushes a final row that has no terminating newline. A generator, parse_csv_stream(chunks), wraps this so a caller can iterate rows directly over file.read(65536)-sized chunks without ever holding the whole file, or even a whole row beyond the one currently being assembled, in memory.
Worked example
class CSVStateMachine:
FIELD_START, UNQUOTED, QUOTED, QUOTE_IN_QUOTED = range(4)
def __init__(self):
self.state = self.FIELD_START
self.field_chars = []
self.row = []
self._rows_ready = []
def feed(self, chunk: str):
for ch in chunk:
self._feed_char(ch)
out, self._rows_ready = self._rows_ready, []
return out
def finish(self):
if self.field_chars or self.row:
self._end_row()
out, self._rows_ready = self._rows_ready, []
return out
def _end_field(self):
self.row.append(''.join(self.field_chars))
self.field_chars = []
def _end_row(self):
self._end_field()
self._rows_ready.append(self.row)
self.row = []
self.state = self.FIELD_START
def _feed_char(self, ch):
s = self.state
if s == self.FIELD_START:
if ch == '"':
self.state = self.QUOTED
elif ch == ',':
self._end_field()
elif ch == '\n':
self._end_row()
elif ch == '\r':
pass
else:
self.field_chars.append(ch)
self.state = self.UNQUOTED
elif s == self.UNQUOTED:
if ch == ',':
self._end_field(); self.state = self.FIELD_START
elif ch == '\n':
self._end_row()
elif ch == '\r':
pass
else:
self.field_chars.append(ch)
elif s == self.QUOTED:
if ch == '"':
self.state = self.QUOTE_IN_QUOTED
else:
self.field_chars.append(ch)
elif s == self.QUOTE_IN_QUOTED:
if ch == '"':
self.field_chars.append('"'); self.state = self.QUOTED
elif ch == ',':
self._end_field(); self.state = self.FIELD_START
elif ch == '\n':
self._end_row()
elif ch == '\r':
pass
else:
self.field_chars.append(ch); self.state = self.UNQUOTED
def parse_csv_stream(chunk_iterable):
machine = CSVStateMachine()
for chunk in chunk_iterable:
for row in machine.feed(chunk):
yield row
for row in machine.finish():
yield row
test_input = (
"id,name,note\r\n"
"1,\"Smith, John\",\"Said \"\"hello\"\" today\"\r\n"
"2,\"multi\nline note\",plain\r\n"
"3,noquotes,last row no newline"
)
whole = list(parse_csv_stream([test_input]))
for row in whole:
print(row)
lengths = [5, 1, 16, 1, 1, 16, 15, 15, 1, 40]
chunks, idx = [], 0
for L in lengths:
chunks.append(test_input[idx:idx + L])
idx += L
chunked = list(parse_csv_stream(chunks))
for row in chunked:
print(row)
print("chunked parse matches whole-input parse:", chunked == whole)
Test input (CRLF endings, a quoted field with an embedded comma, a quoted field with an embedded escaped quote, a quoted field with an embedded newline, and a final row with no trailing newline):
id,name,note\r\n
1,"Smith, John","Said ""hello"" today"\r\n
2,"multi\nline note",plain\r\n
3,noquotes,last row no newline
Parsed whole, in one shot:
['id', 'name', 'note']
['1', 'Smith, John', 'Said "hello" today']
['2', 'multi\nline note', 'plain']
['3', 'noquotes', 'last row no newline']
Then the exact same text was cut into 10 deliberately awkward chunks (lengths [5, 1, 16, 1, 1, 16, 15, 15, 1, 40]), with boundaries landing mid-quoted-field, mid-escaped-quote, and mid-CRLF, and streamed through parse_csv_stream:
['id', 'name', 'note']
['1', 'Smith, John', 'Said "hello" today']
['2', 'multi\nline note', 'plain']
['3', 'noquotes', 'last row no newline']
chunked parse matches whole-input parse: True
The chunked result is character-for-character identical to the whole-input parse, which is the actual proof the state machine (not just the happy-path parse) is correct: if the state were not preserved correctly across feed() calls, at least one of those adversarial cut points would have corrupted a field.
Trade-offs and pitfalls
The single most common bug in a hand-rolled version of this: constructing a new parser instance per chunk instead of reusing one across feed() calls. That silently forgets which state (and which partial field) was in progress, and any chunk boundary landing inside a quoted field, an escaped quote, or a CRLF pair would be mis-parsed without raising any error, it would just produce wrong rows.
Memory footprint is bounded by the longest single field, not by file size, since only the current row's partial content is held between chunks, which is the entire point of doing this as a streaming state machine instead of reading the whole file into one big string first.
This hand-rolled parser is a demonstration of the state-machine technique, not a drop-in CSV library: it does not detect or strip a UTF-8 byte-order mark, does not validate that every row has the same column count as the header, and does not handle encodings other than already-decoded Unicode text. In real production code, reach for a maintained CSV library; this exercise is about the parsing technique the interviewer is actually checking.
Implement basic run-length encoding (RLE) for compressing simple log sequences. Given a string s of characters, return its RLE as counts followed by the character (e.g., 'aaabcc' -> '3a1b2c'). Provide a Python function rle_encode(s: str) -> str and rle_decode(encoded: str) -> str. State time/space complexity and where this is useful in ETL.
Sample Answer
Direct answer
Scan the string once, counting how long each run of an identical character is, and emit that count followed immediately by the character ('aaabcc' becomes '3a1b2c'). Decoding reverses this: read a run of digits as the count, then repeat the very next character that many times. Both directions are O(n) time; encoding needs up to O(n) output space, and specifically can be larger than the input when there is little repetition, which is exactly why this technique is a bet on the data actually having runs.
Structured elaboration
Encoding. Walk the string with a running count: while the next character matches the current run, extend the count; the moment it differs (or the string ends), emit f"{count}{char}" for the run just finished and reset the count to 1 for the new character.
Decoding. Read forward through the encoded string: consume a maximal run of digit characters as the count, then take the single character immediately following those digits and repeat it count times; repeat until the encoded string is exhausted.
Where this fits in an ETL (extract, transform, load) context. Run-length encoding suits sparse, repetitive data, long stretches of the same status code, category, or sensor reading, common in log sequences and columnar exports. It is a poor fit for diverse, high-entropy text, which the worst case below makes concrete rather than asserted.
Worked example
def rle_encode(s: str) -> str:
if not s:
return ""
result = []
count = 1
for i in range(1, len(s) + 1):
if i < len(s) and s[i] == s[i - 1]:
count += 1
else:
result.append(f"{count}{s[i - 1]}")
count = 1
return ''.join(result)
def rle_decode(encoded: str) -> str:
result = []
i, n = 0, len(encoded)
while i < n:
j = i
while j < n and encoded[j].isdigit():
j += 1
count = int(encoded[i:j])
char = encoded[j]
result.append(char * count)
i = j + 1
return ''.join(result)
print(f"rle_encode('aaabcc') = {rle_encode('aaabcc')!r}")
print(f"rle_decode('3a1b2c') = {rle_decode('3a1b2c')!r}")
print()
for t in ["", "a", "aaaaaaaaaa", "abcdef", "aabbccddeeff", "zzzzzzzzzzzzzzzz"]:
enc = rle_encode(t)
dec = rle_decode(enc)
print(f"{t!r} -> {enc!r} -> {dec!r} roundtrip_ok={dec == t}")
print()
worst = "abcdefgh"
enc = rle_encode(worst)
print(f"worst case, no repeats: {worst!r} (len {len(worst)}) -> {enc!r} (len {len(enc)})")
Output:
rle_encode('aaabcc') = '3a1b2c'
rle_decode('3a1b2c') = 'aaabcc'
'' -> '' -> '' roundtrip_ok=True
'a' -> '1a' -> 'a' roundtrip_ok=True
'aaaaaaaaaa' -> '10a' -> 'aaaaaaaaaa' roundtrip_ok=True
'abcdef' -> '1a1b1c1d1e1f' -> 'abcdef' roundtrip_ok=True
'aabbccddeeff' -> '2a2b2c2d2e2f' -> 'aabbccddeeff' roundtrip_ok=True
'zzzzzzzzzzzzzzzz' -> '16z' -> 'zzzzzzzzzzzzzzzz' roundtrip_ok=True
worst case, no repeats: 'abcdefgh' (len 8) -> '1a1b1c1d1e1f1g1h' (len 16)
rle_encode('aaabcc') produces '3a1b2c' exactly as given in the question, and rle_decode recovers the original from it. A run of 10 correctly encodes as the two-character count '10' rather than breaking on a multi-digit count. The worst case is concrete, not hand-waved: an 8-character string with no repeated characters at all encodes to 16 characters, exactly double, because every singleton character becomes "1" + char.
Trade-offs and pitfalls
The worst-case doubling above means this should never be applied blindly. Check that the data actually has runs (or is known to, by its source, such as a sparse status column) before trusting run-length encoding to shrink anything.
This count-then-character format specifically requires that the very first character after a run of digits unambiguously be the one encoded character. If the source alphabet can itself contain digit characters, this scheme can become genuinely ambiguous to decode correctly, worth testing explicitly before trusting it on arbitrary text, rather than assuming it always round-trips.
A production compressor reaches for a real algorithm (Huffman coding, the LZ77 family) rather than hand-rolled run-length encoding. Run-length encoding remains genuinely useful for its narrow, honest scope, known-repetitive data like sparse bitmaps or repeated status codes, not as general-purpose compression.
Implement in Python a function that finds the maximum average subarray of length k in an array of floats. While coding, narrate each step, state assumptions, discuss time and space complexity, and walk through one example including k > n and negative numbers. Provide the implementation and explanation.
Sample Answer
Direct answer
Slide a fixed-size window of length k across the array, maintaining a running SUM (add the element entering the window, subtract the one leaving), track the best sum seen, and divide by k exactly once at the end. Treat k > n as an explicit invalid-input error rather than guessing a fallback, since no window of that length exists. The time complexity is O(n) and the space complexity is O(1) extra.
Structured elaboration, narrated step by step
- State the assumption up front.
kmust satisfy1 <= k <= n; ifk > n, there is no valid window, so raise explicitly rather than returning something like the whole-array average (which would silently answer a DIFFERENT question than the one asked). - Seed the window. Compute the sum of the first
kelements directly; this is the sum for the window starting at index 0. - Slide. For each subsequent starting position, update the running sum in
O(1): add the element newly entering the window on the right, subtract the element leaving on the left (window_sum += nums[i] - nums[i - k]). This avoids recomputing a fresh sum ofkelements for every window, which is what makes the whole scanO(n)instead ofO(n*k). - Track the best. Compare each window's sum (not yet divided) against the running best sum.
- Divide once, at the end. Return
best_sum / kafter the loop finishes, rather than dividing inside the loop on every step; the comparison of sums doesn't need the division at all, since dividing by the same constantknever changes which sum is largest. - All-negative arrays. The algorithm needs no special case here: the "best" window sum is still correctly the LEAST negative one, exactly analogous to the Kadane's-initialization trap, since nothing in this loop clamps the result toward 0.
Worked example
def max_average_subarray(nums, k):
n = len(nums)
if k <= 0:
raise ValueError("max_average_subarray: k must be positive")
if k > n:
raise ValueError(f"max_average_subarray: k={k} exceeds array length n={n}")
window_sum = sum(nums[:k])
best_sum = window_sum
for i in range(k, n):
window_sum += nums[i] - nums[i - k]
if window_sum > best_sum:
best_sum = window_sum
return best_sum / k
def max_average_subarray_brute_force(nums, k):
n = len(nums)
best = sum(nums[:k]) / k
for i in range(1, n - k + 1):
avg = sum(nums[i:i + k]) / k
if avg > best:
best = avg
return best
cases = [
([1.0, 12.0, -5.0, -6.0, 50.0, 3.0], 4),
([-1.0, -2.0, -3.0, -4.0], 2),
([5.0], 1),
]
for nums, k in cases:
result = max_average_subarray(nums, k)
brute = max_average_subarray_brute_force(nums, k)
print(f"nums={nums}, k={k} -> max_average={result}")
assert abs(result - brute) < 1e-9
try:
max_average_subarray([1.0, 2.0, 3.0], 5)
except ValueError as e:
print(f"k > n raised ValueError as expected: {e}")
print("brute-force cross-check passed for all cases")
Output (executed, python3 s70_max_avg_subarray.py, cross-checked against a brute-force O(n*k) implementation for every case):
nums=[1.0, 12.0, -5.0, -6.0, 50.0, 3.0], k=4 -> max_average=12.75
nums=[-1.0, -2.0, -3.0, -4.0], k=2 -> max_average=-1.5
nums=[5.0], k=1 -> max_average=5.0
k > n raised ValueError as expected: max_average_subarray: k=5 exceeds array length n=3
brute-force cross-check passed for all cases
The all-negative case correctly reports -1.5 (the window [-1.0, -2.0], the least-bad pair), not 0 or an unclamped positive value, and the k > n case raises with a message naming both the offending k and the actual array length rather than failing somewhere less informative.
Trade-offs & pitfalls
- All-negative arrays. As with Kadane's, don't clamp the result toward
0; the least-negative window average is the CORRECT answer, and a version seeded withbest_sum = 0would silently and wrongly prefer an empty or zero-sum comparison over the true (negative) best. - Dividing inside the loop on every step, instead of once at the end, is unnecessary floating-point work and a common code-review nit, though not a correctness bug at this scale; it also makes the "compare sums directly" optimization harder to see.
- At scale, the same technique underlies real trailing-moving-average code, for example computing a moving average of per-second request counts for rate-limiting or monitoring: the array becomes a live counter rather than a stored list, but the sliding-sum idea is identical. A Go port of that framing would typically keep the running sum as an integer type (e.g.
int64, since request counts are naturally integers, and to avoid float accumulation error over a long-running process) and convert tofloat64only at the final division, exactly mirroring the "divide once, at the end" principle above; it would also express thek > ncheck as an explicit returnederrorvalue rather than a raised exception, matching Go's idiomatic error-handling convention instead of Python's. - A vectorized (numpy) equivalent trades the explicit Python loop for a cumulative-sum array and slicing, which is the same
O(n)asymptotic work but with a much smaller constant factor in practice, useful once the array is large enough that Python's own per-iteration interpreter overhead dominates:
import numpy as np
def max_average_subarray_numpy(nums, k):
arr = np.asarray(nums, dtype=float)
n = arr.shape[0]
if k <= 0 or k > n:
raise ValueError(f"max_average_subarray_numpy: invalid k={k} for n={n}")
csum = np.cumsum(arr)
window_sums = np.empty(n - k + 1)
window_sums[0] = csum[k - 1]
window_sums[1:] = csum[k:] - csum[:-k]
return float(window_sums.max() / k)
cases = [
([1.0, 12.0, -5.0, -6.0, 50.0, 3.0], 4),
([-1.0, -2.0, -3.0, -4.0], 2),
([5.0], 1),
]
for nums, k in cases:
loop_result = max_average_subarray(nums, k)
numpy_result = max_average_subarray_numpy(nums, k)
print(f"nums={nums}, k={k} -> loop={loop_result}, numpy={numpy_result}, match={abs(loop_result - numpy_result) < 1e-9}")
assert abs(loop_result - numpy_result) < 1e-9
print("numpy variant agrees with the loop-based version to within 1e-9 for all three cases")
Output (executed, continuing in the same session as the loop-based version above):
nums=[1.0, 12.0, -5.0, -6.0, 50.0, 3.0], k=4 -> loop=12.75, numpy=12.75, match=True
nums=[-1.0, -2.0, -3.0, -4.0], k=2 -> loop=-1.5, numpy=-1.5, match=True
nums=[5.0], k=1 -> loop=5.0, numpy=5.0, match=True
numpy variant agrees with the loop-based version to within 1e-9 for all three cases
The numpy variant agrees with the loop-based version to within 1e-9 for all three cases, confirmed by the explicit comparison above rather than asserted.
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.