Remove duplicate training texts after normalising them

Duplicate examples leak between train and test and make models memorise. Exact matching misses copies that differ only in case or spacing.

Write dedupe_texts(texts). Normalise each text by lowercasing, stripping, and collapsing every run of whitespace into one space. Keep the first occurrence of each normalised text and return the indices of the kept texts, in order.

Signaturedef dedupe_texts(texts)

Example

dedupe_texts(["Hi there", "hi there", "Bye"]) is [0, 2].

Understand the idea

Duplicate training examples make a model memorise and can leak between train and test sets. Exact string matching misses copies that differ only in case or spacing, so first normalise each text, then keep only the first time each normalised form appears. A set of seen keys makes this one fast pass. Worked example: texts [' Hello World', 'hello world ', 'HELLO\tworld', 'bye']. Lowercasing, trimming the ends and turning every run of whitespace (spaces, tabs, newlines) into one space gives 'hello world' for the first three and 'bye' for the last. Keep index 0, skip 1 and 2, keep 3. Answer [0, 3]. Rule: key = lowercase, strip, then collapse whitespace runs to a single space; if the key is new, record the index and add the key to the set; return the kept indices in order. Lowercasing alone would treat different spacing as different texts. Real pipelines go further with near-duplicate detection, but this exact normalised match is the cheap first step in cleaning pretraining and fine-tuning datasets.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplededupe_texts(['Hi there', 'hi there', 'Bye'])
  • Sample 2: tabs and newlinesdedupe_texts(['a\tb', ' A B ', 'a\nb c', 'a b c'])
  • Test 3: all uniquededupe_texts(['x', 'y', 'z'])