Skip to content

Commit ce0b69b

Browse files
committed
Added Pythagorean Triplet efficient method
1 parent d7cd892 commit ce0b69b

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

MathAndStats/PythagoreanTriplets.go

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@ Given an array find all the pythagorean triplets (a^2 + b^2 = c^2)
55
package main
66

77
import ("fmt"
8+
"sort"
89
)
910

1011
type triplet struct {
1112
a,b,c int
1213
}
1314

1415
// This solution is O(n^3) in time complexity and space complexity is O(1)
16+
// For every combination of a,b,c we iterate to find the solution
1517
func PythagoreanTripletsBruteForce(array []int) *[]triplet {
1618
var tripletArray []triplet
1719
for i:=0;i<len(array);i++ {
@@ -28,10 +30,31 @@ func PythagoreanTripletsBruteForce(array []int) *[]triplet {
2830

2931
// The Pythagorean triplet using a 3SUM approach
3032
// The time complexity of the solution is O(n^2) and Space complexity (1)
31-
33+
func PythagoreanTriplets3Sum(array sort.IntSlice) *[]triplet {
34+
array.Sort() // Sorted Array
35+
var tripletArray []triplet
36+
for k:=len(array)-1;k>1;k-- {
37+
i := 0
38+
j := k-1
39+
for j!=i {
40+
if (array[i]*array[i] + array[j]*array[j] - array[k]*array[k] > 0) {
41+
j--
42+
} else if (array[i]*array[i] + array[j]*array[j] - array[k]*array[k] < 0) {
43+
i++
44+
} else {
45+
tripletArray = append(tripletArray,triplet{array[i],array[j],array[k]})
46+
break
47+
}
48+
}
49+
}
50+
return &tripletArray
51+
}
3252

3353
func main() {
3454
array := []int{4,16,1,2,3,5,6,8,25,10}
35-
tripletArrayPtr := PythagoreanTripletsBruteForce(array)
36-
fmt.Println(*tripletArrayPtr)
55+
var array1 sort.IntSlice = array //Using this type to do sorting
56+
tripletArrayPtr1 := PythagoreanTripletsBruteForce(array)
57+
fmt.Println(*tripletArrayPtr1)
58+
tripletArrayPtr2 := PythagoreanTriplets3Sum(array1)
59+
fmt.Println(*tripletArrayPtr2)
3760
}

0 commit comments

Comments
 (0)