Logo

Programming-Idioms

History of Idiom 119 > diff from v37 to v38

Edit summary for version 38 by programming-idioms.org:
New Go implementation by user [programming-idioms.org]

Version 37

2018-04-11, 19:49:59

Version 38

2018-04-11, 21:31:59

Idiom #119 Deduplicate list

Remove duplicates from list x.
Explain if original order is preserved.

Illustration

Idiom #119 Deduplicate list

Remove duplicates from list x.
Explain if original order is preserved.

Illustration
Extra Keywords
deduplicate dupe dupes redundant redundancy
Extra Keywords
deduplicate dupe dupes redundant redundancy
Code
seen := make(map[T]bool)
j := 0
for _, v := range x {
	if !seen[v] {
		x[j] = v
		j++
		seen[v] = true
	}
}
for i := j; i < len(x); i++ {
	x[i] = nil
}
x = x[:j]
Comments bubble
Order is preserved.
Discarded slot are set to nil, to avoid a memory leak.

This is O(n).
Demo URL
https://play.golang.org/p/D6Qabw8prus