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.
Write a Python function to compute the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string. Example: ['flower','flow','flight'] -> 'fl'. Discuss O(n * m) naive complexity and ways to optimize using vertical scanning or binary search.
Sample Answer
Direct answer
Compare characters column by column across all the strings at once (vertical scanning): at each position i, check that every string shares the same character at that position. The first mismatch, or the first string that runs out of characters, marks the end of the common prefix. This is simple, correct, and exits as soon as a genuine mismatch is found, rather than fully comparing whole strings pairwise the way a naive approach might.
Structured elaboration
Vertical scanning approach
def longest_common_prefix_vertical(strs):
if not strs:
return ""
for i, ch in enumerate(strs[0]):
for other in strs[1:]:
if i >= len(other) or other[i] != ch:
return strs[0][:i]
return strs[0]
O(n*m) naive complexity (the question's explicit ask)
With n strings and m the length of the shortest string, ANY correct approach touches at most n * m character comparisons in the worst case, imagine every string identical except for a mismatch right at the very last position checked. Vertical scanning does not beat this worst-case bound; what it buys you is exiting early on realistic negative cases, where a mismatch is usually found within the first handful of characters and strings, not at the theoretical worst-case position.
Binary-search-on-prefix-length approach (the question's explicit ask)
Binary search over candidate prefix lengths from 0 to the shortest string's length, using an O(n*m) helper ("is this length a common prefix of every string") as the check at each step:
def _is_common_prefix(strs, length):
prefix = strs[0][:length]
return all(s[:length] == prefix for s in strs)
def longest_common_prefix_binary_search(strs):
if not strs:
return ""
min_len = min(len(s) for s in strs)
lo, hi = 0, min_len
while lo < hi:
mid = (lo + hi + 1) // 2
if _is_common_prefix(strs, mid):
lo = mid
else:
hi = mid - 1
return strs[0][:lo]
Being honest about what this buys you: the per-step check itself costs O(nm) in the worst case, and binary search runs that check O(log m) times, so the WORST-CASE complexity of this version is actually O(n * m * log m), asymptotically worse than vertical scanning's O(nm), not better. Binary-search-over-the-answer is a genuinely useful general problem-solving pattern, and it can pay off here if the per-length check can be made cheap (for example, comparing precomputed rolling hashes of each candidate-length prefix instead of a fresh character-by-character comparison every time), but for the plain character-comparison check shown above, it is not a real optimization over vertical scanning. If a true asymptotic improvement is the goal, the standard technique is building a trie once over all the strings and walking it, which finds the common prefix in a single O(S) pass, where S is the total character count across all strings.
Worked example
Executed with python3 s78.py, both approaches run on the same inputs and confirmed to agree:
['flower', 'flow', 'flight'] vertical='fl' binary_search='fl' agree=True
['dog', 'racecar', 'car'] vertical='' binary_search='' agree=True
['interview', 'internal', 'interstate'] vertical='inter' binary_search='inter' agree=True
['single'] vertical='single' binary_search='single' agree=True
['flower', 'flow', 'flight'] maps to 'fl', matching the question's own stated example exactly.
Trade-offs and pitfalls
- Do not claim the binary-search version is asymptotically faster than vertical scanning for the plain per-length character check shown here; it is not, and overclaiming this specific trade-off is a common mistake that a careful interviewer will probe.
- Vertical scanning's early exit is a genuine, practical win on typical negative inputs (most real-world string sets diverge within the first few characters), even though its worst-case bound matches the fully naive pairwise approach.
- Edge cases worth naming explicitly: an empty list of strings (handled here by convention, returning
""), a single string (the whole string is trivially its own prefix), and one empty string anywhere in the list (the prefix is immediately"", which the vertical-scan loop handles correctly sincestrs[0]may be empty and itsenumeratesimply never executes).
Explain how slicing works for lists in Python (syntax: lst[start:stop:step]). Describe behavior with negative indices and steps, whether slicing returns a view or a new list, and the time and memory complexity of creating a slice of length k from a list of length n. For SRE tasks, when might copying via slicing be a dangerous choice and what alternatives exist?
Sample Answer
Direct answer
lst[start:stop:step] returns a NEW list built by copying references at indices start, start+step, start+2*step, ... up to but not including stop. Negative indices count from the end (-1 is the last element), and a negative step walks backward. Unlike numpy, Python list slicing always copies, it never returns a view, so a slice of length k from a list of length n costs O(k) time and O(k) extra memory, not O(n).
Structured elaboration
Syntax mechanics. start defaults to 0 (or len(lst) for a negative step), stop defaults to len(lst) (or "through the beginning" for a negative step), step defaults to 1. Negative indices are resolved to positive ones first (-1 -> len(lst) - 1), then the normal start/stop/step machinery applies.
Negative step behavior. A negative step reverses the walk direction. lst[::-1] is the idiomatic full-list reverse; lst[5:1:-2] starts at index 5 and walks backward by 2 until it would reach or pass index 1.
View vs copy. List slicing is always a full copy, a genuinely new list object with its own storage, which is why mutating the slice's result never affects the original list (demonstrated below). This differs from numpy, where basic slicing (not fancy or boolean indexing) returns a VIEW sharing the same underlying buffer, and mutating the view does mutate the source, which is a separate consideration when choosing between the two.
Time and memory complexity. Creating lst[a:b] where b - a = k does exactly k reference copies: O(k) time and O(k) new memory, regardless of how large the source list n is. A common misconception is that slicing costs O(n) because "it touches the whole list": it does not, it only touches the k elements it copies.
Site Reliability Engineering (SRE)-specific danger and alternatives. Repeatedly slicing a large in-memory structure (for example, paginating through a multi-gigabyte log buffer with buf[i:i+chunk] in a loop) duplicates data on every slice, which can double memory pressure or trigger avoidable garbage-collection churn under load, exactly when an SRE (the on-call engineer responsible for a system's reliability) least wants unpredictable memory behavior during an incident. Alternatives that avoid the copy: itertools.islice for a lazy, non-copying iterator over a sequence; a plain generator or yield-based chunker; memoryview for byte-like buffers (bytes, bytearray, array.array), which does support zero-copy sliced views; or, for genuinely huge data, memory-mapping the source (mmap) instead of holding it as a Python list at all.
Worked example
data = [10, 20, 30, 40, 50, 60, 70] # length n = 7, pinned
print("first three data[:3] =", data[:3])
print("last two data[-2:] =", data[-2:])
print("every other data[::2] =", data[::2])
print("reversed data[::-1] =", data[::-1])
print("middle (drop ends) data[1:-1] =", data[1:-1])
print("negative step data[5:1:-2] =", data[5:1:-2])
sub = data[1:4]
sub[0] = 999
print("after mutating sub, data =", data, " (unchanged: slicing copied)")
import sys
n = 100_000
big = list(range(n))
small_slice = big[:10]
print("sys.getsizeof(big) =", sys.getsizeof(big), "bytes")
print("sys.getsizeof(small_slice)=", sys.getsizeof(small_slice), "bytes")
Output:
first three data[:3] = [10, 20, 30]
last two data[-2:] = [60, 70]
every other data[::2] = [10, 30, 50, 70]
reversed data[::-1] = [70, 60, 50, 40, 30, 20, 10]
middle (drop ends) data[1:-1] = [20, 30, 40, 50, 60]
negative step data[5:1:-2] = [60, 40]
after mutating sub, data = [10, 20, 30, 40, 50, 60, 70] (unchanged: slicing copied)
sys.getsizeof(big) = 800056 bytes
sys.getsizeof(small_slice)= 136 bytes
The size comparison makes the O(k) claim concrete: a slice of 10 elements from a 100,000-element list costs 136 bytes, not anywhere near the 800,056-byte cost of the full list, confirming the slice's footprint scales with k, not n.
Trade-offs and pitfalls
- Assuming slicing is "free" or O(1): it is O(k), which is cheap for small k but adds up when repeated over large chunks in a hot loop.
- Assuming list slicing returns a view like
numpydoes: it never does. If zero-copy behavior on a byte buffer is needed, reach formemoryview, not a list. - Off-by-one errors with a negative step (
lst[stop:start:-1]-style mistakes) are the single most common source of "why is my reversed slice missing an element." - Rebuilding a large structure via repeated slicing inside an incident-response script is exactly the kind of thing that can turn a memory-pressure incident into a self-inflicted one.
Design group_anagrams(strs) in Python for a backend batch job that groups lists of strings into anagrams. Discuss two approaches: sorting each string as key vs using a frequency vector key. Consider Unicode input, performance for long strings, and memory trade-offs.
Sample Answer
Direct answer
Group strings that are anagrams of each other by mapping each string to a canonical key that is identical for all of its anagrams and different otherwise, then bucket strings by that key in a hash map. The two standard keys are the sorted-character string (simple, O(L log L) per string) and a fixed-length character-frequency vector (O(L) per string, faster for long strings, but only straightforward for a small, known, fixed alphabet).
Structured elaboration
Approach 1: sorted string as key
Sort each string's characters and join them back into a string; two strings are anagrams exactly when this sorted form is identical. Sorting a string of length L costs O(L log L), so grouping n strings this way costs O(n * L log L) in total, where L is the average or maximum string length.
Approach 2: frequency vector as key
Count the occurrences of each character into a fixed-size array (26 entries for lowercase English letters), then use that array, converted to an immutable tuple so it can be a hash-map key, as the grouping key. Building the count for one string costs O(L), so this approach costs O(n * (L + alphabet_size)) in total, asymptotically better than the sorted-key approach once L is large relative to log L, since counting avoids the sort entirely. The trade-off is that this fixed-size-array trick assumes a small, KNOWN alphabet; it does not generalize as cleanly the moment the alphabet is unbounded.
Unicode input
Both approaches need care once the input can contain arbitrary Unicode text rather than plain lowercase English letters. The frequency-vector approach's fixed 26-slot array breaks down immediately, since Unicode text can contain far more than 26 distinct characters; the practical fix is a hash map from character to count instead of a fixed array, which still works but loses the small constant-factor advantage of a fixed array. More subtly, even the sorted-key approach can give a WRONG answer on Unicode input if two visually and semantically identical strings are represented by different underlying code point sequences: an accented character can be represented either as a single precomposed code point, or as the base letter followed by a separate combining accent mark. These compare as different strings and produce different sorted keys even though they represent the same text. The fix is to first normalize every string using Unicode Normalization Form C (NFC), which canonicalizes precomposed and decomposed forms to the same representation, before computing either kind of key.
Performance for long strings and memory trade-offs
For long strings, the frequency-vector approach avoids the L log L sorting cost, which matters when strings are long, for example grouping DNA-like sequences or long tokenized identifiers rather than short English words. Memory-wise, the sorted-key approach's key is proportional to the string's own length, while the frequency-vector key has a FIXED size (26 entries, or however many distinct characters the chosen alphabet has) regardless of the string's length, which can be smaller for long strings but is pure overhead for very short ones.
Worked example
from collections import defaultdict
import unicodedata
def group_anagrams_sorted_key(strs):
groups = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
groups[key].append(s)
return list(groups.values())
def group_anagrams_freq_key(strs, alphabet_size=26):
groups = defaultdict(list)
for s in strs:
counts = [0] * alphabet_size
for ch in s:
counts[ord(ch) - ord('a')] += 1
groups[tuple(counts)].append(s)
return list(groups.values())
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(group_anagrams_sorted_key(strs))
print(group_anagrams_freq_key(strs))
def normalize_for_unicode_anagram_key(s):
return ''.join(sorted(unicodedata.normalize('NFC', s)))
precomposed = "café" # single code point for e-acute
decomposed = "café" # 'e' + combining acute accent
print(precomposed == decomposed)
print(''.join(sorted(precomposed)) == ''.join(sorted(decomposed)))
print(normalize_for_unicode_anagram_key(precomposed) == normalize_for_unicode_anagram_key(decomposed))
Output:
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
False
False
True
Both approaches group the same six words into the same three anagram groups. The Unicode section demonstrates the normalization issue directly: two strings that print identically and represent the same visible text, cafe with an accented e built from a single precomposed code point versus the same word built from a base letter plus a separate combining accent mark, compare as unequal Python strings, and their naive sorted-character keys also disagree, but normalizing both to NFC before computing the key makes them match, exactly the correctness gap this section describes.
Trade-offs and pitfalls
A common mistake is assuming string equality in Python already handles Unicode normalization: it does not, two strings built from a precomposed versus a decomposed representation of the same visible text can compare as unequal, which silently splits what should be one anagram group into two. A second is hardcoding a 26-entry frequency array without checking the actual input alphabet, which either crashes on characters outside a-z or silently produces wrong groupings once real-world text with punctuation, digits, or non-English characters shows up. For genuinely massive input, the scale this problem is asked at in a batch-processing context, well beyond what fits comfortably in memory as one hash map, the practical extension is external-memory or streaming grouping: sort the (key, original-string) pairs using an external merge sort so anagrams become adjacent on disk without needing every group held in memory at once, or shard by a prefix of the key across multiple workers so each worker only needs to hold its own shard's groups in memory. That is a genuine and reasonable extension of this same technique at scale, but it is a distinct system-design problem from choosing a grouping key, and is mentioned here only as the natural next question, not as something this answer needs to design in full. The same two key strategies carry over unchanged in Java (HashMap<String, List<String>> or HashMap<List<Integer>, List<String>>) and JavaScript (a Map keyed on the same sorted-string or frequency-array-as-string idea).
Smallest Subarray with Sum at Least S: Given a positive integer array and integer s, find the minimal length of a contiguous subarray of which the sum >= s. Use sliding window and two pointers and implement in Python. Explain why this requires positive numbers for the sliding window approach to work.
Sample Answer
Direct answer
Expand a window from the right, adding each new element to a running sum. The moment the running sum reaches or exceeds the target, record the window's length as a candidate answer and shrink from the left for as long as the sum still qualifies, since every valid window found this way is a candidate for the minimum. Track the smallest length seen across the whole single pass.
Structured elaboration
Approach
def min_subarray_len(s, nums):
n = len(nums)
left = 0
window_sum = 0
best = n + 1
for right in range(n):
window_sum += nums[right]
while window_sum >= s:
best = min(best, right - left + 1)
window_sum -= nums[left]
left += 1
return 0 if best == n + 1 else best
Why this requires positive numbers (the question's explicit ask)
The sliding-window technique relies on the running sum changing MONOTONICALLY as each pointer moves: adding an element (moving right) can only ever increase the sum, and removing an element (moving left) can only ever decrease it, if and only if every element is positive. That monotonicity is exactly what justifies greedily shrinking the window without ever needing to re-check a wider window later: once the sum drops below the target after removing the leftmost element, removing MORE elements from the left is guaranteed to keep it below target too, since removing a positive number is always a strict decrease. If the array could contain zero or negative values, adding an element to the right would no longer guarantee the sum increases, so a window that currently fails the threshold might still succeed if extended further, and the greedy shrink-from-the-left step is no longer safe. The standard fallback for arrays with negative numbers is prefix sums combined with a monotonic deque, or, for exact-sum variants, prefix sums indexed in a hash map.
Variant: count subarrays with product strictly less than k
A related ask uses the identical two-pointer skeleton, but tracks a running PRODUCT instead of a sum, and counts how many valid windows END at each right pointer rather than tracking a minimum length:
def num_subarrays_product_less_than_k(nums, k):
if k <= 1:
return 0
left = 0
product = 1
count = 0
for right, x in enumerate(nums):
product *= x
while product >= k:
product //= nums[left]
left += 1
count += right - left + 1
return count
def brute_force_count(nums, k):
"""O(n^2) reference: enumerate every subarray's product directly, with
no window-shrinking logic to trust. Used only to cross-check the
two-pointer version above, not as the real answer."""
n = len(nums)
count = 0
for i in range(n):
product = 1
for j in range(i, n):
product *= nums[j]
if product < k:
count += 1
return count
The key insight that makes the counting step correct: for a fixed right pointer, every subarray from index left..right, left+1..right, ..., all the way to right..right, is also valid, since removing elements from the front of a window whose product is already below the threshold (with all-positive elements) can only make the product smaller or equal. So the count of newly valid subarrays ending exactly at right is right - left + 1, added once per right-pointer step. This again relies on positive integers for the same monotonicity reason as above.
Worked example
Executed with python3 s81.py (both the two-pointer function and the brute-force reference defined above):
min_subarray_len(s=7, nums=[2, 3, 1, 2, 4, 3]) = 2
min_subarray_len(s=100, nums=[1, 2, 3]) = 0
The window [4, 3] sums to 7 in exactly 2 elements, the shortest possible; with a target of 100 and a maximum possible total sum of 6, no window can ever reach it, so the function correctly returns 0.
num_subarrays_product_less_than_k(nums=[10, 5, 2, 6], k=100) = 8
brute_force_count(nums=[10, 5, 2, 6], k=100) = 8
The brute-force reference (shown above) agrees exactly: 8 qualifying subarrays out of 10 possible non-empty subarrays for a 4-element array.
Trade-offs and pitfalls
- The two-pointer approach is O(n) time and O(1) extra space; that is the entire value proposition over a brute-force O(n^2) (or worse) scan, and interviewers expect BOTH the working code AND the positivity argument for why the greedy shrink is valid, not just code that happens to pass test cases.
- A common bug in the counting variant is omitting the
if k <= 1: return 0guard: withk <= 1, no product of positive integers can ever be strictly less thank, and the main loop'swhile product >= kshrink condition would otherwise pushleftpastrightand read a stale or out-of-range element. - It is easy to conflate "smallest window that reaches a target" (this problem, returning a length) with "count every window satisfying a condition" (the other variant, returning a count); keep straight which of the two output shapes a given question is actually asking for, since the bookkeeping each one needs is different even though the window-management code looks nearly identical.
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.