Logo

Programming-Idioms

History of Idiom 119 > diff from v40 to v41

Edit summary for version 41 by programming-idioms.org:
[Go] Comments: T is pointer type

Version 40

2018-04-11, 21:34:44

Version 41

2018-04-11, 21:35:32

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]
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).
Comments bubble
Order is preserved.
Use this if T is a pointer type or reference type.
Discarded slots are set to nil, to avoid a memory leak.

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