80. Remove Near-Duplicate Documents
Difficulty: Medium · Topics: Data Prep for AI, Window Functions, Strings
A training corpus docs (doc_id, text) was scraped from several mirrors, so the same document appears more than once with tiny differences: upper or lower case, extra spaces or line breaks, and punctuation.
Treat two documents as duplicates when they are equal after lower-casing, removing every character that is not a letter, digit or whitespace, collapsing runs of whitespace to one space, and trimming. Keep one document per group, the one with the smallest doc_id, and return its original doc_id, text.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
docs
| doc_id | text |
|---|---|
| 1 | Spark is a distributed engine. |
| 2 | spark is a distributed engine |
| 3 | Delta Lake adds transactions. |
| 4 | Spark is a DISTRIBUTED engine! |
Expected output
| doc_id | text |
|---|---|
| 1 | Spark is a distributed engine. |
| 3 | Delta Lake adds transactions. |
Hints
Hint 1
Build the normalised text as a new column:lower, then regexp_replace to drop punctuation ([^a-z0-9\s]), then to collapse whitespace (\s+ to one space), then trim.Hint 2
Rank documents within each normalised text bydoc_id with row_number() over a window, and keep rank 1.Hint 3
dropDuplicates(["text"]) only catches exact copies, and which row it keeps is not defined.Learn the concepts
- row_number / rank · 4 min read. Number and rank rows inside a window, and how the three ranking functions treat ties.
- String functions · 5 min read. concat vs concat_ws, substring, split, trim and padding, with the null traps in each.
- regexp_extract · 8 min read. Extract, filter, replace and collect with a regular expression, and what you get when nothing matches.
PySpark functions you'll practise
- Row Number
- Window spec
- filter
- select
- withColumn
- orderBy
- regexp_replace
- lower
- trim
Related problems
- Filter Low-Quality Training Text · Medium · Data Prep for AI, Strings, Null Handling
- Split Train and Test With No User in Both · Medium · Data Prep for AI, Joins, Aggregations
- Build Preference Pairs from Ratings · Hard · Data Prep for AI, Window Functions, Joins
- Fit Conversations into a Context Window · Hard · Data Prep for AI, Window Functions, Joins
- Mask Personal Data Before Training · Easy · Data Prep for AI, Strings, Filtering & Selection
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice