AlgoTales · Roadmap

Duplicate detection

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Duplicate detection means noticing that you have seen the same item before. You keep a set of items already seen and check each new one against it in a single step, instead of comparing it with everything before it.

Practical use cases

  • Web app: Stopping a double payment. On a slow network a user taps Pay twice, and two identical requests reach your server. Each request carries a unique token, and the server keeps the tokens already processed in a set. The second request is recognised right away and ignored, so the customer is charged once.
  • Web app: Duplicate email at sign-up. A registration form must refuse an email that already has an account. Looking it up in a set or an indexed column answers immediately, without reading all 2 lakh users. The user sees "already registered" as soon as they leave the field.
  • Web app: Cleaning an imported spreadsheet. A CSV import of products may contain the same SKU on many rows. Adding each SKU to a set while reading lets the importer skip repeats and list them in a short report for the admin. A 50,000-row file is cleaned in one pass, instead of silently ending up with doubled stock numbers.
  • System: Web crawler. A search crawler keeps every page address it has visited in a set, so it never downloads the same page twice or walks in circles when two pages link to each other. Each new link costs one quick check, even after millions of pages have been seen.

The story: The Double Entry at the Exam Hall

It was the board-exam morning and Mrs. Sharma stood at the gate of the exam hall with the register. Students called out their roll numbers: 4, 2, 9, 7... Her job was to catch anyone trying to enter twice, since a nervous student had once sneaked in with a friend's admit card.

Her first method was to compare every new roll number with every earlier one on her list. By the 300th student she was comparing 300 numbers each time, and the queue stretched down the road. A peon named Dhanraj offered a trick: "Madam, hang each roll number on a numbered hook as it enters. For a new student, look at their hook. If it is already occupied, that number came before."

The hook board is a hash set. Each check is one jump: is this number already on its hook? If yes, you have a duplicate; if no, hang it and let the student in. Mrs. Sharma finished the check in one pass, and the first imposter was caught on the spot. That is duplicate detection: remembering what you have seen in a set, so that a repeat shows up immediately.

How to spot this problem, and where you need it

The same thing keeps arriving more than once, such as a user, a request or a row, and you need to catch the repeat quickly without comparing against every earlier item.

Signs you need it

  • Customers complain about being charged twice, getting two emails or seeing the same item listed again.
  • Your code compares each new item against all earlier ones with a loop, and imports take longer and longer.
  • The problem says "contains duplicate", "first repeating element" or "unique values".

Where to use it in a project

  • Payment and order endpoints using idempotency keys so retries do not create a second order.
  • Sign-up, import, and crawling features where every incoming item must be checked against what is already known.

The solution

Keep a set, which answers "have I seen this?" in a single step. For each incoming item, check the set first. If it is already there, it is a duplicate: skip it or reject it. If not, add it and carry on. For databases, the same idea is a unique index on the column. For distributed apps, store the keys in Redis with an expiry.

Payoff: Before: each new row compared with all earlier rows, minutes for a big file. After: one check per row, seconds, and no double charges.

Explain it like I am 8

When kids walk through a door, you put a sticker on each kid's hand. If a kid arrives who already has a sticker, they have been here before. The set is your sticker box: it tells you in one look.

How it works, step by step

  1. Make an empty set called seen.
  2. Go through the items one at a time.
  3. If the item is already in seen, you found a duplicate: stop and report it.
  4. Otherwise add the item to seen and continue.
  5. If you reach the end with no repeats, all items are unique.

The code in four languages

PHP

<?php
// Does the list contain any repeat?
function hasDuplicate(array $nums): bool {
    $seen = [];
    foreach ($nums as $x) {
        if (isset($seen[$x])) return true;     // already seen: duplicate!
        $seen[$x] = true;
    }
    return false;
}

// Which number repeats first (the first one whose second copy appears earliest)?
function firstDuplicate(array $nums): ?int {
    $seen = [];
    foreach ($nums as $x) {
        if (isset($seen[$x])) return $x;
        $seen[$x] = true;
    }
    return null;
}

$rolls = [4, 2, 9, 7, 2, 5];
echo (hasDuplicate($rolls) ? 'yes' : 'no') . "\n";            // yes
echo firstDuplicate($rolls) . "\n";                            // 2
echo (hasDuplicate([1, 2, 3]) ? 'yes' : 'no') . "\n";          // no

JavaScript

// Does the list contain any repeat?
function hasDuplicate(nums) {
  const seen = new Set();
  for (const x of nums) {
    if (seen.has(x)) return true;     // already seen: duplicate!
    seen.add(x);
  }
  return false;
}

// Which number repeats first (the first one whose second copy appears earliest)?
function firstDuplicate(nums) {
  const seen = new Set();
  for (const x of nums) {
    if (seen.has(x)) return x;
    seen.add(x);
  }
  return null;
}

const rolls = [4, 2, 9, 7, 2, 5];
console.log(hasDuplicate(rolls) ? 'yes' : 'no');            // yes
console.log(firstDuplicate(rolls));                          // 2
console.log(hasDuplicate([1, 2, 3]) ? 'yes' : 'no');         // no

Java

import java.util.*;

public class Main {
    // Does the list contain any repeat?
    static boolean hasDuplicate(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        for (int x : nums) {
            if (!seen.add(x)) return true;     // add() says false: already seen, duplicate!
        }
        return false;
    }

    // Which number repeats first (the first one whose second copy appears earliest)?
    static Integer firstDuplicate(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        for (int x : nums) {
            if (!seen.add(x)) return x;
        }
        return null;
    }

    public static void main(String[] args) {
        int[] rolls = {4, 2, 9, 7, 2, 5};
        System.out.println(hasDuplicate(rolls) ? "yes" : "no");              // yes
        System.out.println(firstDuplicate(rolls));                           // 2
        System.out.println(hasDuplicate(new int[]{1, 2, 3}) ? "yes" : "no"); // no
    }
}

Go

package main

import "fmt"

// hasDuplicate reports whether the list contains any repeat.
func hasDuplicate(nums []int) bool {
	seen := map[int]bool{}
	for _, x := range nums {
		if seen[x] {
			return true // already seen: duplicate!
		}
		seen[x] = true
	}
	return false
}

// firstDuplicate returns the number whose second copy appears earliest.
func firstDuplicate(nums []int) (int, bool) {
	seen := map[int]bool{}
	for _, x := range nums {
		if seen[x] {
			return x, true
		}
		seen[x] = true
	}
	return 0, false
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	rolls := []int{4, 2, 9, 7, 2, 5}
	fmt.Println(yesNo(hasDuplicate(rolls))) // yes
	if x, ok := firstDuplicate(rolls); ok {
		fmt.Println(x) // 2
	}
	fmt.Println(yesNo(hasDuplicate([]int{1, 2, 3}))) // no
}

Time: O(n) · Extra space: O(n). One pass with a constant-time set check per item; the price is memory for the set (comparing every pair would cost O(n²) time instead).

Watch out for

  • Checking every pair with two nested loops: it works but takes O(n²) time.
  • Sorting first and comparing neighbours is fine, but it changes the order and costs O(n log n); a set keeps the original order and is faster.
  • Forgetting that the set uses extra memory. If memory is tight, sorting may be the better trade.

Quick check

  1. What data structure makes duplicate detection fast?
    • A sorted stack
    • A hash set
    • A queue
  2. When you find the item is already in the set, what do you do?
    • Add it again
    • Report a duplicate
    • Remove it from the set
  3. What is the time cost of the set approach for n numbers?
    • O(n²)
    • O(1)
    • O(n)