Skip to content

How to perform Array Element Parity in Golang

The challenge

You will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer.

Examples:

[1, -1, 2, -2, 3] => 3

3 has no matching negative appearance

[-3, 1, 2, 3, -1, -4, -2] => -4

-4 has no matching positive appearance

[1, -1, 2, -2, 3, 3] => 3

(the only-positive or only-negative integer may appear more than once)

The solution in Golang

Option 1:

package solution func Solve(arr []int) int { hash := make(map[int]bool) ans := for _, entry := range arr { if _, value := hash[entry]; !value { hash[entry] = true ans += entry } } return ans }
Code language: Go (go)

Option 2:

package solution func Solve(a []int) int { s, n := , for _, v := range a { s += v if v < { n-- } else { n++ } } if n < { n = -n } return s/n }
Code language: Go (go)

Option 3:

package solution func Find(arr []int, elem int) bool { for _, x := range arr { if elem == x { return true } } return false } func Solve(arr []int) int { for _, x := range arr { if !Find(arr, -x) { return x } } return }
Code language: Go (go)

Test cases to validate our solution

package solution_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func dotest(arr []int, exp int) { var ans = Solve(arr) Expect(ans).To(Equal(exp)) } var _ = Describe("Example tests", func() { It("It should work for basic tests", func() { dotest([] int{1,-1,2,-2,3}, 3) dotest([] int{-3,1,2,3,-1,-4,-2}, -4) dotest([] int{1,-1,2,-2,3,3}, 3) dotest([] int{-110,110,-38,-38,-62,62,-38,-38,-38}, -38) dotest([] int{-9,-105,-9,-9,-9,-9,105}, -9) }) })
Code language: Go (go)

See also  How to Circularly Sort an Array in Golang
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x