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

Docs(Go): Adding Go folder and solutions #4

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions go/Two Pointers/pairSumSorted.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package main

func pairSumSorted(nums []int, target int) []int {
n := len(nums)
left, right := 0, n-1

for left < right {
sum := nums[left] + nums[right]
if sum < target {
left++
} else if sum > target {
right--
} else {
return []int{left, right}
}
}

return []int{}
}
15 changes: 15 additions & 0 deletions go/Two Pointers/pairSumSortedBruteForce.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package main

func pairSumSortedBruteForce(nums []int, target int) []int {
n := len(nums)

for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}
}
}

return []int{}
}
61 changes: 61 additions & 0 deletions go/Two Pointers/tripletSum.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"sort"
)

func tripletSum(nums []int) [][]int {
triplets := [][]int{}
sort.Ints(nums)

for i := range nums {
if i < 0 {
break
}

if i > 0 && nums[i] == nums[i-1] {
continue
}

pairs := pairSumSortedAllPairs(nums, i+1, -nums[i])
if len(pairs) > 0 {

pairs = append(pairs, 0)
copy(pairs[1:], pairs)
pairs[0] = nums[i]

triplets = append(triplets, pairs)
}

}

return triplets
}

func pairSumSortedAllPairs(nums []int, start, target int) []int {

pairs := []int{}
n := len(nums)
left := start
right := n - 1

for left < right {
sum := nums[left] + nums[right]

if sum == target {
pairs = append(pairs, nums[left], nums[right])
left++

for left < right && nums[left] == nums[left-1] {
left++
}
} else if sum < target {
left++
} else {
right--
}

}

return pairs
}
26 changes: 26 additions & 0 deletions go/Two Pointers/tripletSumBruteForce.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import (
"sort"
)

func tripletSumBruteForce(nums []int) [][]int {
n := len(nums)
triplets := [][]int{}
index := 0

for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
for k := j + 1; k < n; k++ {
if nums[i]+nums[j]+nums[k] == 0 {
triplet := []int{nums[i], nums[j], nums[k]}
sort.Ints(triplet)
triplets = append(triplets, triplet)
index++
}
}
}
}

return triplets
}