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 a JavaScript function to validate whether a given string is a valid IPv4 or IPv6 address. For IPv4, each octet should be 0-255 with no leading zeros unless the octet is zero; for IPv6, validate eight groups of 1-4 hex digits, allowing shorthand '::' once. Discuss edge cases and complexity.
Sample Answer
Direct answer
Try IPv4 first: split on ., require exactly 4 parts, and each part must be all digits, at most 255, with no leading zero unless the part is exactly "0". If that fails, try IPv6: split on :, handle the :: zero-compression shorthand (which can appear at most once), require the expanded form to have exactly 8 groups, and each group must be 1 to 4 hexadecimal digits. Both formats have real edge-case density, which is exactly why this question is a good filter for carefulness rather than algorithmic cleverness.
Approach: IPv4
- Split on
.; reject unless there are exactly 4 parts. - Each part must be all-digit (test against
/^[0-9]+$/), which also rejects a sign character or empty part. - Reject a leading zero unless the part is exactly
"0"(i.e."0"is valid,"00"and"01"are not). - Reject if the numeric value exceeds 255.
Approach: IPv6
::can appear at most once; more than one is invalid (the shorthand would be ambiguous about how many zero groups it represents).- If
::is present, split the string into a "head" and "tail" around it, split each side on:(an empty side yields zero groups, not one empty-string group), and the total number of explicit groups on both sides together must be strictly less than 8 (the whole point of::is to stand in for at least one omitted group). - If
::is absent, splitting on:must yield exactly 8 groups. - Every resulting group must be 1 to 4 hexadecimal digits.
Complexity
Both: O(L) where L is the length of the input string (each character is inspected a constant number of times across the split and per-group checks).
Edge cases
- IPv4 with a leading zero (
"1.1.1.01"): rejected under the standard interview convention, discussed further below. - IPv6 with the
::shorthand at the very start or end ("::1","1::"), or standing alone for all-zero ("::"): all valid, and the head/tail split correctly produces zero groups on the empty side. - A string that looks numeric but isn't a valid address in either format (e.g. too many or too few groups): correctly rejected by both checks, so the overall answer is "neither."
function isValidIPv4(s) {
const parts = s.split(".");
if (parts.length !== 4) return false;
for (const p of parts) {
if (!/^[0-9]+$/.test(p)) return false;
if (p.length > 1 && p[0] === "0") return false;
if (parseInt(p, 10) > 255) return false;
}
return true;
}
function isValidIPv6(s) {
if ((s.match(/::/g) || []).length > 1) return false;
let parts;
if (s.includes("::")) {
const [head, tail] = s.split("::");
const headParts = head ? head.split(":") : [];
const tailParts = tail ? tail.split(":") : [];
if (headParts.length + tailParts.length >= 8) return false;
parts = headParts.concat(tailParts);
} else {
parts = s.split(":");
if (parts.length !== 8) return false;
}
for (const p of parts) {
if (p.length < 1 || p.length > 4) return false;
if (!/^[0-9a-fA-F]+$/.test(p)) return false;
}
return true;
}
const cases = ["172.16.254.1", "256.1.1.1", "1.1.1.1.1", "192.168.0.1",
"2001:0db8:85a3:0000:0000:8a2e:0370:7334", "2001:db8::8a2e:370:7334", "::1", "::"];
for (const c of cases) {
console.log(`${c} -> (${isValidIPv4(c)}, ${isValidIPv6(c)})`);
}
Output (executed, node s59_ip_validate.js):
172.16.254.1 -> (true, false)
256.1.1.1 -> (false, false)
1.1.1.1.1 -> (false, false)
192.168.0.1 -> (true, false)
2001:0db8:85a3:0000:0000:8a2e:0370:7334 -> (false, true)
2001:db8::8a2e:370:7334 -> (false, true)
::1 -> (false, true)
:: -> (false, true)
Each IPv4-shaped input is correctly recognized only as IPv4 ((true, false)), each IPv6-shaped input only as IPv6 ((false, true)), and the malformed 256.1.1.1 / 1.1.1.1.1 cases are correctly rejected as neither.
Trade-offs and pitfalls, grounded against a real parser
I checked this implementation's verdicts against Node's built-in net.isIP() (a mature, spec-driven parser shipped with the runtime this answer targets), as ground truth, over a wider test set that included two intentionally awkward cases. It surfaced one genuine, useful disagreement rather than confirming everything blindly:
const net = require("net");
console.log("1.1.1.01 -> mine:", isValidIPv4("1.1.1.01"), "net.isIP:", net.isIP("1.1.1.01"));
console.log("02001:0db8:85a3:0000:0000:8a2e:0370:7334 -> mine:", isValidIPv6("02001:0db8:85a3:0000:0000:8a2e:0370:7334"), "net.isIP:", net.isIP("02001:0db8:85a3:0000:0000:8a2e:0370:7334"));
console.log("::ffff:1.2.3.4 -> mine:", isValidIPv6("::ffff:1.2.3.4"), "net.isIP:", net.isIP("::ffff:1.2.3.4"));
Output (executed, node s59_parser_check.js):
1.1.1.01 -> mine: false net.isIP: 0
02001:0db8:85a3:0000:0000:8a2e:0370:7334 -> mine: false net.isIP: 0
::ffff:1.2.3.4 -> mine: false net.isIP: 6
- Leading zero and the oversized hex group: no disagreement here, and that itself is worth confirming rather than assuming.
net.isIP("1.1.1.01")returns0(invalid), agreeing with this implementation's rejection; the same is true for the 5-hex-digit IPv6 group. Leading-zero rejection is a deliberate, security-motivated convention: leading zeros in IPv4 octets are genuinely ambiguous across tools (some historically parsed them as octal, so"010"meant 8, not 10), and that exact ambiguity was serious enough that Python's own standard-libraryipaddressmodule was patched (CVE-2021-29921, fixed in Python 3.8.12 / 3.9.5 / 3.10.0a7) to reject any leading-zero octet outright rather than guess, precisely because parser disagreement on this point had been used to bypass IP-based access controls elsewhere. Node'snet.isIPhappens to already enforce the strict reading here, so this specific check doesn't surface a gap, but it would be a mistake to conclude every runtime's built-in parser is this strict; confirm it for whichever one you actually ship against. - A real disagreement:
"::ffff:1.2.3.4"(an IPv4-mapped IPv6 address, RFC 4291 section 2.5.5.2) is accepted bynet.isIPas valid IPv6 (6), but this implementation rejects it (false). The reason is structural, not a bug in the sense of violating the question's own spec: the question defines IPv6 validity as "eight groups of 1-4 hex digits, allowing shorthand::once," and"1.2.3.4"is neither a hex group nor handled by the::-splitting logic, so it correctly falls out of scope for THIS definition. A production-grade validator that needs to accept the full real-world IPv6 address space would need an explicit extra branch recognizing a trailing dotted-quad segment. This is a good example of why "matches a mature real parser" and "matches the question's stated spec" are two different bars, and a candidate should be explicit about which one their implementation is targeting. - A common bug in the IPv6 head/tail split: using
head.split(":")unconditionally, without thehead ? ... : []guard, on an empty head (e.g. for"::1") produces[""](one empty-string "group") instead of[](zero groups), which then incorrectly fails the later 1-to-4-hex-digit check on that phantom empty group. This applies identically in JavaScript and in a straightforward Python port of the same logic.
Implement Kadane's algorithm in Java or Python to compute the maximum subarray sum (contiguous) for a given integer array. Your implementation should handle empty arrays and arrays with all negative numbers correctly and run in O(n) time using O(1) extra space. Explain how to return both the max sum and the subarray indices.
Sample Answer
Direct answer
Kadane's algorithm tracks the best sum ending exactly at the current index, resetting it whenever it goes negative, which gives O(n) time and O(1) extra space. Extend it with a couple of extra index variables to also recover the winning subarray's start and end, and treat an empty input as an explicit error rather than guessing a placeholder value.
Structured elaboration
- State.
current_sum: best sum of a subarray ending at the current index.best_sum: best seen anywhere so far. - Reset rule. If
current_sumgoes negative, it can never help a future subarray (adding a negative running total only hurts the next element), so restart at the current element. This is what makes the algorithm handle an all-negative array correctly, PROVIDED you initializebest_sumandcurrent_sumwithnums[0], not0. - The classic initialization bug. Initializing
best_sum = 0silently treats the empty subarray as a legal candidate. For an all-negative array like[-3, -1, -4, -1, -5], the true best NON-EMPTY subarray sum is-1(the single element-1), but a0-initialized version would wrongly report0, implying an empty subarray beats every real one. Most interview phrasings (this one included) require a non-empty subarray, so seed with the first element. - Recovering indices. Track
current_start(where the current running sum began) alongsidecurrent_sum; whenevercurrent_sumresets,current_startmoves to the current index. Whenevercurrent_sumbeatsbest_sum, copycurrent_startand the current index intobest_start/best_end. - Empty array. There is no subarray to return, so raise explicitly rather than returning
0orNone, which would look like a valid (and wrong) answer to a caller who doesn't check.
Worked example
def max_subarray(nums):
if not nums:
raise ValueError("max_subarray: input array must be non-empty")
best_sum = current_sum = nums[0]
best_start = best_end = 0
current_start = 0
for i in range(1, len(nums)):
if current_sum < 0:
current_sum = nums[i]
current_start = i
else:
current_sum += nums[i]
if current_sum > best_sum:
best_sum = current_sum
best_start = current_start
best_end = i
return best_sum, best_start, best_end
def max_subarray_brute_force(nums):
n = len(nums)
best = nums[0]
for i in range(n):
s = 0
for j in range(i, n):
s += nums[j]
if s > best:
best = s
return best
cases = [
[-2, 1, -3, 4, -1, 2, 1, -5, 4],
[-3, -1, -4, -1, -5],
[5],
[2, 2, 2],
]
for nums in cases:
best_sum, start, end = max_subarray(nums)
brute = max_subarray_brute_force(nums)
print(f"nums={nums} -> best_sum={best_sum}, subarray={nums[start:end+1]}, indices=({start},{end}), brute_force={brute}")
assert best_sum == brute
try:
max_subarray([])
except ValueError as e:
print(f"empty input raised ValueError as expected: {e}")
print("brute-force cross-check passed for all cases")
Output (executed, python3 s62_kadane.py, also cross-checked against an O(n^2) brute force for every case):
nums=[-2, 1, -3, 4, -1, 2, 1, -5, 4] -> best_sum=6, subarray=[4, -1, 2, 1], indices=(3,6), brute_force=6
nums=[-3, -1, -4, -1, -5] -> best_sum=-1, subarray=[-1], indices=(1,1), brute_force=-1
nums=[5] -> best_sum=5, subarray=[5], indices=(0,0), brute_force=5
nums=[2, 2, 2] -> best_sum=6, subarray=[2, 2, 2], indices=(0,2), brute_force=6
empty input raised ValueError as expected: max_subarray: input array must be non-empty
brute-force cross-check passed for all cases
Trade-offs & pitfalls
- Seeding
best_sum = 0is the single most common bug on this problem; always test against an all-negative array to catch it (as above). - Deciding whether the empty subarray is a legal answer is a real design decision, not a formality; state the assumption up front rather than let the code's default silently pick one.
- The state above is O(1) beyond the input, so it also works directly on a stream you can only scan once, but you cannot recover the ORIGINAL array's earlier indices after the fact unless you kept them as you went, which is exactly what
current_start/best_startalready do here at no extra asymptotic cost. - A Java port of this same logic is a straightforward, mechanical translation (three
intlocals instead of Python variables, an explicitIllegalArgumentExceptionin place of theValueError); nothing about the algorithm changes across the two languages.
Implement partition(arr, predicate) with two variants: (1) an in-place O(1) extra space partition that reorders elements matching predicate before the rest (relative order not guaranteed), and (2) a variant that preserves the original relative order of both groups. Provide Python implementations and discuss the trade-offs between the two, including whether O(1) extra space and order-preservation can be achieved simultaneously.
Sample Answer
Direct answer
Two clean variants exist. Variant 1, in-place, O(1) extra space: a single write-pointer pass that swaps every element satisfying the predicate to the front; O(n) time, O(1) extra space, but does NOT preserve relative order within either group. Variant 2, order-preserving: build two lists (matched, unmatched) in a single pass and concatenate them; O(n) time, O(n) extra space, and DOES preserve relative order. In general, O(1) extra space and stability cannot both be had in O(n) time; achieving both simultaneously needs O(n log n) time instead, the same trade-off behind why C++'s std::stable_partition switches to a slower algorithm specifically when it cannot get extra memory.
Structured elaboration
Variant 1 mechanics (swap-based partition). Maintain a write pointer starting at 0. Scan read from 0 to n-1; whenever predicate(arr[read]) holds, swap arr[write] and arr[read], then increment write. After the scan, everything before write satisfies the predicate and everything from write onward does not, but a swap can move an unmatched element out of its original relative position among other unmatched elements (or vice versa for matched elements).
Variant 2 mechanics. A single pass builds two separate lists, matched and unmatched, in original encounter order, then concatenates them. Correctness is immediate: each list is built purely by appends in scan order, and appends never reorder elements relative to each other within their own list.
Can O(1) space and stability be achieved together? Yes, but not in O(n) time. A divide-and-conquer approach recursively stable-partitions each half of the array, then merges the two halves' now-partitioned matched and unmatched runs using an in-place rotation (rotation itself can be done with O(1) extra space via the three-reversals trick, in time proportional to the rotated range). This gives the recurrence T(n) = 2T(n/2) + O(n), which solves to O(n log n) time with O(1) extra space (or O(log n) if counting recursion-stack space). This mirrors exactly what C++'s standard library documents for std::stable_partition: O(n) swaps when extra memory is available for a temporary buffer, up to O(n log n) swaps if allocation fails and it must fall back to in-place. It is a genuine impossibility result at O(n) time: you cannot have in-place (O(1) space), stable, AND O(n) time simultaneously for a general predicate-based partition; you must give up exactly one of the three.
Worked example
def partition_inplace_unstable(arr, predicate):
'''O(1) extra space, O(n) time. Relative order NOT guaranteed.'''
write = 0
for read in range(len(arr)):
if predicate(arr[read]):
arr[write], arr[read] = arr[read], arr[write]
write += 1
def partition_stable(arr, predicate):
'''O(n) extra space, O(n) time. Preserves relative order in each group.'''
matched = [x for x in arr if predicate(x)]
unmatched = [x for x in arr if not predicate(x)]
return matched + unmatched
data = [1, 4, 2, 7, 3, 8, 5, 9, 6] # pinned
is_even = lambda x: x % 2 == 0
unstable_copy = data.copy()
partition_inplace_unstable(unstable_copy, is_even)
print("input =", data)
print("unstable in-place result =", unstable_copy)
stable_result = partition_stable(data, is_even)
print("stable (extra space) =", stable_result)
evens_in_order = [x for x in data if is_even(x)]
odds_in_order = [x for x in data if not is_even(x)]
print("stability check (evens):", stable_result[:len(evens_in_order)] == evens_in_order)
print("stability check (odds): ", stable_result[len(evens_in_order):] == odds_in_order)
evens_after_unstable = [x for x in unstable_copy if is_even(x)]
odds_after_unstable = [x for x in unstable_copy if not is_even(x)]
print("unstable evens order matches original order?", evens_after_unstable == evens_in_order)
print("unstable odds order matches original order? ", odds_after_unstable == odds_in_order)
Output:
input = [1, 4, 2, 7, 3, 8, 5, 9, 6]
unstable in-place result = [4, 2, 8, 6, 3, 1, 5, 9, 7]
stable (extra space) = [4, 2, 8, 6, 1, 7, 3, 5, 9]
stability check (evens): True
stability check (odds): True
unstable evens order matches original order? True
unstable odds order matches original order? False
The stable variant preserves order for BOTH groups, as guaranteed. The unstable variant's evens [4, 2, 8, 6] happen to keep their original relative order for this particular input, but the odds group does not: it ends as [3, 1, 5, 9, 7] instead of the original relative order [1, 7, 3, 5, 9]. That asymmetry is instructive: instability is not a guarantee that EVERY group gets scrambled, it is the absence of a guarantee that ANY group stays in order, and this input concretely demonstrates the odds group breaking.
Trade-offs and pitfalls
- The three-way trade-off (space, stability, time) is the deep point of this question: claiming the swap-based partition is "basically the same as the stable one, just in place" misses that the relative-order guarantee is genuinely lost, not merely an implementation detail.
- A common bug is forgetting to swap (writing
arr[write] = arr[read]instead) in the O(1)-space version, which overwrites and destroys data rather than reordering it; this only works if discarding the unmatched values is acceptable, otherwise a real swap is required. - The O(n)-space stable variant needs no swapping subtlety at all; that simplicity is itself a valid engineering argument, plenty of real systems accept O(n) extra space for a partition specifically to keep the code obviously correct.
- Do not assume "in-place" always means "faster": the swap-based version is not asymptotically faster than the two-list version, both are O(n) time, it only saves memory, and if that memory saving is not needed, the added subtlety may not be worth it.
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).
You are given an array of n+1 integers where each value is between 1 and n (inclusive). Prove and implement an algorithm to find a duplicate value in O(n) time and O(1) extra space without modifying the array. (Hint: use cycle detection/floyd's algorithm treating indices as pointers.)
Sample Answer
Direct answer
Treat each value in the array as a pointer: from index i, "follow" nums[i] to land on index nums[i]. Because there are n+1 values all in the range [1, n], at least two different indices must point to the same value (pigeonhole), which means this functional graph has a cycle, and the duplicate value is exactly the entry point of that cycle. Floyd's tortoise-and-hare cycle detection finds that entry point in O(n) time and O(1) extra space, without modifying the array at all, which is exactly what the question asks for.
Approach (Floyd's cycle detection)
- Start both
slowandfastatnums[0], i.e. one step into the implicit linked structure (index 0 always has an outgoing "pointer," but nothing points back to it, so it can't be part of the cycle itself, only the tail leading into it). - Advance
slowone step (slow = nums[slow]) andfasttwo steps (fast = nums[nums[fast]]) each iteration until they meet; a meeting point is guaranteed to exist since the structure has a cycle (standard tortoise-and-hare argument). - Reset a second pointer to index 0, then advance it and
slowone step at a time together; the index where they meet is the cycle's entry point, which is the duplicate value.
Complexity
Time: O(n) (each phase does at most O(n) steps). Space: O(1) extra; nums itself is never modified.
Edge cases
- Exactly one duplicate value, appearing exactly twice: this is the assumed input shape and the algorithm handles it directly.
- The duplicate value equal to
nitself (the largest allowed value): handled the same way, since indexing is 0-based but values start at 1, sonums[i]is always a valid index regardless of which value 1..n is duplicated.
def find_duplicate_floyd(nums):
slow = nums[0]
fast = nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
slow2 = 0
while slow2 != slow:
slow2 = nums[slow2]
slow = nums[slow]
return slow
data = [1, 3, 4, 2, 2]
original = list(data)
print(find_duplicate_floyd(data), data == original)
Output:
2 True
The duplicate is correctly identified as 2, and data == original confirms the array was never mutated during the search.
Alternative technique: index-marking
A second valid approach exploits the same "values are indices" fact differently: walk the array once, and for each value, negate the entry at the index that value points to (abs(value) - 1). If you ever land on an index whose entry is already negative, that index (converted back to 1-based) is the duplicate, because it means two different positions "pointed" to it. This is also O(n) time and O(1) additional space, but unlike Floyd's approach, it works by temporarily mutating nums in place (each visited value's target slot gets negated), so if the caller needs nums to remain externally unmodified while the function runs (not just restored by the time it returns), Floyd's version is the safer default.
def find_duplicate_marking(nums):
duplicate = None
for x in nums:
idx = abs(x) - 1
if nums[idx] < 0:
duplicate = idx + 1
break
nums[idx] = -nums[idx]
for i in range(len(nums)):
nums[i] = abs(nums[i])
return duplicate
data2 = [1, 3, 4, 2, 2]
print(find_duplicate_marking(data2), data2)
Output:
2 [1, 3, 4, 2, 2]
Both techniques agree on the duplicate (2), and the marking approach restores the array to its original values by the time it returns, even though it mutated it during the scan.
Trade-offs and pitfalls
- "Does not modify the array" has two readings, and the question's phrasing ("without modifying the array") most naturally means Floyd's guarantee: never mutated, at any point, including during execution. The marking approach only satisfies a weaker version ("unmodified once the function returns"), which is a meaningful difference if another thread could read
numsconcurrently while this function runs, or if the function could throw partway through and leave the array in its negated state. - A frequent proof gap: candidates often reach for cycle detection without first establishing why a cycle must exist here. The argument is exactly pigeonhole: n+1 values drawn from a range of only n possible values guarantees at least one repeat, and because every value is a valid index (never 0, since the range is [1, n] not [0, n-1]), the "value points to index" structure is well-defined for every position, forcing at least one node in the sequence to be revisited, i.e. a cycle.
- A common bug in the marking approach: forgetting the final restoration pass, which silently corrupts the caller's array (still functionally finds the right duplicate, but violates the "don't modify the array" requirement in a way that's easy to overlook if you only test the return value).
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.