Removing duplicate elements from an array/slice in Golang

Souvik Haldar
1 min readFeb 28, 2019

--

Recently I encountered an issue where I was supposed to merge two slices of strings into one so that the resulting slice should not contain any element from first or the second more than once. For example, A = [‘x’,’y’,’z’] and B = [‘x’,’p’,’q’]C = [‘p’,’x’,’z’,’q’,’y’].

So here I’m doing what is mentioned in the topic of this blog on the final slice that is a=obtained by just appending both the slices. This can be done by- c:= append(a, b…)

Algorithm for the solution:-

  1. append both the slices and form the final slice.
  2. Create a hash map from string to int. (you can use something else as value too)
  3. Iterate through slice and map each element to 0. (or any other thing)
  4. Now finally iterate through the map and append each key of the map to a new slice of strings. Since any duplicate value too will be mapped to the same number as the previous one, hence all the keys will be unique.

Link to golang Playground.

--

--

Souvik Haldar
Souvik Haldar

Responses (2)