Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day390 #784

Merged
merged 2 commits into from
Dec 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}