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 in nums,
  • "first_index": the 0-based index of "value"'s earliest appearance in nums.

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 nums may be negative, zero, or arbitrarily large Python integers.
  • Must run in O(n) average time and O(k) extra space (k = distinct values in nums), leaving nums unchanged.

Step-by-step walkthrough

  1. 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 across nums, - "first_index": the 0-based index of its earliest occurrence in nums.

    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]) that 6's second copy arrives at index 5 before -4's second copy at index 8, yet -4 must come before 6 because -4 first appeared at index 1 < 2. Any number occurring once is omitted, so an empty or all-unique list returns [].

  2. Why scanning repeatedly is too slow

    A direct beginner attempt checks each index i, scans nums[:i] to make sure we have not already reported nums[i], and then calls nums.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] and nums.count(...) walk across the list from scratch. Doing an O(n) scan at every one of the n indices costs O(n^2) operations — for n = 1,000,000, that is roughly 1,000,000,000,000 comparisons.

    To handle large inputs cleanly, we gather counts and earliest indices in one pass (O(n) average time).

  3. Key idea: track count and first index in a dictionary

    As we walk through nums from left to right, only two pieces of information matter for each distinct number: 1. Its count, which starts at 1 the first time we see it and goes up by 1 on 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 store value -> [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 stats at the end visits distinct values in first_index order automatically — no sorting required! (In a language whose hash map is unordered, you would simply append each newly discovered value to a side list order.)

  4. Phase 1: Count every number in one pass

    We walk nums using enumerate(nums) so we have both index and value at each step. Notice why index is only written in the else branch: once a key exists in stats, its first_index at stats[value][1] is locked in forever, and later copies only bump stats[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]
    
  5. Phase 2: Filter for duplicates in first-occurrence order

    Now we loop through stats.items(). Because keys stay in insertion order, first_index is already strictly increasing from one item to the next. We check count > 1 so 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,
            })
    
  6. 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     -> skip
    
  7. Complete solution

    Putting both phases inside find_duplicates gives the complete O(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 the n elements once and performs one O(1) average-time dictionary lookup and update per step; Phase 2 loops once over the k distinct entries in stats (k <= n), with no sorting step needed.
  • Space: O(k) extra. stats stores one [count, first_index] pair for each of the k distinct values, and the returned duplicates list holds at most min(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, so duplicates comes back as [].
  • All unique values ([10, -2, 0, 15, 3], Example 3): Every entry in stats ends with count == 1, so Phase 2 filters all of them out and returns [].
  • All identical values ([-7, -7, -7, -7], Example 2): stats holds a single key (k = 1), using O(1) space and returning [{"value": -7, "count": 4, "first_index": 0}].
  • Negative numbers and zero: Negative integers and 0 hash just like positive integers; 2 and -2 are 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): -4 precedes 6 because -4 appeared at index 1 < 2, even though 6 reached count 2 earlier at index 5.

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 than first_index (emitting 6 before -4 in Example 1).
  • Sorting the output by value or by count: The problem rule requires first-appearance order (first_index ascending), not numeric order or most-frequent-first.
  • Overwriting first_index on later occurrences: Updating [count + 1, index] on every hit turns first_index into last_index; only set index when value not in stats.
  • Calling nums.index(value) after counting with Counter: Each .index() call does a linear scan from the start of nums, turning an O(n) algorithm into O(n * d) when d distinct values repeat.
  • Mutating nums in place when not asked: Sorting nums directly destroys first_index and 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 holds first_index and whose length gives count. You then sort the duplicate records back by first_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 of O(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 index i, extract the original value val = nums[i] % n and add n to nums[val]; after pass 1, nums[v] // n equals the exact count of v, while nums[v] % n preserves the original nums[v]. In pass 2, scan i from 0 to n - 1 so every value is visited at its first_index; whenever nums[val] // n > 1, append (val, nums[val] // n, i) and reset nums[val] %= n so its quotient drops to 0 and later copies are skipped without breaking future % n reads. Pass 3 executes nums[i] %= n to restore the caller's array. Negatives work in O(1) space only if all values fall inside a bounded span [lo, lo + n - 1] of width at most n (shift every element by -lo before counting and +lo afterward); if values span a wider interval than n, 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 file hash(value) % B on disk so equal integers always land in the same shard; then load one shard at a time into our in-memory stats dictionary, emit (first_index, value, count) for count > 1, and finish with an external merge sort on first_index. Notice why a Count-Min Sketch (a fixed-size d x w grid of hash counters estimating item frequencies without storing keys) fails to isolate count-2 items: with width w = ceil(e / eps) and depth d = ceil(ln(1 / delta)), its additive error bound is 0 <= estimate - true_count <= eps * n with probability >= 1 - delta, so distinguishing 1 from 2 requires eps * n < 1, i.e. w > e * n counters — 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 rate p) works far better when duplicates are sparse and the stream is replayable: pass 1 uses ~9.6 bits per distinct key (~120 MB at p = 1% for 10^8 items) 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 and O(k) space while preserving first_index naturally, but pathological hash collisions can degrade runtime to O(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) guarantees O(n log n) worst-case time in O(1) extra space with sequential, cache-friendly scans, though sorting raw integers erases first_index unless you sort (value, index) tuples in O(n) space. Bitsets (contiguous bit arrays where bit v tracks integer v directly) take deterministic O(U) space and setup time over domain size U with zero collisions (2 bitsets of 2^32 bits = 1 GiB total 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

Similar questions

More TCS interview questions

All 2 TCS questions →