Skip to content
Exercise · Maps · lesson 9 of 9

Exercise: no duplicates

Write a function func unique(nums []int) []int that returns a new slice in which each number from nums appears once. The numbers come in the order in which they first appear in nums.

  • unique([]int{3, 1, 3, 2, 1}) → [3 1 2]
  • unique([]int{5, 5, 5}) → [5]
  • unique([]int{}) → []

Constraints: nums holds from 0 to 100000 numbers, which can include negative numbers and zero; for an empty slice, the function returns an empty slice.

The solution must be fast: 60,000 numbers take a fraction of a second, so check for a repeat with a map, not by scanning the result.

Do not add extra imports unless the task says so explicitly.

unique.go — go
go · 6 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way