Report Repeated Integers in First-Appearance Order
Medium · Coding & Algorithms · Data Scientist · Technical Screen
Problem Statement
Implement find_duplicates(nums) to identify every integer that appears at least twice inside a potentially large list nums (which may contain negative integers, zero, and arbitrarily large integers).
For each repeated value, return a dictionary with three keys:
"value": the repeated integer itself,"count": the total number of times"value"occurs innums,"first_index": the 0-based index of"value"'s earliest appearance innums.
Return the dictionaries in strictly increasing order of "first_index" (matching the order in which each duplicate value was first encountered when scanning nums from left to right), without mutating nums. Aim for O(n) average time and O(k) extra space, where n = len(nums) and k is the count of distinct integers in nums.
def find_duplicates(nums: List[int]) -> List[Dict[str, int]]:
Examples
Example 1
Input: nums = [8, -4, 6, 8, 0, 6, 8, 12, -4]
Output:
[
{"value": 8, "count": 3, "first_index": 0},
{"value": -4, "count": 2, "first_index": 1},
{"value": 6, "count": 2, "first_index": 2},
]
Explanation: 8 occurs at indices 0, 3, 6 (count = 3, first_index = 0), -4 occurs at indices 1, 8 (count = 2, first_index = 1), and 6 occurs at indices 2, 5 (count = 2, first_index = 2). Singletons 0 and 12 are omitted, and -4 precedes 6 because -4 appeared earlier at index 1 < 2 even though 6's second copy arrived sooner at index 5.
Example 2
Input: nums = [-7, -7, -7, -7]
Output:
[{"value": -7, "count": 4, "first_index": 0}]
Explanation: Only one distinct integer -7 is present, occurring 4 times starting at index 0.
Example 3
Input: nums = [10, -2, 0, 15, 3]
Output:
[]
Explanation: Every integer appears once, so no duplicates exist and [] is returned.
Constraints
0 <= len(nums) <= 2 * 10^5- Elements of
numsmay be negative, zero, or arbitrarily large Python integers. - Must run in
O(n)average time andO(k)extra space (k= distinct values innums), leavingnumsunchanged.
Step-by-step walkthrough
Understand the goal and output order
We receive a list of integers
nums(which may include negative values, zero, or arbitrarily large integers) and need to report every distinct integer that occurs at least twice.For each repeated integer, we return a dictionary with three keys: -
"value": the integer itself, -"count": how many times it occurs acrossnums, -"first_index": the 0-based index of its earliest occurrence innums.The returned list must keep entries in strictly increasing order of
first_index. Notice in Example 1 ([8, -4, 6, 8, 0, 6, 8, 12, -4]) that6's second copy arrives at index5before-4's second copy at index8, yet-4must come before6because-4first appeared at index1 < 2. Any number occurring once is omitted, so an empty or all-unique list returns[].Why scanning repeatedly is too slow
A direct beginner attempt checks each index
i, scansnums[:i]to make sure we have not already reportednums[i], and then callsnums.count(nums[i])to count all occurrences.That gives the right order, because we only act on the first copy of each value. However, both
nums[i] in nums[:i]andnums.count(...)walk across the list from scratch. Doing anO(n)scan at every one of thenindices costsO(n^2)operations — forn = 1,000,000, that is roughly1,000,000,000,000comparisons.To handle large inputs cleanly, we gather counts and earliest indices in one pass (
O(n)average time).Key idea: track count and first index in a dictionary
As we walk through
numsfrom left to right, only two pieces of information matter for each distinct number: 1. Its count, which starts at1the first time we see it and goes up by1on every later match. 2. Its first index, which is recorded the very first time we see it and never changes afterward.A dictionary (also called a hash map, a data structure that looks up keys by their hash code in
O(1)average time) lets us storevalue -> [count, first_index]as we scan.Even better, since Python 3.7, dictionaries iterate over keys in the exact order those keys were first inserted:
Input: [9, 1, 1, 9, 5] Insert 9 at idx 0 -> stats = {9: [1, 0]} Insert 1 at idx 1 -> stats = {9: [1, 0], 1: [1, 1]} Update 1 at idx 2 -> stats = {9: [1, 0], 1: [2, 1]} (order stays 9, then 1) Update 9 at idx 3 -> stats = {9: [2, 0], 1: [2, 1]} (first_index of 9 stays 0) Insert 5 at idx 4 -> stats = {9: [2, 0], 1: [2, 1], 5: [1, 4]}Because each key is inserted at its first occurrence, iterating over
statsat the end visits distinct values infirst_indexorder automatically — no sorting required! (In a language whose hash map is unordered, you would simply append each newly discovered value to a side listorder.)Phase 1: Count every number in one pass
We walk
numsusingenumerate(nums)so we have bothindexandvalueat each step. Notice whyindexis only written in theelsebranch: once a key exists instats, itsfirst_indexatstats[value][1]is locked in forever, and later copies only bumpstats[value][0].stats: Dict[int, List[int]] = {} # Phase 1: Scan the list once to count occurrences and lock in each value's first index. for index, value in enumerate(nums): if value in stats: # Seen before: increment the count, but leave first_index untouched. stats[value][0] += 1 else: # First sight of this value: record count 1 and its earliest index. stats[value] = [1, index]Phase 2: Filter for duplicates in first-occurrence order
Now we loop through
stats.items(). Because keys stay in insertion order,first_indexis already strictly increasing from one item to the next. We checkcount > 1so values that appeared only once are skipped, and build the required output dictionaries.# Phase 2: Walk the dictionary in insertion (first-occurrence) order and filter duplicates. duplicates: List[Dict[str, int]] = [] for value, entry in stats.items(): count, first_index = entry # Strictly greater than 1: values seen only once are not duplicates. if count > 1: duplicates.append({ "value": value, "count": count, "first_index": first_index, })Walk through Example 1 step by step
Let's trace
nums = [8, -4, 6, 8, 0, 6, 8, 12, -4]from start to finish:idx value action stats (value: [count, first_index]) --- ----- ------------------ --------------------------------------------------------- 0 8 new key (idx 0) {8: [1, 0]} 1 -4 new key (idx 1) {8: [1, 0], -4: [1, 1]} 2 6 new key (idx 2) {8: [1, 0], -4: [1, 1], 6: [1, 2]} 3 8 bump count of 8 {8: [2, 0], -4: [1, 1], 6: [1, 2]} 4 0 new key (idx 4) {8: [2, 0], -4: [1, 1], 6: [1, 2], 0: [1, 4]} 5 6 bump count of 6 {8: [2, 0], -4: [1, 1], 6: [2, 2], 0: [1, 4]} 6 8 bump count of 8 {8: [3, 0], -4: [1, 1], 6: [2, 2], 0: [1, 4]} 7 12 new key (idx 7) {8: [3, 0], -4: [1, 1], 6: [2, 2], 0: [1, 4], 12: [1, 7]} 8 -4 bump count of -4 {8: [3, 0], -4: [2, 1], 6: [2, 2], 0: [1, 4], 12: [1, 7]} Filter stats for count > 1 (in insertion order 8, -4, 6, 0, 12): 8 -> count 3 > 1 -> keep {"value": 8, "count": 3, "first_index": 0} -4 -> count 2 > 1 -> keep {"value": -4, "count": 2, "first_index": 1} 6 -> count 2 > 1 -> keep {"value": 6, "count": 2, "first_index": 2} 0 -> count 1 -> skip 12 -> count 1 -> skipComplete solution
Putting both phases inside
find_duplicatesgives the completeO(n)time,O(k)space solution:from typing import Any, Dict, List, Optional, Set, Tuple def find_duplicates(nums: List[int]) -> List[Dict[str, int]]: # stats: hash map from value -> [occurrence_count, first_index], e.g. {8: [3, 0]} # Python dicts preserve key insertion order, which matches first-occurrence order. stats: Dict[int, List[int]] = {} # Phase 1: Scan the list once to count occurrences and lock in each value's first index. for index, value in enumerate(nums): if value in stats: # Seen before: increment the count, but leave first_index untouched. stats[value][0] += 1 else: # First sight of this value: record count 1 and its earliest index. stats[value] = [1, index] # Phase 2: Walk the dictionary in insertion (first-occurrence) order and filter duplicates. duplicates: List[Dict[str, int]] = [] for value, entry in stats.items(): count, first_index = entry # Strictly greater than 1: values seen only once are not duplicates. if count > 1: duplicates.append({ "value": value, "count": count, "first_index": first_index, }) return duplicates✅ Submit now — all tests should pass.
Intuition & how it works
Imagine checking guests in at the door of a busy event where people can leave and re-enter several times. The first time a guest walks in, you write their name on the next blank line of a clipboard alongside their arrival number and draw one tally mark. Whenever that same guest walks in again later, you find their line, add one tally mark, and leave their original line position and arrival number untouched. At the end of the night, reading down the clipboard from top to bottom and skipping anyone with just one tally mark gives you every repeat guest, their total entries, and when they first arrived — already in exact first-arrival order.
Why does the naive approach fall short? Checking each element by scanning earlier elements (nums[i] in nums[:i]) and calling nums.count(nums[i]) rescans the list inside a loop, taking O(n^2) time — roughly a trillion operations for a million numbers. Even counting frequencies with collections.Counter first and then calling nums.index(value) on every duplicate still scans the list from index 0 for each duplicate, degrading back toward O(n^2) when thousands of distinct numbers repeat.
Instead, we use a hash map (dict in Python — a key-value table that finds or updates any key in O(1) average time using a hash function) mapping value -> [count, first_index]. Because Python dictionaries remember the insertion order of keys (the chronological order in which distinct keys were first added), a quick trace on [8, -4, 6, 8, 6, -4] (trimmed from Example 1) shows how insertion order preserves first_index even when 6 repeats before -4:
idx 0 (val 8): new -> stats = {8: [1, 0]}
idx 1 (val -4): new -> stats = {8: [1, 0], -4: [1, 1]}
idx 2 (val 6): new -> stats = {8: [1, 0], -4: [1, 1], 6: [1, 2]}
idx 3 (val 8): hit -> stats = {8: [2, 0], -4: [1, 1], 6: [1, 2]}
idx 4 (val 6): hit -> stats = {8: [2, 0], -4: [1, 1], 6: [2, 2]}
idx 5 (val -4): hit -> stats = {8: [2, 0], -4: [2, 1], 6: [2, 2]}
Keep entries with count > 1 in insertion order:
-> [{"value": 8, "count": 2, "first_index": 0},
{"value": -4, "count": 2, "first_index": 1},
{"value": 6, "count": 2, "first_index": 2}]
Complexity
Let n be len(nums) and k be the number of distinct integers in nums (k <= n).
- Time:
O(n)average. Phase 1 visits each of thenelements once and performs oneO(1)average-time dictionary lookup and update per step; Phase 2 loops once over thekdistinct entries instats(k <= n), with no sorting step needed. - Space:
O(k)extra.statsstores one[count, first_index]pair for each of thekdistinct values, and the returnedduplicateslist holds at mostmin(k, n // 2)dictionaries because every duplicate consumes at least two input slots.
Edge cases
- Empty list (
[]) or single element ([7]): No value can appear twice, soduplicatescomes back as[]. - All unique values (
[10, -2, 0, 15, 3], Example 3): Every entry instatsends withcount == 1, so Phase 2 filters all of them out and returns[]. - All identical values (
[-7, -7, -7, -7], Example 2):statsholds a single key (k = 1), usingO(1)space and returning[{"value": -7, "count": 4, "first_index": 0}]. - Negative numbers and zero: Negative integers and
0hash just like positive integers;2and-2are distinct keys with separate counts. - Arbitrarily large integers (
10**20): Python integers have arbitrary precision and hash cleanly without 64-bit overflow. - First-occurrence tie-breaking (
[8, -4, 6, 8, 0, 6, 8, 12, -4], Example 1):-4precedes6because-4appeared at index1 < 2, even though6reached count2earlier at index5.
Common mistakes
- Emitting duplicates as soon as
count == 2: Appending a value the moment you see its second copy orders output by second index rather thanfirst_index(emitting6before-4in Example 1). - Sorting the output by value or by count: The problem rule requires first-appearance order (
first_indexascending), not numeric order or most-frequent-first. - Overwriting
first_indexon later occurrences: Updating[count + 1, index]on every hit turnsfirst_indexintolast_index; only setindexwhenvalue not in stats. - Calling
nums.index(value)after counting withCounter: Each.index()call does a linear scan from the start ofnums, turning anO(n)algorithm intoO(n * d)whenddistinct values repeat. - Mutating
numsin place when not asked: Sortingnumsdirectly destroysfirst_indexand alters the caller's list.
Alternative approaches
- Sort
(value, original_index)pairs (O(n log n)time,O(n)space): Pairing each element with its index and sorting groups identical values into contiguous runs whose first pair holdsfirst_indexand whose length givescount. You then sort the duplicate records back byfirst_index. This avoids hashing altogether (useful when worst-case hash collisions are a concern or data lives in sorted runs on disk), at the cost ofO(n log n)time.
Follow-up questions
- When every element lies in 0..n-1 and mutating the input array is permitted, how can you run in O(n) time with O(1) auxiliary space, and when can this handle negative numbers? Use modular counting (encoding two integers inside one array slot using quotient and remainder when dividing by
n). In pass 1, for each indexi, extract the original valueval = nums[i] % nand addntonums[val]; after pass 1,nums[v] // nequals the exact count ofv, whilenums[v] % npreserves the originalnums[v]. In pass 2, scanifrom0ton - 1so every value is visited at itsfirst_index; whenevernums[val] // n > 1, append(val, nums[val] // n, i)and resetnums[val] %= nso its quotient drops to0and later copies are skipped without breaking future% nreads. Pass 3 executesnums[i] %= nto restore the caller's array. Negatives work inO(1)space only if all values fall inside a bounded span[lo, lo + n - 1]of width at mostn(shift every element by-lobefore counting and+loafterward); if values span a wider interval thann, the pigeonhole principle leaves too few array slots to serve as counters.
python
def find_duplicates_in_place(nums: List[int]) -> List[Dict[str, int]]:
n = len(nums)
for i in range(n):
nums[nums[i] % n] += n
duplicates = []
for i in range(n):
val = nums[i] % n
count = nums[val] // n
if count > 1:
duplicates.append({"value": val, "count": count, "first_index": i})
nums[val] %= n # drops quotient to 0 ("already reported") while keeping original value
for i in range(n):
nums[i] %= n
return duplicates
- How would you process a stream of 10^8 integers that exceeds available RAM, and why do frequency sketches struggle to separate count 1 from count 2? For an exact bounded-RAM solution, apply hash partitioning to disk: stream through the input once and append each
(value, index)pair to shard filehash(value) % Bon disk so equal integers always land in the same shard; then load one shard at a time into our in-memorystatsdictionary, emit(first_index, value, count)forcount > 1, and finish with an external merge sort onfirst_index. Notice why a Count-Min Sketch (a fixed-sized x wgrid of hash counters estimating item frequencies without storing keys) fails to isolate count-2items: with widthw = ceil(e / eps)and depthd = ceil(ln(1 / delta)), its additive error bound is0 <= estimate - true_count <= eps * nwith probability>= 1 - delta, so distinguishing1from2requireseps * n < 1, i.e.w > e * ncounters — more memory than holding the raw stream! A Bloom filter (a compact bit vector using multiple hash functions with zero false negatives and tunable false-positive ratep) works far better when duplicates are sparse and the stream is replayable: pass 1 uses ~9.6 bits per distinct key (~120 MBatp = 1%for10^8items) to collect candidate repeats, and pass 2 counts only those candidates exactly. - How do hash tables, in-place sorting, and bitsets compare in worst-case runtime, memory layout, and CPU cache behavior? Hash tables achieve
O(n)average time andO(k)space while preservingfirst_indexnaturally, but pathological hash collisions can degrade runtime toO(n * k)worst case, and scattered bucket probes trigger frequent CPU cache misses (stalls when memory accesses jump outside fast on-chip cache) once the table exceeds L3 cache. In-place sorting (like heapsort) guaranteesO(n log n)worst-case time inO(1)extra space with sequential, cache-friendly scans, though sorting raw integers erasesfirst_indexunless you sort(value, index)tuples inO(n)space. Bitsets (contiguous bit arrays where bitvtracks integervdirectly) take deterministicO(U)space and setup time over domain sizeUwith zero collisions (2bitsets of2^32bits =1 GiBtotal detect all 32-bit repeats in one pass before counting them), excelling on dense bounded integer domains while remaining impractical across sparse 64-bit ranges.
Follow-up questions
- When every element lies in 0..n-1 and mutating the input array is permitted, how can you run in O(n) time with O(1) auxiliary space, and when can this handle negative numbers?
- How would you process a stream of 10^8 integers that exceeds available RAM, and why do frequency sketches struggle to separate count 1 from count 2?
- How do hash tables, in-place sorting, and bitsets compare in worst-case runtime, memory layout, and CPU cache behavior?
Similar questions
- Joins, Data Blending, and Filter Order in Tableau
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One