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 a recursive function flatten(nested: List[Any]) -> List[Any] in Python that flattens arbitrarily nested lists (e.g., [1, [2, [3, 4], 5], 6] -> [1,2,3,4,5,6]). Discuss recursion depth concerns for extremely nested input and provide an iterative alternative using an explicit stack.
Sample Answer
Direct answer
A straightforward recursive flatten walks the nested structure, recursing into every sub-list and appending every non-list element directly to the result. It is correct and easy to read, but its recursion depth equals the input's NESTING depth, not its total element count, so an extremely deeply nested input (thousands of levels of [[[...]]]) can exceed the language's recursion limit and crash with a stack overflow, even though the total amount of data is tiny. An iterative version using an explicit stack does the identical traversal without ever growing the call stack, and handles arbitrary nesting depth safely.
Structured elaboration
The recursive approach
For each item in the input list: if it is itself a list, recursively flatten it and extend the result with what comes back; otherwise, append it directly. This mirrors the problem's own recursive structure (a nested list is either an element or a list of nested lists) almost exactly, which is why it reads so naturally, but that same one-to-one mirroring is exactly what ties its stack depth to the input's nesting depth.
Why recursion depth is the real concern here
Python's default recursion limit, retrievable via sys.getrecursionlimit(), is 1000. This limit exists to protect the underlying interpreter stack from being exhausted, which would crash the process outright rather than raising a catchable Python exception; the recursion limit is what turns that hard crash into a catchable RecursionError instead. A list nested 1500 levels deep, [[[...[1]...]]], has only a single element, but flattening it recursively requires 1500 nested calls, comfortably past the default limit, so the recursive version raises RecursionError on an input that is trivially small in terms of total data.
The iterative alternative with an explicit stack
Replace the call stack with an explicit Python list acting as a stack, where each stack entry is an ITERATOR over one level of nesting rather than a raw list. Repeatedly pull the next item from the iterator at the top of the stack: if it is a list, push an iterator over IT onto the stack and continue; if it is a plain element, append it to the result; if the top iterator is exhausted, pop it off and continue with whatever is now on top. This performs the exact same traversal as the recursive version, but the "depth" it tracks lives on the heap (as entries in the stack list), bounded only by available memory, not by the interpreter's fixed recursion limit.
Worked example
import sys
def flatten(nested):
result = []
for item in nested:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
def flatten_iterative(nested):
result = []
stack = [iter(nested)]
while stack:
top = stack[-1]
try:
item = next(top)
except StopIteration:
stack.pop()
continue
if isinstance(item, list):
stack.append(iter(item))
else:
result.append(item)
return result
example = [1, [2, [3, 4], 5], 6]
print(flatten(example))
print(flatten_iterative(example))
depth = sys.getrecursionlimit() + 500
deeply_nested = 1
for _ in range(depth):
deeply_nested = [deeply_nested]
try:
flatten(deeply_nested)
print("recursive: no error")
except RecursionError:
print("recursive: RecursionError")
print("iterative:", flatten_iterative(deeply_nested))
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
recursive: RecursionError
iterative: [1]
Both implementations agree exactly on the question's own example, [1, [2, [3, 4], 5], 6] -> [1, 2, 3, 4, 5, 6]. The recursion-depth concern is demonstrated directly, not just asserted: building a list nested 500 levels past the default recursion limit and flattening it recursively does raise RecursionError (confirmed against Python's default limit of 1000), while the iterative version flattens the exact same deeply nested input to [1] without any error.
Trade-offs and pitfalls
Raising sys.setrecursionlimit() to a larger number is a tempting quick fix, but it does not remove the underlying risk, it only moves the crash point further out, and pushing it too far can crash the whole PROCESS with a C-level stack overflow instead of a catchable Python exception, since the interpreter's own limit exists specifically to stay within the real stack memory available. The iterative version is the more ROBUST general answer for this reason: it trades a small amount of code complexity, managing an explicit stack of iterators rather than relying on the language's call stack, for a traversal that cannot fail on input shape alone, only on genuinely running out of memory. Also worth naming: neither version currently guards against a value that is directly self-referential (a list containing itself), which would recurse or loop forever regardless of which approach is used; that is a distinct edge case from nesting depth and would need explicit cycle detection if the input could ever be adversarial or attacker-controlled rather than merely deeply nested.
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).
Longest Consecutive Sequence: Given an unsorted array of integers, implement a Python function that returns the length of the longest sequence of consecutive integers using O(n) time. Explain why a hash set approach works and discuss how this could be used to detect contiguous ID spans in large event logs.
Sample Answer
Direct answer
Put every number into a hash set for O(1) average membership checks, then only start counting a run from numbers that are the START of a run, meaning num - 1 is not in the set. From each such start, walk forward while the next consecutive integer is present, tracking the longest run found. This turns an O(n log n) sort-based approach into O(n) average time, because the set lets you test "is this the start of a run" without looking at the rest of the array.
Structured elaboration
Approach
def longest_consecutive(nums):
num_set = set(nums)
best = 0
for n in num_set:
if (n - 1) not in num_set:
length = 1
while (n + length) in num_set:
length += 1
best = max(best, length)
return best
Why this is O(n), not O(n times the average run length)
The inner while loop only ever runs starting from a number that has no predecessor in the set, that is, the FIRST element of some run. Every other number in that run gets skipped by the outer loop's guard (n - 1 not in num_set is false for them), so the inner loop is never re-entered from the middle of a run it has already walked. Summed across the whole execution, every number in the array is visited by the inner loop's forward walk at most once, across the ENTIRE algorithm, not once per outer-loop iteration; that is what keeps the total work at O(n) despite the code superficially looking like a nested loop.
Application: contiguous ID spans in event logs (the question's explicit ask)
If event or record identifiers are integers assigned in increasing order, but the log has gaps (from filtered-out, dropped, or retried events), this exact technique finds the longest unbroken run of the IDs that DID make it into the log, in one O(n) pass over an unsorted set of IDs, without first sorting the whole log.
Worked example
Executed with python3 s74.py, pinned inputs:
input: [100, 4, 200, 1, 3, 2, 101, 102]
longest_consecutive(nums) = 4
The run 1, 2, 3, 4 has length 4; the run 100, 101, 102 has length 3; 4 is the longer of the two, matching the printed result.
event_ids: [7001, 7002, 7004, 7005, 7006, 7010]
longest contiguous ID span length = 3
The span 7004, 7005, 7006 (length 3) is longer than the span 7001, 7002 (length 2), matching the printed result and directly demonstrating the event-log framing the question asks about.
Trade-offs and pitfalls
- The single most common bug is dropping the
(n - 1) not in num_setguard and letting the inner loop start from every element; that degrades to O(n^2) in the worst case (for example, one long consecutive run), even though the code still looks like "the hash-set version" at a glance. - Duplicate values in the input do not affect correctness (the set removes them), but the returned length measures the run over DISTINCT values; if a caller actually needs to count how many raw events fall in the longest span, including duplicates, this exact function does not do that and needs a small extension.
- If the caller needs the actual start and end of the run for reporting (not just its length, which is what the event-log framing implies you would want in practice), track the start value alongside the length whenever a new best is found.
In an SRE environment you observe a Python service allocating many temporary strings and causing GC pressure. Describe concrete methods to profile string allocations (tracing allocators, memory profilers), identify hotspots, and reduce allocations using techniques like bytearray/memoryview, io.StringIO, preallocated buffers, pooling, or moving hot paths to languages with different allocation/escape analysis (Go). Provide metrics you'd collect to demonstrate improvement.
Sample Answer
Direct answer
Profile with tracemalloc (or a sampling profiler like py-spy for a live production process you cannot restart) to find which lines are allocating the most, then reduce churn by building strings incrementally into a preallocated buffer (io.StringIO, a list plus "".join(), or a bytearray/memoryview for byte-oriented data) instead of repeated concatenation, and only reach for rewriting the hot path in a compiled language like Go once profiling shows the Python-level allocation itself, not something else, is the bottleneck. To demonstrate improvement, compare allocation counts and bytes allocated before and after, not wall-clock time, since wall-clock measurements are too environment-dependent to be a reliable before/after signal on their own.
Structured elaboration
Profiling and identifying hotspots:
tracemalloc(standard library): take a snapshot, run the workload, take a second snapshot, and compare them grouped by traceback (Snapshot.compare_to(..., "lineno")). This ranks allocation sites by net bytes and net object count, which is exactly "identify hotspots" turned into a concrete procedure.py-spy: a sampling profiler that attaches to an already-running process by PID, with no code changes and low enough overhead to run against production. This matters specifically in a Site Reliability Engineering (SRE) context, where the process causing the pressure may not be restartable or instrumentable on demand.objgraph: useful when the concern is object retention (things not being freed) rather than pure allocation churn, by showing what is holding references to a suspect object type.
A precision point that changes how you frame the problem to a team: plain Python str objects are refcounted, not tracked by the cyclic garbage collector (garbage collection, GC) at all, since they cannot hold references to other objects. Confirmed directly: gc.is_tracked("hello") returns False. This means transient string churn in CPython does not, by itself, increase cyclic-GC pause frequency the way churn of container objects (lists, dicts, custom class instances) can; it shows up instead as allocator (pymalloc) traffic, more time spent in malloc/free-equivalent bookkeeping, and heap fragmentation. Calling this "GC pressure" is common shorthand but is worth correcting precisely when advising a team, since it points them at the right tool (tracemalloc, allocator-level metrics) instead of the wrong one (gc.get_stats(), which reports on the cyclic collector).
Reducing allocations, in the order the question names them:
bytearray/memoryview:bytearrayis mutable, so appending to it does not create a new object each time the way immutablestrconcatenation can;memoryviewlets you take zero-copy slices of existing buffer objects instead of allocating a new copy for every substring.io.StringIO: acts as a growable in-memory buffer with.write(), giving the same "accumulate then finalize" benefit as building a list and joining it, useful when the code is structured as many small writes rather than a clean list comprehension.- Preallocated buffers / pooling: if the maximum size is known or bounded, allocate the buffer once outside the hot loop and reuse it, rather than allocating fresh per iteration or per request; this is the standard fix once profiling shows the same code path allocating repeatedly at high frequency.
"".join(list_of_parts): append parts to a list (which CPython over-allocates geometrically, so appending is amortized O(1)) and join once at the end, rather than repeated+=concatenation.- Moving the hot path to a language with different allocation and escape-analysis behavior: Go's escape analysis can keep many short-lived values on the stack instead of the heap, avoiding per-object allocator overhead entirely for values that never need to outlive the function call; a hand-written C extension goes further still, giving full manual control over a single reused buffer with zero object-header overhead per string. Both are justified only once profiling has shown the allocation itself, not I/O or something else entirely, is the actual bottleneck.
Metrics to collect to demonstrate improvement:
- Net bytes allocated and net object count from
tracemallocsnapshot comparisons, run against the same fixed workload before and after the change (a controlled, repeatable comparison, not a wall-clock timing claim). gc.get_stats()collection counts per generation, mainly as a sanity check that the change has not shifted pressure onto container types the cyclic collector does track, rather than as the primary signal for string-specific churn (per the precision point above).- Process-level memory metrics already collected by most SRE tooling: resident set size (RSS) over time and page-fault counts, which reflect real allocator and operating-system-level cost.
- Downstream 95th/99th-percentile (P95/P99) request latency in production dashboards, correlated with the change's rollout, as the ultimate business-relevant signal, understanding that latency is influenced by many factors and is a correlation check, not a controlled experiment by itself.
Worked example
A controlled comparison of three approaches to building an 80,000-character string from 2,000 fixed 40-character pieces, counting reallocations directly via consecutive-identity comparison rather than timing anything:
import gc
N_ITEMS = 2000
ITEM = "x" * 40
print(f"gc.is_tracked('hello') = {gc.is_tracked('hello')}")
def count_reallocations_plus_equals(alias=False):
s = ""
history = [] if alias else None
realloc_count = 0
bytes_copied = 0
prev_id = None
for _ in range(N_ITEMS):
if alias:
history.append(s) # keeps refcount(s) >= 2, defeating CPython's in-place resize fast path
s += ITEM
if id(s) != prev_id:
realloc_count += 1
bytes_copied += len(s)
prev_id = id(s)
return realloc_count, bytes_copied
def count_reallocations_join():
parts = [ITEM for _ in range(N_ITEMS)]
result = "".join(parts)
return 1, len(result)
n_no_alias, bytes_no_alias = count_reallocations_plus_equals(alias=False)
n_alias, bytes_alias = count_reallocations_plus_equals(alias=True)
n_join, bytes_join = count_reallocations_join()
quadratic_upper_bound = sum(i * len(ITEM) for i in range(1, N_ITEMS + 1))
print(f"'+=' no alias : reallocations = {n_no_alias:6d}, bytes copied = {bytes_no_alias:9d}")
print(f"'+=' aliased : reallocations = {n_alias:6d}, bytes copied = {bytes_alias:9d}")
print(f"''.join(list) : reallocations = {n_join:6d}, bytes copied = {bytes_join:9d}")
print(f"O(n^2) upper bound if every '+=' fully reallocated = {quadratic_upper_bound}")
print(f"aliased bytes-copied / no-alias bytes-copied = {bytes_alias / bytes_no_alias:.1f}x")
print(f"aliased bytes-copied / quadratic upper bound = {bytes_alias / quadratic_upper_bound:.3f}")
Output (one representative run; counting via id(s) != prev_id rather than accumulating ids in a set matters here, because CPython can reuse a freed string's memory address for a later object, which silently under-counts reallocations if you count distinct id() values seen across the whole run instead of consecutive-call transitions):
gc.is_tracked('hello') = False
'+=' no alias : reallocations = 36, bytes copied = 212200
'+=' aliased : reallocations = 2000, bytes copied = 80040000
''.join(list) : reallocations = 1, bytes copied = 80000
O(n^2) upper bound if every '+=' fully reallocated = 80040000
aliased bytes-copied / no-alias bytes-copied = 377.2x
aliased bytes-copied / quadratic upper bound = 1.000
This is a genuinely interesting result, not the textbook story most candidates repeat: when nothing else holds a reference to the accumulating string, CPython's own refcount-1 fast path resizes the string in place for most iterations, so only a few dozen reallocations (36 in this run; repeated local runs varied between 36 and 37, with bytes copied varying correspondingly between roughly 212,200 and 277,720, since the fast path's exact behavior depends on the allocator's in-memory layout at the time) were actually needed for 2,000 concatenations, and total bytes copied is nowhere near the naive O(n2) bound in any of those runs. The moment something else holds a reference to the intermediate value on each iteration (history.append(s), simulating an innocuous-looking debug log or snapshot list elsewhere in the code), that fast path is completely defeated: exactly 2,000 reallocations occur every time (one per iteration, matching N exactly) and the bytes-copied total lands at a ratio of 1.000 against the textbook quadratic bound, with no run-to-run variation
exactly matching the printed value, in every run. "".join() allocates exactly one object regardless. The practical lesson for an SRE debugging this in a real service: the dangerous pattern is not += concatenation itself, it is += concatenation where something else (a logger, a cache, a list of "recent values" for a debug endpoint) is quietly holding a reference to each intermediate string.
Trade-offs & pitfalls
- "Always use
join, never+=" is oversimplified advice given what this measurement shows: in CPython specifically, single-owner+=is often not the quadratic disaster it is in languages without that optimization."".join()remains the right default because it is portable (not every Python implementation, such as PyPy in some configurations, guarantees the same optimization) and immune to accidental aliasing, but do not present the complexity claim as universally true across implementations without qualifying it. - Reporting "reduced GC pressure" without the
gc.is_trackeddistinction can send a team optimizing the wrong layer. If the actual problem is generational-collector pause time, the fix is about reducing tracked-container churn (dicts, lists, custom objects), not string handling at all; conflating the two wastes an investigation cycle. - Rewriting a hot path in Go or C is the highest-effort, highest-risk option on this list (new language, new deployment surface, a cross-language call boundary to maintain) and should be the last resort, justified by profiler evidence that the allocation itself, not serialization overhead, I/O wait, or something else in the same code path, is what dominates.
- A common measurement mistake: comparing wall-clock time for a "before" and "after" version on a shared, noisy production host and presenting the difference as the improvement. Machine load, CPU frequency scaling, and other tenants make single wall-clock comparisons unreliable; use allocation counts and bytes (as measured above) or repeated, controlled benchmarking on an isolated host as the primary evidence instead.
Find all start indices of p's anagrams in s. Given strings s and p, return a list of starting indices of p's anagrams in s. Example: s = 'cbaebabacd', p = 'abc' -> [0,6]. Implement in Python using sliding window + frequency arrays in O(n) time. Explain applications for substring pattern detection in tokenized text.
Sample Answer
Direct answer
Slide a fixed-size window of length len(p) across s, tracking the window's contents with two fixed-size frequency arrays (as the question specifies), one for p's required counts and one for the current window, indexed directly by character rather than through hashing. Updating the window incrementally (increment the entering character's slot, decrement the exiting character's slot) rather than rebuilding and comparing a fresh count every position is what makes this O(n) instead of O(n * |p|). Space is O(alphabet size): for lowercase English letters, that is a fixed 26 integers regardless of how long s or p are.
Algorithm
- Build
need, a length-26 array ofp's character counts (need[ord(ch) - ord('a')] += 1for each character inp). - Initialize
windowas the length-26 count array ofs's firstlen(p)characters. - If
window == need(array-to-array comparison), index 0 is a match. - Slide the window one character at a time: increment the slot of the character entering on the right, decrement the slot of the character leaving on the left, and compare
window == needagain after each slide.
def find_anagrams(s: str, p: str) -> list:
len_s, len_p = len(s), len(p)
if len_p > len_s:
return []
def index_of(ch):
return ord(ch) - ord("a")
need = [0] * 26
window = [0] * 26
for ch in p:
need[index_of(ch)] += 1
for ch in s[:len_p]:
window[index_of(ch)] += 1
result = []
if window == need:
result.append(0)
for i in range(len_p, len_s):
incoming, outgoing = s[i], s[i - len_p]
window[index_of(incoming)] += 1
window[index_of(outgoing)] -= 1
if window == need:
result.append(i - len_p + 1)
return result
Using a fixed-size array indexed directly by ord(ch) - ord('a'), rather than a hash map keyed by the character, is exactly what "frequency array" means here: no hashing, no key deletion bookkeeping (a count naturally sits at 0 in an untouched slot, so there is nothing to clean up the way there would be with a dict-based count map), and the window == need comparison is a fixed-length list comparison, always exactly 26 elements, regardless of the alphabet actually observed in a given window. This assumes a known, bounded alphabet (lowercase English letters, size 26 here); for Unicode or an unbounded alphabet, a hash map keyed by character is the structure that scales with distinct characters actually seen instead of the size of the declared alphabet, at the cost of per-key hashing overhead.
Applications for substring pattern detection in tokenized text
The same fixed-size-window-plus-count-comparison technique applies directly to detecting "this window of tokens is a rearrangement of a target token multiset," which comes up in tasks like flagging text spans that contain exactly the same word multiset as a suspicious phrase (word-order-scrambled plagiarism or obfuscation detection) or matching a fixed-size set of required tags in a tokenized log line regardless of their order. The technique is identical, only the "character" unit changes to "token."
Worked example
def brute_force_find_anagrams(s, p):
len_p = len(p)
target = sorted(p)
result = []
for i in range(len(s) - len_p + 1):
if sorted(s[i:i+len_p]) == target:
result.append(i)
return result
tests = ["cbaebabacd", "abab", "aaaaaaaaaa"]
patterns = ["abc", "ab", "aaa"]
for s, p in zip(tests, patterns):
fast = find_anagrams(s, p)
brute = brute_force_find_anagrams(s, p)
print(f"find_anagrams({s!r}, {p!r}) = {fast} (brute-force agrees: {fast == brute})")
Output (verified by execution, and cross-checked against an O(n * k log k) brute-force reference that sorts every window directly, so the fast result's correctness is independently confirmed rather than assumed):
find_anagrams('cbaebabacd', 'abc') = [0, 6] (brute-force agrees: True)
find_anagrams('abab', 'ab') = [0, 1, 2] (brute-force agrees: True)
find_anagrams('aaaaaaaaaa', 'aaa') = [0, 1, 2, 3, 4, 5, 6, 7] (brute-force agrees: True)
Tracing s='cbaebabacd', p='abc' (need = {a:1, b:1, c:1}): the window at index 0 is "cba", whose counts exactly match need, so index 0 is recorded. Sliding to index 1 gives "bae", which introduces 'e' (not in need at all) so it fails to match. The window keeps sliding until index 6, "bac" (b,a,c), which again matches need exactly, giving the second recorded index. No other window in between matches because each contains either a repeated letter with the wrong count or a letter ('e', 'd') that need doesn't have at all.
Trade-offs and pitfalls
- Comparing two full 26-length arrays on every slide is itself O(alphabet size) per comparison, not O(1), so even though the alphabet here is small and fixed, this is not free; a common refinement is to track a single integer "how many of the 26 positions currently match between the two arrays" (the same trick used in minimum-window-substring problems), updated incrementally as each slide changes at most two positions, which turns the check into O(1) instead of O(26) per step.
- The frequency-array approach assumes a known, bounded alphabet. It is the right choice here (lowercase English letters) precisely because the question specifies it; for Unicode text or an unbounded token vocabulary, a hash map keyed by the actual character or token is what scales with distinct values seen, and switching to one is a straightforward substitution of the counting structure without changing the sliding-window logic itself.
- This is a fixed-size window, unlike minimum-window-substring's variable-size window: the window length here is always exactly
len(p), which is simpler (no shrink/grow decision needed) but means the technique doesn't generalize to "smallest window containing X" problems without the additional grow/shrink logic those require. - Edge cases:
plonger thans(no window can exist, return empty immediately),pempty (depends on the problem's intended contract, typically treated as matching every position or explicitly disallowed), and heavily repeated characters ins(as in the'aaaaaaaaaaaa'/'aaa'case above), which stress-test that the sliding update (not a full rebuild) is genuinely being used, since a naive re-slice-and-recount implementation would still pass correctness tests here but silently lose its performance advantage.
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.