Removing Duplicates While Preserving Input Order
An order-preserving deduplication walks the input and emits a value only at the first key occurrence.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace the kept entries
On labels B, A, B, C, A, the emitted order is B, A, C. A set can record seen keys while a separate result preserves insertion order explicitly. Membership tests tell the loop whether each key needs recording.
Choose a key rule
Deduplicating contacts by name can merge multiple people. Deduplicating records by ID can instead keep the first snapshot of the same entity. Record equality determines whether keeping that first snapshot satisfies the domain.[1]
Keep both presence and output sequence
From ["b", "a", "b", "c", "a"], scanning with a set of seen labels preserves ["b", "a", "c"]. The set answers whether a label has appeared. Appending on first insertion preserves chronology. Sorting first would return a different order and therefore changes which sequence consumers see. For objects with a key, decide whether the first record or its last replacement survives. See stable ordering.
Define equivalence before discarding anything
Under case-folded equality, "A" and "a" share a bucket but can keep the first observed spelling in the output. Under exact equality they both remain. Apply the same key when checking and inserting into the seen set. Test repeated values separated by another value and a pair whose keys agree while their records differ. Maintaining the seen set uses memory proportional to distinct keys. See normalization and text equality.