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 minCut(s) in Python that returns the minimum number of cuts needed to partition string s so that every substring is a palindrome. Provide an O(n^2) time solution by precomputing palindrome table and using dynamic programming to compute minimum cuts, and discuss optimizations to reduce constant factors and memory footprint.
Sample Answer
Direct answer
First precompute, for every substring s[i..j], whether it is a palindrome, by dynamic programming over increasing substring length (a substring is a palindrome if its two endpoints match and the substring strictly inside it is also a palindrome). Then run a second dynamic-programming pass where cut[i] is the minimum number of cuts needed to partition the prefix s[0..i] into palindromic pieces, trying every valid palindrome ending exactly at i as the final piece.
Structured elaboration
Step 1: the palindrome table
def build_palindrome_table(s):
n = len(s)
is_pal = [[False] * n for _ in range(n)]
for i in range(n):
is_pal[i][i] = True
for length in range(2, n + 1):
for i in range(0, n - length + 1):
j = i + length - 1
if s[i] == s[j]:
is_pal[i][j] = (length == 2) or is_pal[i + 1][j - 1]
return is_pal
Filling by increasing length guarantees that whenever is_pal[i + 1][j - 1] is read, it was already computed on an earlier iteration (a shorter substring), which is exactly why this fill order is required rather than incidental.
Step 2: minimum cuts
def min_cut(s):
n = len(s)
if n <= 1:
return 0
is_pal = build_palindrome_table(s)
cut = [0] * n
for i in range(n):
if is_pal[0][i]:
cut[i] = 0
continue
best = i
for j in range(1, i + 1):
if is_pal[j][i]:
best = min(best, cut[j - 1] + 1)
cut[i] = best
return cut[n - 1]
Total cost: O(n^2) time (the palindrome table fill and the cut computation are each bounded by the number of (i, j) pairs), O(n^2) space for the table plus O(n) for the cut array, matching what the question asks for.
Optimizations to reduce constant factors AND memory footprint (both parts of the question's explicit ask)
- Constant factor: pack each row of the boolean palindrome table into a single machine integer used as a bitset, one bit per column, instead of a Python list of booleans. Membership becomes a bit shift and mask instead of a list index and a full Python object lookup, and the table's memory footprint drops substantially since a machine integer packs many booleans per word, with identical asymptotic behavior:
def min_cut_bitset(s):
"""Same DP as min_cut, but each row of the palindrome table is packed
into a single Python int bitset (bit j of rows[i] set iff s[i..j] is a
palindrome) instead of a list of booleans."""
n = len(s)
if n <= 1:
return 0
rows = [1 << i for i in range(n)]
for length in range(2, n + 1):
for i in range(0, n - length + 1):
j = i + length - 1
if s[i] == s[j] and (length == 2 or (rows[i + 1] >> (j - 1)) & 1):
rows[i] |= (1 << j)
cut = [0] * n
for i in range(n):
if (rows[0] >> i) & 1:
cut[i] = 0
continue
best = i
for j in range(1, i + 1):
if (rows[j] >> i) & 1:
best = min(best, cut[j - 1] + 1)
cut[i] = best
return cut[n - 1]
I cross-checked this bitset-packed version against the plain version above; both are exercised together in the worked example below.
- Memory footprint: the
cutarray itself already only needs O(n) space, one integer per prefix length; the O(n^2) memory lives entirely in the palindrome table. If memory, not time, is the binding constraint, one option is to recompute "iss[j..i]a palindrome" on demand via a direct two-pointer character comparison instead of storing the full table, trading a higher constant-factor time cost (each on-demand check costs up to O(n) rather than O(1) table lookup) for O(1) extra space beyond the output. This is a genuine time-for-space trade, not a free win, and is only worthwhile once the O(n^2) table itself is the actual bottleneck resource for the input sizes involved.
Worked example
Executed with python3 s79.py (defining both min_cut and min_cut_bitset above), the plain and bitset-packed versions run on five pinned strings and cross-checked:
min_cut('aab' ) = 1 bitset_packed=1 agree=True
min_cut('a' ) = 0 bitset_packed=0 agree=True
min_cut('ab' ) = 1 bitset_packed=1 agree=True
min_cut('racecarxyzracecar' ) = 4 bitset_packed=4 agree=True
min_cut('aabbc' ) = 2 bitset_packed=2 agree=True
'aab' needs exactly 1 cut: split into 'aa' and 'b', both palindromes, using the minimum possible number of cuts (0 cuts would require the whole string to already be a palindrome, which 'aab' is not).
Trade-offs and pitfalls
- The O(n^2) palindrome table is unavoidable in this straightforward DP formulation; genuinely reducing the worst-case time below O(n^2) requires fundamentally different machinery for palindrome detection that belongs to a different topic's territory, not a small tweak to this approach.
- A common bug: filling
is_pal[i][j]usingis_pal[i + 1][j - 1]before that entry has actually been computed. The length-ordered fill above exists specifically to prevent this; iterating by row or column index instead of substring length silently reads stale (defaultFalse) values and produces wrong results for longer palindromes. - Off-by-one in the cut recurrence: forgetting the base case where
s[0..i]is itself a palindrome (0 cuts needed) is an easy miss, distinct from the general "minimize over every valid split pointj" loop, and produces an answer that is too high by exactly one in cases where the whole prefix needs no cut at all.
Explain how finding a subarray with a given sum differs for arrays with all positive numbers vs arrays that may contain negative numbers. For each case, describe the algorithm and core data structure you would use and explain why the approaches differ in complexity or correctness.
Sample Answer
Direct answer
With all-positive numbers, use the two-pointer sliding window: because every element is positive, extending the window can only increase its sum and shrinking it can only decrease it, so "shrink from the left whenever the sum is too big" is always a safe move, giving O(n) time and O(1) extra space. Once negative numbers are allowed that guarantee disappears entirely: a window you shrank because its sum got too big can later need to be that size again after passing through a negative number, so a fixed two-pointer sweep can permanently miss a subarray that actually sums to the target. The general-case fix is a prefix sum tracked in a hash map, which is O(n) time but needs O(n) space, and that extra space is the direct cost of correctness once the array can decrease.
Structured elaboration
All-positive case: two-pointer sliding window. Maintain left and right indices and a running window_sum. Advance right one step at a time, adding to window_sum; whenever window_sum exceeds the target, advance left (subtracting from window_sum) until it no longer does. Core data structure: just two integer indices and a running total, no auxiliary structure at all, which is what makes this O(1) extra space. Correctness depends entirely on positivity: since removing an element from the window can only shrink the sum and adding one can only grow it, the window's sum behaves monotonically as the pointers move, so there is never an ambiguous case where shrinking might have been the wrong call.
General case (negatives allowed): prefix sum plus hash map. Maintain a running prefix sum as you scan once, left to right. At each index, check whether running_prefix_sum - target has already occurred as an earlier prefix sum; if it has, the subarray between that earlier point and the current index sums to exactly the target, because prefix[i] - prefix[j] equals the sum of the subarray from j+1 to i. Core data structure: a hash map from a prefix-sum VALUE to the earliest index at which it occurred (seeded with {0: -1} to handle a matching subarray that starts at index 0). This turns an otherwise O(n^2) all-pairs check (try every start and end) into O(n), because the hash map gives average O(1) lookup for "has the value I need already been seen."
Why complexity and correctness differ between the two. The positive-only technique is O(n) time and O(1) space precisely because it exploits monotonicity to avoid remembering anything except the current window's running sum. That is a correctness-dependent shortcut, not a generally-true property of subarray-sum problems: it is only safe because positivity guarantees the window's sum moves in one direction as each pointer moves. The hash-map technique never relied on that guarantee in the first place; it works by exact bookkeeping of every prefix sum ever seen, which is why it costs O(n) space rather than O(1). Applying the sliding-window shrink logic to an array with negatives does not raise an error or crash, it silently returns "no subarray found" or the wrong subarray, which is a more dangerous failure mode than a crash because there is no signal that anything went wrong.
Worked example
def find_subarray_sum_sliding_window(nums, target):
left = 0
window_sum = 0
for right in range(len(nums)):
window_sum += nums[right]
while window_sum > target and left <= right:
window_sum -= nums[left]
left += 1
if window_sum == target:
return (left, right)
return None
def find_subarray_sum_prefix_hashmap(nums, target):
seen = {0: -1}
running = 0
for i, x in enumerate(nums):
running += x
if (running - target) in seen:
j = seen[running - target]
return (j + 1, i)
if running not in seen:
seen[running] = i
return None
# All-positive: sliding window works
pos_nums = [2, 1, 5, 3, 2]
print(find_subarray_sum_sliding_window(pos_nums, 9)) # (1, 3) -> subarray [1, 5, 3], sum 9
# With a negative: the positive-only sliding window MISSES a subarray that exists
neg_nums = [4, -3, 5, 2]
target = 1 # subarray [4, -3] sums to 1
print(find_subarray_sum_sliding_window(neg_nums, target)) # None (misses it)
print(find_subarray_sum_prefix_hashmap(neg_nums, target)) # (0, 1) -> [4, -3], sum 1
Output:
(1, 3)
None
(0, 1)
The neg_nums case is a small, hand-constructed counterexample: pick a first element large enough that the window is forced to shrink away from index 0 before a compensating negative number arrives. Tracing the window's own logic confirms why: at right=0 the sum (4) exceeds the target and the window immediately shrinks past index 0 before the negative number at index 1 arrives, so left never revisits index 0 again, permanently losing that candidate.
Trade-offs and pitfalls
The most common wrong turn is applying the sliding-window shrink loop to a general array "because it looks like the same problem," without first checking whether the positivity precondition actually holds; as shown above this produces a wrong answer with no error, which is worse than a crash because it gives no signal that anything is off. A senior answer should name the precondition (a monotonic running sum) explicitly before reaching for the two-pointer technique, and should treat the move to prefix-sum-plus-hash-map as a different technique built on a different invariant, not "the same algorithm made harder." A related pitfall on the hash-map side is forgetting to seed the map with {0: -1}, which silently drops the case where the matching subarray starts at index 0. Finally, if the actual ask were to COUNT every subarray summing to the target rather than find one, the hash-map approach generalizes cleanly (map prefix-sum to a running count, accumulate instead of short-circuiting on first match), while the positive-only two-pointer approach needs a different bookkeeping detail (for each right, add right - left + 1 whenever window_sum equals target after shrinking) to count all valid windows ending there rather than stopping at the first; naming that distinction explicitly is a strong signal of depth beyond the base existence-only framing.
Implement remove_element(nums, val) in-place in Python or Java: remove all occurrences of val from nums and return the new length. This is part of a backend cleanup job where payload arrays must be compacted before storage. Explain how to move elements and whether order must be preserved.
Sample Answer
Direct answer
Use a read/write two-pointer: walk the array once with a read index, and every time you see a value that isn't val, copy it into the next open slot tracked by a write index. The write index at the end is the new length. Whether order must be preserved decides which of two variants you use: the read/write copy above preserves the original relative order in O(n) writes; if order doesn't matter, you can instead swap a matching element with the current last element and shrink the array, which does fewer writes when val is rare.
Approach
- Order-preserving (read/write two-pointer):
writestarts at 0. For eachreadindex in order, ifnums[read] != val, copy it tonums[write]and advancewrite. Every kept element lands in its original relative order, one slot earlier than or at its original position. - Order-not-preserved (swap-with-last): keep a shrinking logical length
n. Whennums[i] == val, overwrite it withnums[n-1](the current last element) and shrinknby one, without advancingi(the swapped-in element still needs to be checked). Whennums[i] != val, advancei. This does one write per removal instead of potentially shifting every later element, which is cheaper when matches are rare and scattered. - Both mutate
numsin place and return the new length; elements at or past the returned length are not meaningfully defined afterward.
Complexity
Both variants: O(n) time (single pass), O(1) extra space. The order-preserving version always does one write per surviving element; the swap variant does one write per removed element, which is fewer when val is rare.
Edge cases
valnot present at all: every element is kept, new length equals original length, zero writes beyond the initial pass.- All elements equal
val: new length is 0. - Empty input: returns 0 immediately.
def remove_element(nums, val):
write = 0
for read in range(len(nums)):
if nums[read] != val:
nums[write] = nums[read]
write += 1
del nums[write:]
return write
def remove_element_unordered(nums, val):
i = 0
n = len(nums)
while i < n:
if nums[i] == val:
n -= 1
nums[i] = nums[n]
else:
i += 1
del nums[n:]
return n
payload = [4, 2, 5, 2, 7, 2, 9]
k = remove_element(payload, 2)
print(k, payload)
payload2 = [4, 2, 5, 2, 7, 2, 9]
k2 = remove_element_unordered(payload2, 2)
print(k2, payload2)
Output:
4 [4, 5, 7, 9]
4 [4, 9, 5, 7]
Both agree on the count (4 surviving elements), but the surviving values land in different positions: [4, 5, 7, 9] keeps the original left-to-right order, while [4, 9, 5, 7] does not (9 moved from the end into an earlier slot during a swap), which is exactly the trade-off the question is asking about.
Trade-offs and pitfalls
- A common bug: using
list.remove(val)or deleting elements from the middle of the array inside a loop, which is O(n) per removal (everything after the deletion point shifts down), making the whole operation O(n^2) in the worst case, and it also skips the next element if you don't adjust the loop index after a deletion. The two-pointer approaches here avoid both problems. - The same read/write two-pointer technique applies directly to low-level, fixed-size buffers, not just Python lists. In C, given a null-terminated
char *s, removing all space characters in place is the identical idea: a write index and a read index both walk the buffer, the write index only advances when the current character should be kept, and a null terminator is placed at the final write position. There's no list-resize step (del nums[write:]) because a C string doesn't carry a separate length field the way a Python list does; the null terminator is the length. - Backend-cleanup framing from the question: "compacting payload arrays before storage" is exactly the order-preserving case if the array represents an ordered sequence (e.g. a time-ordered log) where reordering would corrupt meaning, or the order-not-preserved case if it's an unordered set of records where minimizing writes matters more than position.
Given an array of non-negative integers representing per-minute event counts, implement in Python a data structure that builds prefix sums in O(n) time and answers range sum queries (inclusive) in O(1) time. Also describe how to support efficient incremental updates when new events arrive in a streaming fashion and how to support time-windowed queries (e.g., last 60 minutes).
Sample Answer
Direct answer
Precompute a running-total array prefix where prefix[i] is the sum of the first i counts, built once in O(n). Any inclusive range sum [left, right] is then prefix[right + 1] - prefix[left], O(1). When a new minute of events arrives, append one new prefix entry (last + new_count) in O(1) rather than recomputing anything. A "last W minutes" query is just a range-sum query where the range is derived from the current length, so it reuses the same O(1) machinery.
Approach
- Build:
prefix = [0]; for each count in order, appendprefix[-1] + count.prefixhas n+1 entries so thatprefix[0] = 0represents "the sum of zero elements," letting the range-sum formula work uniformly even for a range starting at index 0. - Range query
[left, right]inclusive:prefix[right + 1] - prefix[left]. This is O(1) regardless of range width, because the two boundary lookups already encode the running total up to each endpoint. - Streaming update: appending a new minute's count is
prefix.append(prefix[-1] + new_count), O(1) amortized (Python list append), since it only ever adds one new entry using the existing last total; nothing earlier inprefixneeds to change. This is what makes the update efficiently incremental: each new event only costs one addition, never a recomputation of the whole array. - Windowed query ("last W minutes"): since the array is indexed one entry per minute in arrival order, the last W minutes are just the range
[n - W, n - 1](clamped to 0 if W exceeds the history length), so this reuses the same O(1) range-sum formula directly.
Complexity
Build: O(n) time, O(n) space for the prefix array. Range query: O(1). Streaming append: O(1) amortized. Windowed query: O(1), same as any other range query, because the window boundary is derivable directly from the current array length.
Edge cases
- Windowed query wider than the history so far (e.g. asking for the last 60 minutes when only 5 minutes of data exist): clamp the left boundary to 0 rather than going negative, returning the sum of everything available.
- Zero-length range (
left == right + 1, i.e. querying an empty window): returns 0 correctly, sinceprefix[right+1] - prefix[left]collapses toprefix[left] - prefix[left].
class MinuteEventCounter:
def __init__(self, counts):
self.prefix = [0]
for c in counts:
self.prefix.append(self.prefix[-1] + c)
def range_sum(self, left, right):
return self.prefix[right + 1] - self.prefix[left]
def append(self, count):
self.prefix.append(self.prefix[-1] + count)
def last_window_sum(self, window_minutes):
n = len(self.prefix) - 1
left = max(0, n - window_minutes)
return self.range_sum(left, n - 1)
counts = [10, 0, 5, 20, 3]
counter = MinuteEventCounter(counts)
print(counter.range_sum(0, 4))
print(counter.range_sum(2, 3))
counter.append(7)
print(counter.range_sum(0, 5))
print(counter.last_window_sum(3))
print(counter.last_window_sum(60))
Output:
38
25
45
30
45
Five minutes of counts [10, 0, 5, 20, 3] sum to 38 overall, and minutes 2-3 (5 + 20) sum to 25, both matching the range-sum formula directly. After a sixth minute (7 events) streams in, the full six-minute sum is 45. The last-3-minutes window covers minutes 3, 4, 5 (20 + 3 + 7 = 30); asking for a 60-minute window when only 6 minutes of history exist correctly clamps to the whole history's sum, 45.
Trade-offs and pitfalls
- This O(1)-per-minute update relies on the array being indexed one entry per minute, in order, with no gaps (exactly the shape given in the question). If events instead arrived with irregular or sparse timestamps (not one guaranteed entry per minute) and a windowed query meant "events from timestamp T-60min to now" rather than "the last 60 array slots," you would need to look up the index corresponding to a given timestamp first, which is a binary search over a parallel timestamps array (O(log n)), not O(1); the O(1) windowed-query property here is a direct consequence of the question's stated per-minute indexing, not something that survives arbitrary timestamp irregularity for free.
- Prefix sums do not support efficient updates to a value that has already been counted (e.g. correcting minute 2's count after the fact): that would require rebuilding every later prefix entry (O(n)) with this simple array, whereas a Fenwick tree (binary indexed tree) supports both point updates and prefix queries in O(log n) each, at the cost of noticeably more implementation complexity than this straight prefix array. For a purely append-only stream (as asked here), the simple array is the right level of machinery; reach for a Fenwick tree only once in-place corrections to historical counts become a real requirement.
- Memory grows without bound on an infinite append-only stream: since every new minute keeps a running prefix entry forever, a long-lived service would eventually want to either cap the retained history (e.g. only keep the last 24 hours of prefix entries, discarding older ones once no query can reference them) or periodically "re-base" by dropping fully-expired history and adjusting subsequent range-sum math accordingly.
Given extremely long input delivered as a character stream in the browser, design a memory-efficient algorithm to find the longest substring without repeating characters seen so far (streaming longest-unique-substring). Discuss state you must keep, when you can evict old state, and whether exact answers are possible without storing the entire stream.
Sample Answer
Direct answer
Yes, an exact answer is possible without ever storing the whole stream: track, per character, the index it was last seen and the current window's start, exactly like the batch sliding-window algorithm, and update a running best length as you go. The key realization is that the state you need is bounded by the number of distinct characters that can appear inside a single window, not by how much of the stream you have already consumed.
Structured elaboration
What state you actually need
Two pieces of state carry all the information required for correctness: a map from character to its last-seen index, and the current window's start index (plus a running maximum length). You do not need to keep the characters themselves once they are behind the window, and you do not need to keep any information about characters that fell out of the window before the current run even started, because they cannot affect a length computed against the current start.
When you can evict old state
An entry in the last-seen map only matters while its recorded index is still inside the current window, that is, last_seen[ch] >= window_start. Once the window start advances past that index, either through natural growth or because that same character reappeared and forced a jump, the old entry becomes irrelevant. You can either check the index against window_start on every lookup and treat a stale entry as "not currently in the window" (the simple approach, and the one used in the batch algorithm too), or actively delete entries whose index falls behind window_start, trading a small amount of extra bookkeeping for a strictly bounded map size at every instant. Either way, nothing in the map ever needs to survive longer than one window's worth of characters.
Whether exact answers are possible without storing the entire stream
Yes, and this is the part that surprises people who assume "streaming" implies "approximate." The reason it works is that a valid answer at any point in the stream only depends on the current no-repeat window, and that window's length is bounded above by the number of distinct characters possible: for a fixed alphabet like ASCII (the standard 128-character text encoding), at most 128 or 256; for Unicode, bounded by however many distinct characters the stream actually contains within one window, in practice small relative to stream length. So the memory footprint is O(min(current window size, alphabet size)), which does not grow as the total stream length grows, unlike a naive approach that stores every character seen so far.
What genuinely does not carry over
The one thing you permanently lose by not storing the whole stream is the ability to reconstruct the actual best substring's TEXT after the fact if you did not also retain a copy of it when it was the current best. If you only need the best LENGTH, you never need the text. If you need the winning substring itself, you additionally need to snapshot it (or its start and end indices, plus the ability to look them up later) at the moment it becomes the new best, which costs a bit more memory but still nothing close to the size of the whole stream.
Worked example
def streaming_longest_unique(stream_chars):
'''One character at a time. State: last_seen (char -> index) and
window_start. Both bounded by the number of distinct characters
in the current window, not by stream length.'''
last_seen = {}
window_start = 0
best = 0
for i, ch in enumerate(stream_chars):
if ch in last_seen and last_seen[ch] >= window_start:
window_start = last_seen[ch] + 1
last_seen[ch] = i
best = max(best, i - window_start + 1)
return best
stream = "abcabcbbcaabcdefabcdefabc" * 40 # 1000 characters, 6 distinct chars
print(len(stream), len(set(stream)), streaming_longest_unique(stream))
Output:
1000 6 6
Over a 1000-character stream built from a 6-character alphabet, the longest unique-substring length comes out to 6, the maximum possible given only 6 distinct characters exist at all. Instrumenting the same run to record the size of last_seen after every character confirms it never exceeds 6, the alphabet size, regardless of how far into the 1000-character stream the scan has progressed. Re-running the non-streaming, whole-string version of the algorithm on the identical input produces the same answer, confirming the streaming version loses no accuracy.
Trade-offs and pitfalls
The most common wrong turn is assuming "streaming" automatically means trading exactness for an approximate or probabilistic answer (a sketch or a sampling scheme), when in this specific problem the natural state is already small and exact. That intuition is right for problems like counting distinct elements over a huge stream, where an exact answer genuinely requires unbounded memory and something like a probabilistic cardinality estimator becomes necessary, but it does not apply here, because the answer only ever depends on a small, recent window. A second pitfall is forgetting to bound the map at all: storing every character ever seen with its ORIGINAL first-seen index and never updating it silently reintroduces unbounded growth, and also produces wrong window jumps from stale first-seen data instead of last-seen data. A third is conflating "no repeats in the whole stream" (which would require unbounded state, since you would have to remember everything ever seen) with "no repeats in the current window" (what this problem actually asks for, and what stays bounded).
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.