-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
mode.go
47 lines (34 loc) · 824 Bytes
/
mode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// mode.go
// author(s): [CalvinNJK] (https://github.com/CalvinNJK)
// time complexity: O(n)
// space complexity: O(n)
// description: Finding Mode Value In an Array
// see mode.go
package math
import (
"errors"
"github.com/TheAlgorithms/Go/constraints"
)
// ErrEmptySlice is the error returned by functions in math package when
// an empty slice is provided to it as argument when the function expects
// a non-empty slice.
var ErrEmptySlice = errors.New("empty slice provided")
func Mode[T constraints.Number](numbers []T) (T, error) {
countMap := make(map[T]int)
n := len(numbers)
if n == 0 {
return 0, ErrEmptySlice
}
for _, number := range numbers {
countMap[number]++
}
var mode T
count := 0
for k, v := range countMap {
if v > count {
count = v
mode = k
}
}
return mode, nil
}