Skip to content

Commit

Permalink
Merge pull request #88 from vaskoz/day40
Browse files Browse the repository at this point in the history
Day40
  • Loading branch information
vaskoz committed Sep 30, 2018
2 parents 1c31f4e + 57fa1c6 commit dc35022
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,4 @@ problems from
* [Day 36](https://github.com/vaskoz/dailycodingproblem-go/issues/79)
* [Day 37](https://github.com/vaskoz/dailycodingproblem-go/issues/81)
* [Day 38](https://github.com/vaskoz/dailycodingproblem-go/issues/83)
* [Day 40](https://github.com/vaskoz/dailycodingproblem-go/issues/87)
33 changes: 33 additions & 0 deletions day40/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package day40

// FindOnce returns the number that appears only once in a list where
// other numbers appear 3 times.
// Runs in O(N) time and O(1) space.
func FindOnce(nums []int) int {
var ones, twos int
for _, v := range nums {
twos |= ones & v
ones ^= v
not := ^(ones & twos)
ones &= not
twos &= not
}
return ones
}

// FindOnceMap uses a map to find the non-duplicated value.
// Runs in O(N) and O(N) space
func FindOnceMap(nums []int) int {
counts := make(map[int]int)
for _, v := range nums {
counts[v]++
}
var result int
for k, v := range counts {
if v == 1 {
result = k
break
}
}
return result
}
45 changes: 45 additions & 0 deletions day40/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package day40

import "testing"

var testcases = []struct {
input []int
expected int
}{
{[]int{6, 1, 3, 3, 3, 6, 6}, 1},
{[]int{13, 19, 13, 13}, 19},
}

func TestFindOnce(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := FindOnce(tc.input); tc.expected != result {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkFindOnce(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
FindOnce(tc.input)
}
}
}

func TestFindOnceMap(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := FindOnceMap(tc.input); tc.expected != result {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkFindOnceMap(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
FindOnceMap(tc.input)
}
}
}

0 comments on commit dc35022

Please sign in to comment.