Skip to content

Commit

Permalink
Merge pull request #784 from vaskoz/day390
Browse files Browse the repository at this point in the history
Day390
  • Loading branch information
vaskoz committed Dec 14, 2019
2 parents 75e50be + 689b9c3 commit 30264e5
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -382,4 +382,5 @@ problems from
* [Day 384](https://github.com/vaskoz/dailycodingproblem-go/issues/776)
* [Day 385](https://github.com/vaskoz/dailycodingproblem-go/issues/774)
* [Day 386](https://github.com/vaskoz/dailycodingproblem-go/issues/778)
* [Day 390](https://github.com/vaskoz/dailycodingproblem-go/issues/783)

22 changes: 22 additions & 0 deletions day390/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package day390

// MissingThousandInMillion returns the numbers missing
// between 1 and 1 million.
// Runs in O(N) time and space.
func MissingThousandInMillion(nums []int) []int {
seen := make(map[int]struct{}, len(nums))

for _, n := range nums {
seen[n] = struct{}{}
}

ans := make([]int, 0, 1_000_000-len(seen)+1)

for n := 1; n <= 1_000_000; n++ {
if _, ok := seen[n]; !ok {
ans = append(ans, n)
}
}

return ans
}
53 changes: 53 additions & 0 deletions day390/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package day390

import (
"math/rand"
"reflect"
"testing"
"time"
)

func TestMissingThousandInMillion(t *testing.T) {
t.Parallel()

missing := []int{10_395, 25_011, 345_335, 565_332, 999_993}
input := setup(missing)

if res := MissingThousandInMillion(input); !reflect.DeepEqual(res, missing) {
t.Errorf("Expected %v, got %v", missing, res)
}
}

func BenchmarkMissingThousandInMillion(b *testing.B) {
missing := []int{25_011, 345_335, 565_332, 999_993, 10_395}
input := setup(missing)

for i := 0; i < b.N; i++ {
MissingThousandInMillion(input)
}
}

func setup(miss []int) []int {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
ans := make([]int, 1_000_000-len(miss)+1)
missMap := make(map[int]struct{}, len(miss))

for _, n := range miss {
missMap[n] = struct{}{}
}

pos := 0

for n := 1; n <= 1_000_000; n++ {
if _, skip := missMap[n]; !skip {
ans[pos] = n
pos++
}
}

r.Shuffle(len(ans), func(i, j int) {
ans[i], ans[j] = ans[j], ans[i]
})

return ans
}

0 comments on commit 30264e5

Please sign in to comment.