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.
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.
Implement nested_get(data, path, default=None) in Python where data may be a nested mixture of dicts and lists and path is a list like ['a', 0, 'b'] representing data['a'][0]['b']. Return default if any part of the path is missing. Provide a robust implementation and discuss error handling and performance.
Sample Answer
Direct answer
Walk the path one key at a time, keeping a "current" reference that starts at data. At each step, check what kind of container you are looking at (dict vs list/tuple) before indexing into it, and catch every way that step can legitimately fail (missing key, out-of-range index, or trying to index something that is not a container). The moment any step fails, return default immediately rather than letting the exception escape.
Approach
- Iterate, don't recurse. An iterative loop over
pathis O(depth) time and O(1) extra space; a recursive version works too but costs O(depth) stack frames for no benefit here, so the loop is the better default. - Branch on container type before indexing.
dictsupportscurrent[key], and so doeslist/tuplewhenkeyis anint, but alistindexed with a string key raisesTypeError, notKeyError. Checkingisinstance(current, dict)vsisinstance(current, (list, tuple))up front means you always know which failure mode to expect. - Treat KeyError, IndexError, and TypeError as the same "path segment missing" signal. All three mean "this step of the path does not exist in this data," so they should all fall through to the same
return default. - Stop as soon as
currentis neither a dict nor a list/tuple but the path isn't finished. Trying to walk further into a plain int or string is also "missing," not a crash.
Error handling and performance
Error handling here means treating every legitimate "this path segment doesn't exist" case (missing dict key, out-of-range list index, or indexing into a non-container) as the single default-returning outcome, rather than letting the underlying KeyError / IndexError / TypeError propagate up to the caller. Performance: time is O(d) where d is the length of path (each step does one O(1) dict/list access), and space is O(1) extra (iterative; ignoring the space already used by data itself).
Edge cases
- Empty
pathreturnsdataitself unchanged. - A path segment that is a valid dict key syntactically but absent at runtime returns
default. - A path segment that indexes past the end of a list, or indexes a list with a non-integer key, returns
defaultrather than raising. - The function never mutates
data.
def nested_get(data, path, default=None):
current = data
for key in path:
try:
if isinstance(current, dict):
current = current[key]
elif isinstance(current, (list, tuple)):
current = current[key]
else:
return default
except (KeyError, IndexError, TypeError):
return default
return current
data = {
"a": [{"b": 1}, {"b": 2}],
"x": {"y": {"z": 42}},
}
print(nested_get(data, ["a", 1, "b"])) # 2
print(nested_get(data, ["a", 5, "b"])) # None (index out of range)
print(nested_get(data, ["x", "y", "q"], -1)) # -1 (missing key, custom default)
print(nested_get(data, ["a", 0, "b", "c"])) # None (tries to index an int)
print(nested_get(data, [])) # returns data itself
Output:
2
None
-1
None
{'a': [{'b': 1}, {'b': 2}], 'x': {'y': {'z': 42}}}
Trade-offs and pitfalls
- EAFP (try/except) vs LBYL (isinstance checks) for the actual indexing: this answer combines both, using
isinstanceto route to the right container operation andtry/exceptto catch the specific ways that operation can fail. A pure EAFP version (baretry: current = current[key]for every type) is shorter but conflates "wrong container type" with "index/key not found," which matters if a caller wants to distinguish them later. - Silent-failure risk: returning
defaultfor every failure mode is convenient but means a genuine bug in the caller'spath(e.g. a typo'd key) looks identical to legitimately absent data. If the caller needs to tell those apart, raise a custom exception with the failing segment instead of swallowing it. defaultvs "value isNone" ambiguity: if a real value indataisNone, this function correctly returns thatNone(it only returnsdefaultwhen a step actually fails), but callers should not assume "gotNoneback" always means "missing": it may mean "found, and the value wasNone."- Immutability of the path: using a
listforpathis fine since it is only read, never written; atupleworks identically and communicates intent slightly better since paths are typically fixed once constructed.
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 is_subsequence(short: str, long: str) -> bool in Python that checks whether 'short' is a subsequence of 'long' (characters in order but not necessarily contiguous). This is used in approximate matching and fuzzy token mapping. Your solution should be O(n) time where n is length of 'long'. Provide an example and handle edge cases.
Sample Answer
Direct answer
Walk through long once with a single pointer, and advance a second pointer into short only when the current character of long matches the character short is currently waiting for. If the pointer into short reaches the end before long runs out, every character of short was found in order, so short is a subsequence of long.
Structured elaboration
Approach
def is_subsequence(short, long):
i = 0
if not short:
return True
for ch in long:
if i < len(short) and ch == short[i]:
i += 1
if i == len(short):
return True
return i == len(short)
Only one pass over long is made, and the pointer into short never moves backward, so the total work is O(n) where n is the length of long, matching the question's explicit complexity requirement. No extra data structure is needed since matching only ever needs to compare the CURRENT position of short against the current character of long.
Application context (the question's explicit ask)
This same one-pass check is the building block behind approximate matching and fuzzy token mapping: for example, checking whether a user's typed abbreviation could plausibly expand to a longer canonical term ("gcm" as a subsequence of "google cloud monitoring"), or filtering a large candidate list down to the ones that could still match a partially typed query, before applying a more expensive scoring step only to that smaller candidate set.
Worked example
Executed with python3 s83.py, five pinned cases including two explicit edge cases (empty short, empty long):
is_subsequence('abc', 'ahbgdc') = True expected=True match=True
is_subsequence('axc', 'ahbgdc') = False expected=False match=True
is_subsequence('', 'anything') = True expected=True match=True
is_subsequence('abc', '') = False expected=False match=True
is_subsequence('ace', 'abcde') = True expected=True match=True
'abc' is found in order inside 'ahbgdc' (a, then b, then c, each appearing later than the last), so it returns True. 'axc' fails because after matching 'a', no 'x' appears anywhere later in 'ahbgdc', so the pointer into short never reaches the end.
Trade-offs and pitfalls
- The empty-
short-is-always-a-subsequence edge case (is_subsequence('', 'anything')returningTrue) is easy to get backwards if the loop logic is written slightly differently; the explicitif not short: return Trueguard above makes this an intentional decision rather than an accident of how the loop happens to terminate. - If this check needs to run many times against the SAME
longstring with many differentshortcandidates, a smarter structure (precomputing, for each position and character, the next occurrence of that character) avoids repeating the full O(n) scan per query, at the cost of O(n * alphabet size) preprocessing; that preprocessing trade is only worth it when the number of queries against the samelongstring is large. - This only answers yes/no. If the caller also needs the actual matched positions in
long(for example, to highlight which characters satisfied the match), track and return the index list as the pointer advances, rather than just the boolean.
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.