Skip to content

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_idtext
1Spark is a distributed engine.
2spark is a distributed engine
3Delta Lake adds transactions.
4Spark is a DISTRIBUTED engine!

Expected output

doc_idtext
1Spark is a distributed engine.
3Delta Lake adds transactions.

Hints

Hint 1Build 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 2Rank documents within each normalised text by doc_id with row_number() over a window, and keep rank 1.
Hint 3dropDuplicates(["text"]) only catches exact copies, and which row it keeps is not defined.

Learn the concepts

PySpark functions you'll practise

Related problems

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