From 3b78dd9d416e149047a2f703dc6a1c8fc6ed2455 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Fri, 8 Jul 2022 14:49:42 +0000 Subject: [PATCH 01/19] twosum --- go/1-TwoASum.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 go/1-TwoASum.go diff --git a/go/1-TwoASum.go b/go/1-TwoASum.go new file mode 100644 index 000000000..021a59b29 --- /dev/null +++ b/go/1-TwoASum.go @@ -0,0 +1,13 @@ +package TwoSum + +func twoSum(nums []int, target int) []int { + var seen = make(map[int]int) + for i := range nums { + item, exist := seen[target-nums[i]] + if exist { + return []int{i, item} + } + seen[nums[i]] = i + } + return []int{0, 0} +} From bfe865a59b3adb173a26783f8208bea9c7375824 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Fri, 8 Jul 2022 14:52:39 +0000 Subject: [PATCH 02/19] adding code for arrays and hashing --- go/01_arrays_and_hashing/containsDuplicate.go | 15 +++++++++ .../twoSum.go} | 2 +- go/01_arrays_and_hashing/validAnagram.go | 31 +++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 go/01_arrays_and_hashing/containsDuplicate.go rename go/{1-TwoASum.go => 01_arrays_and_hashing/twoSum.go} (89%) create mode 100644 go/01_arrays_and_hashing/validAnagram.go diff --git a/go/01_arrays_and_hashing/containsDuplicate.go b/go/01_arrays_and_hashing/containsDuplicate.go new file mode 100644 index 000000000..015c72b75 --- /dev/null +++ b/go/01_arrays_and_hashing/containsDuplicate.go @@ -0,0 +1,15 @@ +package arraysandhashing + +func containsDuplicate(nums []int) bool { + hashmap := make(map[int]int8) + + for _, val := range nums { + _, ok := hashmap[val] + if ok { + return true + } else { + hashmap[val] = 1 + } + } + return false +} diff --git a/go/1-TwoASum.go b/go/01_arrays_and_hashing/twoSum.go similarity index 89% rename from go/1-TwoASum.go rename to go/01_arrays_and_hashing/twoSum.go index 021a59b29..a2f042962 100644 --- a/go/1-TwoASum.go +++ b/go/01_arrays_and_hashing/twoSum.go @@ -1,4 +1,4 @@ -package TwoSum +package arraysandhashing func twoSum(nums []int, target int) []int { var seen = make(map[int]int) diff --git a/go/01_arrays_and_hashing/validAnagram.go b/go/01_arrays_and_hashing/validAnagram.go new file mode 100644 index 000000000..4447066fe --- /dev/null +++ b/go/01_arrays_and_hashing/validAnagram.go @@ -0,0 +1,31 @@ +package arraysandhashing + +func isAnagram(s string, t string) bool { + characters := make(map[byte]int) + + if len(s) != len(t) { + return false + } + + for i := 0; i < len(s); i++ { + _, ok := characters[s[i]] + if !ok { + characters[s[i]] = 1 + } else { + characters[s[i]] += 1 + } + + } + + for i := 0; i < len(t); i++ { + val, ok := characters[t[i]] + if ok && val > 0 { + characters[t[i]] -= 1 + } else { + return false + } + } + + return true + +} From b401a49e69dac366a0cf2449c708e2851f935b59 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Fri, 8 Jul 2022 14:56:10 +0000 Subject: [PATCH 03/19] group anagrams --- go/01_arrays_and_hashing/groupAnagrams.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 go/01_arrays_and_hashing/groupAnagrams.go diff --git a/go/01_arrays_and_hashing/groupAnagrams.go b/go/01_arrays_and_hashing/groupAnagrams.go new file mode 100644 index 000000000..1809bac02 --- /dev/null +++ b/go/01_arrays_and_hashing/groupAnagrams.go @@ -0,0 +1,23 @@ +package arraysandhashing + +func groupAnagrams(strs []string) [][]string { + var result [][]string + strsMap := make(map[[26]int][]string) + var charArray [26]int + var anagramGroup []string + for i := 0; i < len(strs); i++ { + for _, char := range strs[i] { + charIndex := char - 'a' + charArray[charIndex] += 1 + } + anagramGroup, _ = strsMap[charArray] + anagramGroup = append(anagramGroup, strs[i]) + strsMap[charArray] = anagramGroup + charArray = [26]int{} + } + // fmt.Println(strsMap) + for _, value := range strsMap { + result = append(result, value) + } + return result +} From 4dd6993fcf80cc6f0ba3ac6ef4686ddda96f0519 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Sat, 9 Jul 2022 04:23:58 +0000 Subject: [PATCH 04/19] added solutions for topK elements and product of array except self --- .vscode/settings.json | 10 +++ .../main.go} | 10 ++- .../238. Product of Array Except Self/main.go | 68 +++++++++++++++++++ .../main.go} | 10 ++- .../347. Top K Frequent Elements/main.go | 47 +++++++++++++ .../main.go} | 10 ++- .../665_Non-decreasing Array/main.go | 31 +++++++++ go/01_arrays_and_hashing/twoSum.go | 13 ---- 8 files changed, 183 insertions(+), 16 deletions(-) create mode 100644 .vscode/settings.json rename go/01_arrays_and_hashing/{containsDuplicate.go => 217. Contains Duplicate/main.go} (61%) create mode 100644 go/01_arrays_and_hashing/238. Product of Array Except Self/main.go rename go/01_arrays_and_hashing/{validAnagram.go => 242. Valid Anagram/main.go} (77%) create mode 100644 go/01_arrays_and_hashing/347. Top K Frequent Elements/main.go rename go/01_arrays_and_hashing/{groupAnagrams.go => 49. Group Anagrams/main.go} (82%) create mode 100644 go/01_arrays_and_hashing/665_Non-decreasing Array/main.go delete mode 100644 go/01_arrays_and_hashing/twoSum.go diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..4e4bb40dc --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "workbench.colorCustomizations": { + "sideBar.background": "#f9fdf9", + "editor.lineHighlightBackground": "#1073cf2d", + "editor.lineHighlightBorder": "#9fced11f", + "activityBar.background": "#422717", + "titleBar.activeBackground": "#5C3720", + "titleBar.activeForeground": "#FDFBFA" + } +} \ No newline at end of file diff --git a/go/01_arrays_and_hashing/containsDuplicate.go b/go/01_arrays_and_hashing/217. Contains Duplicate/main.go similarity index 61% rename from go/01_arrays_and_hashing/containsDuplicate.go rename to go/01_arrays_and_hashing/217. Contains Duplicate/main.go index 015c72b75..5f1a01842 100644 --- a/go/01_arrays_and_hashing/containsDuplicate.go +++ b/go/01_arrays_and_hashing/217. Contains Duplicate/main.go @@ -1,4 +1,12 @@ -package arraysandhashing +package main + +import "fmt" + +func main() { + nums := []int{1, 2, 4, 4} + result := containsDuplicate(nums) + fmt.Println(result) +} func containsDuplicate(nums []int) bool { hashmap := make(map[int]int8) diff --git a/go/01_arrays_and_hashing/238. Product of Array Except Self/main.go b/go/01_arrays_and_hashing/238. Product of Array Except Self/main.go new file mode 100644 index 000000000..eb9ad7df9 --- /dev/null +++ b/go/01_arrays_and_hashing/238. Product of Array Except Self/main.go @@ -0,0 +1,68 @@ +package main + +import "fmt" + +func main() { + nums := []int{1, 2, 3, 4} + result := productExceptSelf(nums) + fmt.Println(result) +} + +func getPrefixProduct(nums []int) []int { + prefixProductArr := make([]int, len(nums)) + prefixProduct := 1 + for i := range nums { + prefixProductArr[i] = prefixProduct * nums[i] + prefixProduct = prefixProductArr[i] + } + return prefixProductArr +} + +func getPostFixProduct(nums []int) []int { + postFixProductArr := make([]int, len(nums)) + postFixProduct := 1 + i := len(nums) - 1 + for i >= 0 { + postFixProductArr[i] = postFixProduct * nums[i] + postFixProduct = postFixProductArr[i] + i-- + } + return postFixProductArr +} + +func productExceptSelf(nums []int) []int { + result := make([]int, len(nums)) + prefixProductArr := getPrefixProduct(nums) + postFixProductArr := getPostFixProduct(nums) + prefixValue := 1 + postFixValue := 1 + + for i := range result { + if i == 0 { + prefixValue = 1 + } else { + prefixValue = prefixProductArr[i-1] + } + if i < len(result)-1 { + postFixValue = postFixProductArr[i+1] + } else { + postFixValue = 1 + } + + result[i] = prefixValue * postFixValue + } + return result +} + +// For O(1) space solution we need to store the prefix Array as +// [1, nums[0], nums[1]*nums[0], nums[2]*nums[1]*nums[0] ..... ] +// then we write a loop +// Initial postfix value will be 1 +// for i >=0 { +// if i == len(nums) - 1 { +// postFix = 1 +// }else { +// postFix *= nums[i+1] +// } +// result[i] = postFix * prefixArray[i] +// } diff --git a/go/01_arrays_and_hashing/validAnagram.go b/go/01_arrays_and_hashing/242. Valid Anagram/main.go similarity index 77% rename from go/01_arrays_and_hashing/validAnagram.go rename to go/01_arrays_and_hashing/242. Valid Anagram/main.go index 4447066fe..085c78107 100644 --- a/go/01_arrays_and_hashing/validAnagram.go +++ b/go/01_arrays_and_hashing/242. Valid Anagram/main.go @@ -1,4 +1,12 @@ -package arraysandhashing +package main + +import "fmt" + +func main() { + s, t := "anagram", "nagaram" + result := isAnagram(s, t) + fmt.Println(result) +} func isAnagram(s string, t string) bool { characters := make(map[byte]int) diff --git a/go/01_arrays_and_hashing/347. Top K Frequent Elements/main.go b/go/01_arrays_and_hashing/347. Top K Frequent Elements/main.go new file mode 100644 index 000000000..6b42ae6f6 --- /dev/null +++ b/go/01_arrays_and_hashing/347. Top K Frequent Elements/main.go @@ -0,0 +1,47 @@ +package main + +import "fmt" + +func main() { + nums := []int{4, 1, -1, 2, -1, 2, 3} + k := 2 + result := topKFrequent(nums, k) + fmt.Println("result", result) +} + +func getElementFrequencyMap(nums []int) map[int]int { + freqMap := make(map[int]int) + for _, value := range nums { + _, ok := freqMap[value] + if !ok { + freqMap[value] = 1 + } else { + freqMap[value] += 1 + } + } + return freqMap +} + +func topKFrequent(nums []int, k int) []int { + var result []int + freqMap := getElementFrequencyMap(nums) + fmt.Println(freqMap) + + //bucket sort + bucket := make([][]int, len(nums)+1) + for key, value := range freqMap { + bucket[value] = append(bucket[value], key) + } + + i := len(bucket) - 1 + for i >= 0 { + if len(bucket[i]) > 0 { + result = append(result, bucket[i]...) + if len(result) >= k { + return result[:k] + } + } + i-- + } + return result +} diff --git a/go/01_arrays_and_hashing/groupAnagrams.go b/go/01_arrays_and_hashing/49. Group Anagrams/main.go similarity index 82% rename from go/01_arrays_and_hashing/groupAnagrams.go rename to go/01_arrays_and_hashing/49. Group Anagrams/main.go index 1809bac02..de9451461 100644 --- a/go/01_arrays_and_hashing/groupAnagrams.go +++ b/go/01_arrays_and_hashing/49. Group Anagrams/main.go @@ -1,4 +1,12 @@ -package arraysandhashing +package main + +import "fmt" + +func main() { + strs := []string{"a"} + result := groupAnagrams(strs) + fmt.Println(result) +} func groupAnagrams(strs []string) [][]string { var result [][]string diff --git a/go/01_arrays_and_hashing/665_Non-decreasing Array/main.go b/go/01_arrays_and_hashing/665_Non-decreasing Array/main.go new file mode 100644 index 000000000..adb0cf8d1 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non-decreasing Array/main.go @@ -0,0 +1,31 @@ +package main + +import "fmt" + +func main() { + nums := []int{4, 2, 5} + result := checkPossibility(nums) + fmt.Println(result) +} + +func checkPossibility(nums []int) bool { + changed := false + for i := 0; i < len(nums)-1; i++ { + if nums[i] <= nums[i+1] { + continue + } + if changed { + return false + } + if i == 0 || nums[i+1] >= nums[i-1] { + nums[i] = nums[i+1] + changed = true + } else { + nums[i+1] = nums[i] + changed = true + } + } + return true +} + +//5,7,7,8,9 diff --git a/go/01_arrays_and_hashing/twoSum.go b/go/01_arrays_and_hashing/twoSum.go deleted file mode 100644 index a2f042962..000000000 --- a/go/01_arrays_and_hashing/twoSum.go +++ /dev/null @@ -1,13 +0,0 @@ -package arraysandhashing - -func twoSum(nums []int, target int) []int { - var seen = make(map[int]int) - for i := range nums { - item, exist := seen[target-nums[i]] - if exist { - return []int{i, item} - } - seen[nums[i]] = i - } - return []int{0, 0} -} From 9c953f409df7821235e40079c2b96240767e26cd Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Sat, 9 Jul 2022 04:51:10 +0000 Subject: [PATCH 05/19] Added tests for files Did some modularization for better representation. Instead of having main packages made the packages with the method name --- .../217_ContainsDuplicate.go} | 10 +--- .../217_ContainsDuplicate_test.go | 29 +++++++++ .../238_Product_of_Array_Except_Self.go} | 10 +--- .../238_Product_of_Array_Except_Self_test.go | 32 ++++++++++ .../242_Valid_Anagram.go} | 10 +--- .../242_Valid_Anagram_test.go | 31 ++++++++++ .../347_Top_K_Frequent_Elements.go} | 2 +- .../347_Top_K_Frequent_Elements_test.go | 34 +++++++++++ .../49_Group_Anagrams.go} | 12 +--- .../49_Group_Anagrams_test.go | 42 +++++++++++++ .../217_ContainsDuplicate.go | 15 +++++ .../217_ContainsDuplicate_test.go | 29 +++++++++ .../238_Product_of_Array_Except_Self.go | 60 +++++++++++++++++++ .../238_Product_of_Array_Except_Self_test.go | 32 ++++++++++ .../242_Valid_Anagram/242_Valid_Anagram.go | 31 ++++++++++ .../242_Valid_Anagram_test.go | 31 ++++++++++ .../347_Top_K_Frequent_Elements.go | 47 +++++++++++++++ .../347_Top_K_Frequent_Elements_test.go | 34 +++++++++++ .../49_Group_Anagrams/49_Group_Anagrams.go | 23 +++++++ .../49_Group_Anagrams_test.go | 42 +++++++++++++ .../665_Non_decreasing_Array.go} | 10 +--- .../665_Non_decreasing_Array_test.go | 27 +++++++++ 22 files changed, 546 insertions(+), 47 deletions(-) rename go/01_arrays_and_hashing/{217. Contains Duplicate/main.go => 217_ContainsDuplicate/217_ContainsDuplicate.go} (61%) create mode 100644 go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate_test.go rename go/01_arrays_and_hashing/{238. Product of Array Except Self/main.go => 238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go} (91%) create mode 100644 go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go rename go/01_arrays_and_hashing/{242. Valid Anagram/main.go => 242_Valid_Anagram/242_Valid_Anagram.go} (77%) create mode 100644 go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram_test.go rename go/01_arrays_and_hashing/{347. Top K Frequent Elements/main.go => 347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go} (97%) create mode 100644 go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go rename go/01_arrays_and_hashing/{49. Group Anagrams/main.go => 49_Group_Anagrams/49_Group_Anagrams.go} (76%) create mode 100644 go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams_test.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate_test.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram_test.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams.go create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams_test.go rename go/01_arrays_and_hashing/{665_Non-decreasing Array/main.go => 665_Non_decreasing_Array/665_Non_decreasing_Array.go} (73%) create mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go diff --git a/go/01_arrays_and_hashing/217. Contains Duplicate/main.go b/go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate.go similarity index 61% rename from go/01_arrays_and_hashing/217. Contains Duplicate/main.go rename to go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate.go index 5f1a01842..0c7de7a76 100644 --- a/go/01_arrays_and_hashing/217. Contains Duplicate/main.go +++ b/go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate.go @@ -1,12 +1,4 @@ -package main - -import "fmt" - -func main() { - nums := []int{1, 2, 4, 4} - result := containsDuplicate(nums) - fmt.Println(result) -} +package containsDuplicate func containsDuplicate(nums []int) bool { hashmap := make(map[int]int8) diff --git a/go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate_test.go b/go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate_test.go new file mode 100644 index 000000000..f1d88ee61 --- /dev/null +++ b/go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate_test.go @@ -0,0 +1,29 @@ +package containsDuplicate + +import "testing" + +func Test_containsDuplicate(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + nums: []int{1, 2, 3, 3}, + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := containsDuplicate(tt.args.nums); got != tt.want { + t.Errorf("containsDuplicate() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/238. Product of Array Except Self/main.go b/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go similarity index 91% rename from go/01_arrays_and_hashing/238. Product of Array Except Self/main.go rename to go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go index eb9ad7df9..53c4b9a25 100644 --- a/go/01_arrays_and_hashing/238. Product of Array Except Self/main.go +++ b/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go @@ -1,12 +1,4 @@ -package main - -import "fmt" - -func main() { - nums := []int{1, 2, 3, 4} - result := productExceptSelf(nums) - fmt.Println(result) -} +package productExceptSelf func getPrefixProduct(nums []int) []int { prefixProductArr := make([]int, len(nums)) diff --git a/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go b/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go new file mode 100644 index 000000000..77d416e04 --- /dev/null +++ b/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go @@ -0,0 +1,32 @@ +package productExceptSelf + +import ( + "reflect" + "testing" +) + +func Test_productExceptSelf(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "case1", + args: args{ + []int{1, 2, 3, 4}, + }, + want: []int{24, 12, 8, 6}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := productExceptSelf(tt.args.nums); !reflect.DeepEqual(got, tt.want) { + t.Errorf("productExceptSelf() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/242. Valid Anagram/main.go b/go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram.go similarity index 77% rename from go/01_arrays_and_hashing/242. Valid Anagram/main.go rename to go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram.go index 085c78107..ceba532ea 100644 --- a/go/01_arrays_and_hashing/242. Valid Anagram/main.go +++ b/go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram.go @@ -1,12 +1,4 @@ -package main - -import "fmt" - -func main() { - s, t := "anagram", "nagaram" - result := isAnagram(s, t) - fmt.Println(result) -} +package isAnagram func isAnagram(s string, t string) bool { characters := make(map[byte]int) diff --git a/go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram_test.go b/go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram_test.go new file mode 100644 index 000000000..fa6b127df --- /dev/null +++ b/go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram_test.go @@ -0,0 +1,31 @@ +package isAnagram + +import "testing" + +func Test_isAnagram(t *testing.T) { + type args struct { + s string + t string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + s: "anagram", + t: "nagaram", + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isAnagram(tt.args.s, tt.args.t); got != tt.want { + t.Errorf("isAnagram() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/347. Top K Frequent Elements/main.go b/go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go similarity index 97% rename from go/01_arrays_and_hashing/347. Top K Frequent Elements/main.go rename to go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go index 6b42ae6f6..1b92ea271 100644 --- a/go/01_arrays_and_hashing/347. Top K Frequent Elements/main.go +++ b/go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go @@ -1,4 +1,4 @@ -package main +package topKFrequent import "fmt" diff --git a/go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go b/go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go new file mode 100644 index 000000000..dd8539393 --- /dev/null +++ b/go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go @@ -0,0 +1,34 @@ +package topKFrequent + +import ( + "reflect" + "testing" +) + +func Test_topKFrequent(t *testing.T) { + type args struct { + nums []int + k int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "case1", + args: args{ + nums: []int{4, 1, -1, 2, -1, 2, 3}, + k: 2, + }, + want: []int{-1, 2}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := topKFrequent(tt.args.nums, tt.args.k); !reflect.DeepEqual(got, tt.want) { + t.Errorf("topKFrequent() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/49. Group Anagrams/main.go b/go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams.go similarity index 76% rename from go/01_arrays_and_hashing/49. Group Anagrams/main.go rename to go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams.go index de9451461..f16690908 100644 --- a/go/01_arrays_and_hashing/49. Group Anagrams/main.go +++ b/go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams.go @@ -1,12 +1,4 @@ -package main - -import "fmt" - -func main() { - strs := []string{"a"} - result := groupAnagrams(strs) - fmt.Println(result) -} +package groupAnagrams func groupAnagrams(strs []string) [][]string { var result [][]string @@ -18,7 +10,7 @@ func groupAnagrams(strs []string) [][]string { charIndex := char - 'a' charArray[charIndex] += 1 } - anagramGroup, _ = strsMap[charArray] + anagramGroup = strsMap[charArray] anagramGroup = append(anagramGroup, strs[i]) strsMap[charArray] = anagramGroup charArray = [26]int{} diff --git a/go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams_test.go b/go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams_test.go new file mode 100644 index 000000000..32f86b980 --- /dev/null +++ b/go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams_test.go @@ -0,0 +1,42 @@ +package groupAnagrams + +import ( + "reflect" + "testing" +) + +func Test_groupAnagrams(t *testing.T) { + type args struct { + strs []string + } + tests := []struct { + name string + args args + want [][]string + }{ + { + name: "case1", + args: args{ + []string{ + "cat", + "bat", + "tac", + "ate", + "eat", + }, + }, + want: [][]string{ + {"cat", "tac"}, + {"bat"}, + {"ate", "eat"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := groupAnagrams(tt.args.strs); !reflect.DeepEqual(got, tt.want) { + t.Errorf("groupAnagrams() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate.go new file mode 100644 index 000000000..0c7de7a76 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate.go @@ -0,0 +1,15 @@ +package containsDuplicate + +func containsDuplicate(nums []int) bool { + hashmap := make(map[int]int8) + + for _, val := range nums { + _, ok := hashmap[val] + if ok { + return true + } else { + hashmap[val] = 1 + } + } + return false +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate_test.go new file mode 100644 index 000000000..f1d88ee61 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate_test.go @@ -0,0 +1,29 @@ +package containsDuplicate + +import "testing" + +func Test_containsDuplicate(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + nums: []int{1, 2, 3, 3}, + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := containsDuplicate(tt.args.nums); got != tt.want { + t.Errorf("containsDuplicate() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go new file mode 100644 index 000000000..53c4b9a25 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go @@ -0,0 +1,60 @@ +package productExceptSelf + +func getPrefixProduct(nums []int) []int { + prefixProductArr := make([]int, len(nums)) + prefixProduct := 1 + for i := range nums { + prefixProductArr[i] = prefixProduct * nums[i] + prefixProduct = prefixProductArr[i] + } + return prefixProductArr +} + +func getPostFixProduct(nums []int) []int { + postFixProductArr := make([]int, len(nums)) + postFixProduct := 1 + i := len(nums) - 1 + for i >= 0 { + postFixProductArr[i] = postFixProduct * nums[i] + postFixProduct = postFixProductArr[i] + i-- + } + return postFixProductArr +} + +func productExceptSelf(nums []int) []int { + result := make([]int, len(nums)) + prefixProductArr := getPrefixProduct(nums) + postFixProductArr := getPostFixProduct(nums) + prefixValue := 1 + postFixValue := 1 + + for i := range result { + if i == 0 { + prefixValue = 1 + } else { + prefixValue = prefixProductArr[i-1] + } + if i < len(result)-1 { + postFixValue = postFixProductArr[i+1] + } else { + postFixValue = 1 + } + + result[i] = prefixValue * postFixValue + } + return result +} + +// For O(1) space solution we need to store the prefix Array as +// [1, nums[0], nums[1]*nums[0], nums[2]*nums[1]*nums[0] ..... ] +// then we write a loop +// Initial postfix value will be 1 +// for i >=0 { +// if i == len(nums) - 1 { +// postFix = 1 +// }else { +// postFix *= nums[i+1] +// } +// result[i] = postFix * prefixArray[i] +// } diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go new file mode 100644 index 000000000..77d416e04 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go @@ -0,0 +1,32 @@ +package productExceptSelf + +import ( + "reflect" + "testing" +) + +func Test_productExceptSelf(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "case1", + args: args{ + []int{1, 2, 3, 4}, + }, + want: []int{24, 12, 8, 6}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := productExceptSelf(tt.args.nums); !reflect.DeepEqual(got, tt.want) { + t.Errorf("productExceptSelf() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram.go new file mode 100644 index 000000000..ceba532ea --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram.go @@ -0,0 +1,31 @@ +package isAnagram + +func isAnagram(s string, t string) bool { + characters := make(map[byte]int) + + if len(s) != len(t) { + return false + } + + for i := 0; i < len(s); i++ { + _, ok := characters[s[i]] + if !ok { + characters[s[i]] = 1 + } else { + characters[s[i]] += 1 + } + + } + + for i := 0; i < len(t); i++ { + val, ok := characters[t[i]] + if ok && val > 0 { + characters[t[i]] -= 1 + } else { + return false + } + } + + return true + +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram_test.go new file mode 100644 index 000000000..fa6b127df --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram_test.go @@ -0,0 +1,31 @@ +package isAnagram + +import "testing" + +func Test_isAnagram(t *testing.T) { + type args struct { + s string + t string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + s: "anagram", + t: "nagaram", + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isAnagram(tt.args.s, tt.args.t); got != tt.want { + t.Errorf("isAnagram() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go new file mode 100644 index 000000000..1b92ea271 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go @@ -0,0 +1,47 @@ +package topKFrequent + +import "fmt" + +func main() { + nums := []int{4, 1, -1, 2, -1, 2, 3} + k := 2 + result := topKFrequent(nums, k) + fmt.Println("result", result) +} + +func getElementFrequencyMap(nums []int) map[int]int { + freqMap := make(map[int]int) + for _, value := range nums { + _, ok := freqMap[value] + if !ok { + freqMap[value] = 1 + } else { + freqMap[value] += 1 + } + } + return freqMap +} + +func topKFrequent(nums []int, k int) []int { + var result []int + freqMap := getElementFrequencyMap(nums) + fmt.Println(freqMap) + + //bucket sort + bucket := make([][]int, len(nums)+1) + for key, value := range freqMap { + bucket[value] = append(bucket[value], key) + } + + i := len(bucket) - 1 + for i >= 0 { + if len(bucket[i]) > 0 { + result = append(result, bucket[i]...) + if len(result) >= k { + return result[:k] + } + } + i-- + } + return result +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go new file mode 100644 index 000000000..dd8539393 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go @@ -0,0 +1,34 @@ +package topKFrequent + +import ( + "reflect" + "testing" +) + +func Test_topKFrequent(t *testing.T) { + type args struct { + nums []int + k int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "case1", + args: args{ + nums: []int{4, 1, -1, 2, -1, 2, 3}, + k: 2, + }, + want: []int{-1, 2}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := topKFrequent(tt.args.nums, tt.args.k); !reflect.DeepEqual(got, tt.want) { + t.Errorf("topKFrequent() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams.go new file mode 100644 index 000000000..f16690908 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams.go @@ -0,0 +1,23 @@ +package groupAnagrams + +func groupAnagrams(strs []string) [][]string { + var result [][]string + strsMap := make(map[[26]int][]string) + var charArray [26]int + var anagramGroup []string + for i := 0; i < len(strs); i++ { + for _, char := range strs[i] { + charIndex := char - 'a' + charArray[charIndex] += 1 + } + anagramGroup = strsMap[charArray] + anagramGroup = append(anagramGroup, strs[i]) + strsMap[charArray] = anagramGroup + charArray = [26]int{} + } + // fmt.Println(strsMap) + for _, value := range strsMap { + result = append(result, value) + } + return result +} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams_test.go new file mode 100644 index 000000000..32f86b980 --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams_test.go @@ -0,0 +1,42 @@ +package groupAnagrams + +import ( + "reflect" + "testing" +) + +func Test_groupAnagrams(t *testing.T) { + type args struct { + strs []string + } + tests := []struct { + name string + args args + want [][]string + }{ + { + name: "case1", + args: args{ + []string{ + "cat", + "bat", + "tac", + "ate", + "eat", + }, + }, + want: [][]string{ + {"cat", "tac"}, + {"bat"}, + {"ate", "eat"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := groupAnagrams(tt.args.strs); !reflect.DeepEqual(got, tt.want) { + t.Errorf("groupAnagrams() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/665_Non-decreasing Array/main.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array.go similarity index 73% rename from go/01_arrays_and_hashing/665_Non-decreasing Array/main.go rename to go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array.go index adb0cf8d1..f22895d0d 100644 --- a/go/01_arrays_and_hashing/665_Non-decreasing Array/main.go +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array.go @@ -1,12 +1,4 @@ -package main - -import "fmt" - -func main() { - nums := []int{4, 2, 5} - result := checkPossibility(nums) - fmt.Println(result) -} +package checkPossibility func checkPossibility(nums []int) bool { changed := false diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go new file mode 100644 index 000000000..2f7a93fea --- /dev/null +++ b/go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go @@ -0,0 +1,27 @@ +package checkPossibility + +import "testing" + +func Test_checkPossibility(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{[]int{4, 2, 3}}, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := checkPossibility(tt.args.nums); got != tt.want { + t.Errorf("checkPossibility() = %v, want %v", got, tt.want) + } + }) + } +} From dc0c356ba9f525ea5e9f6e7d42d72fa9b336fefb Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Sat, 9 Jul 2022 05:43:49 +0000 Subject: [PATCH 06/19] valid sudoku --- .../36_validSudoku/36_validSudoku.go | 79 +++++++++++++++++++ .../36_validSudoku/36_validSudoku_test.go | 56 +++++++++++++ 2 files changed, 135 insertions(+) create mode 100644 go/01_arrays_and_hashing/36_validSudoku/36_validSudoku.go create mode 100644 go/01_arrays_and_hashing/36_validSudoku/36_validSudoku_test.go diff --git a/go/01_arrays_and_hashing/36_validSudoku/36_validSudoku.go b/go/01_arrays_and_hashing/36_validSudoku/36_validSudoku.go new file mode 100644 index 000000000..56c424123 --- /dev/null +++ b/go/01_arrays_and_hashing/36_validSudoku/36_validSudoku.go @@ -0,0 +1,79 @@ +package isValidSudoku + +import "fmt" + +func validRow(board [][]byte) bool { + for i := 0; i < len(board); i++ { + numberMap := make(map[byte]byte) + for j := 0; j < len(board[i]); j++ { + if board[i][j] == '.' { + continue + } + _, ok := numberMap[board[i][j]] + if ok { + fmt.Println("Row Validation Failed ", board[i][j]) + return false + } else { + numberMap[board[i][j]] = 1 + } + } + } + return true +} + +func validColumn(board [][]byte) bool { + + for j := 0; j < len(board); j++ { + numberMap := make(map[byte]byte) + for i := 0; i < len(board); i++ { + if board[i][j] == '.' { + continue + } + _, ok := numberMap[board[i][j]] + if ok { + fmt.Println("Column Validation Failed") + return false + } else { + numberMap[board[i][j]] = 1 + } + } + } + + return true +} + +func validBoxes(board [][]byte) bool { + rowItr := 0 + columnItr := 0 + + for columnItr < 3 { + rowItr = 0 + for rowItr < 3 { + numberMap := make(map[byte]byte) + for j := rowItr * 3; j < 3*rowItr+3; j++ { + for k := 3 * columnItr; k < 3*columnItr+3; k++ { + if board[j][k] == '.' { + continue + } + _, ok := numberMap[board[j][k]] + if ok { + fmt.Println("Box Validation Failed ", j, k) + return false + } else { + numberMap[board[j][k]] = 1 + } + } + } + rowItr++ + } + columnItr++ + } + return true +} + +func isValidSudoku(board [][]byte) bool { + if !validRow(board) || !validColumn(board) || !validBoxes(board) { + return false + } + return true +} diff --git a/go/01_arrays_and_hashing/36_validSudoku/36_validSudoku_test.go b/go/01_arrays_and_hashing/36_validSudoku/36_validSudoku_test.go new file mode 100644 index 000000000..477daad2a --- /dev/null +++ b/go/01_arrays_and_hashing/36_validSudoku/36_validSudoku_test.go @@ -0,0 +1,56 @@ +package isValidSudoku + +import "testing" + +func Test_isValidSudoku(t *testing.T) { + type args struct { + board [][]byte + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + board: [][]byte{ + {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, + {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, + {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, + {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, + {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, + {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, + {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, + {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, + {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, + }, + }, + want: true, + }, + { + name: "case2", + args: args{ + board: [][]byte{ + {'8', '3', '.', '.', '7', '.', '.', '.', '.'}, + {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, + {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, + {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, + {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, + {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, + {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, + {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, + {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, + }, + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isValidSudoku(tt.args.board); got != tt.want { + t.Errorf("isValidSudoku() = %v, want %v", got, tt.want) + } + }) + } +} From 3478aa321fc36d7d356d9e421da5fb590b4431d1 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Sat, 9 Jul 2022 16:16:03 +0000 Subject: [PATCH 07/19] Deleted wrongly copied files --- .../217_ContainsDuplicate.go | 15 ----- .../217_ContainsDuplicate_test.go | 29 --------- .../238_Product_of_Array_Except_Self.go | 60 ------------------- .../238_Product_of_Array_Except_Self_test.go | 32 ---------- .../242_Valid_Anagram/242_Valid_Anagram.go | 31 ---------- .../242_Valid_Anagram_test.go | 31 ---------- .../347_Top_K_Frequent_Elements.go | 47 --------------- .../347_Top_K_Frequent_Elements_test.go | 34 ----------- .../49_Group_Anagrams/49_Group_Anagrams.go | 23 ------- .../49_Group_Anagrams_test.go | 42 ------------- 10 files changed, 344 deletions(-) delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate_test.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram_test.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams.go delete mode 100644 go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams_test.go diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate.go deleted file mode 100644 index 0c7de7a76..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate.go +++ /dev/null @@ -1,15 +0,0 @@ -package containsDuplicate - -func containsDuplicate(nums []int) bool { - hashmap := make(map[int]int8) - - for _, val := range nums { - _, ok := hashmap[val] - if ok { - return true - } else { - hashmap[val] = 1 - } - } - return false -} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate_test.go deleted file mode 100644 index f1d88ee61..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/217_ContainsDuplicate/217_ContainsDuplicate_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package containsDuplicate - -import "testing" - -func Test_containsDuplicate(t *testing.T) { - type args struct { - nums []int - } - tests := []struct { - name string - args args - want bool - }{ - { - name: "case1", - args: args{ - nums: []int{1, 2, 3, 3}, - }, - want: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := containsDuplicate(tt.args.nums); got != tt.want { - t.Errorf("containsDuplicate() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go deleted file mode 100644 index 53c4b9a25..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go +++ /dev/null @@ -1,60 +0,0 @@ -package productExceptSelf - -func getPrefixProduct(nums []int) []int { - prefixProductArr := make([]int, len(nums)) - prefixProduct := 1 - for i := range nums { - prefixProductArr[i] = prefixProduct * nums[i] - prefixProduct = prefixProductArr[i] - } - return prefixProductArr -} - -func getPostFixProduct(nums []int) []int { - postFixProductArr := make([]int, len(nums)) - postFixProduct := 1 - i := len(nums) - 1 - for i >= 0 { - postFixProductArr[i] = postFixProduct * nums[i] - postFixProduct = postFixProductArr[i] - i-- - } - return postFixProductArr -} - -func productExceptSelf(nums []int) []int { - result := make([]int, len(nums)) - prefixProductArr := getPrefixProduct(nums) - postFixProductArr := getPostFixProduct(nums) - prefixValue := 1 - postFixValue := 1 - - for i := range result { - if i == 0 { - prefixValue = 1 - } else { - prefixValue = prefixProductArr[i-1] - } - if i < len(result)-1 { - postFixValue = postFixProductArr[i+1] - } else { - postFixValue = 1 - } - - result[i] = prefixValue * postFixValue - } - return result -} - -// For O(1) space solution we need to store the prefix Array as -// [1, nums[0], nums[1]*nums[0], nums[2]*nums[1]*nums[0] ..... ] -// then we write a loop -// Initial postfix value will be 1 -// for i >=0 { -// if i == len(nums) - 1 { -// postFix = 1 -// }else { -// postFix *= nums[i+1] -// } -// result[i] = postFix * prefixArray[i] -// } diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go deleted file mode 100644 index 77d416e04..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package productExceptSelf - -import ( - "reflect" - "testing" -) - -func Test_productExceptSelf(t *testing.T) { - type args struct { - nums []int - } - tests := []struct { - name string - args args - want []int - }{ - { - name: "case1", - args: args{ - []int{1, 2, 3, 4}, - }, - want: []int{24, 12, 8, 6}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := productExceptSelf(tt.args.nums); !reflect.DeepEqual(got, tt.want) { - t.Errorf("productExceptSelf() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram.go deleted file mode 100644 index ceba532ea..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram.go +++ /dev/null @@ -1,31 +0,0 @@ -package isAnagram - -func isAnagram(s string, t string) bool { - characters := make(map[byte]int) - - if len(s) != len(t) { - return false - } - - for i := 0; i < len(s); i++ { - _, ok := characters[s[i]] - if !ok { - characters[s[i]] = 1 - } else { - characters[s[i]] += 1 - } - - } - - for i := 0; i < len(t); i++ { - val, ok := characters[t[i]] - if ok && val > 0 { - characters[t[i]] -= 1 - } else { - return false - } - } - - return true - -} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram_test.go deleted file mode 100644 index fa6b127df..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/242_Valid_Anagram/242_Valid_Anagram_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package isAnagram - -import "testing" - -func Test_isAnagram(t *testing.T) { - type args struct { - s string - t string - } - tests := []struct { - name string - args args - want bool - }{ - { - name: "case1", - args: args{ - s: "anagram", - t: "nagaram", - }, - want: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := isAnagram(tt.args.s, tt.args.t); got != tt.want { - t.Errorf("isAnagram() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go deleted file mode 100644 index 1b92ea271..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go +++ /dev/null @@ -1,47 +0,0 @@ -package topKFrequent - -import "fmt" - -func main() { - nums := []int{4, 1, -1, 2, -1, 2, 3} - k := 2 - result := topKFrequent(nums, k) - fmt.Println("result", result) -} - -func getElementFrequencyMap(nums []int) map[int]int { - freqMap := make(map[int]int) - for _, value := range nums { - _, ok := freqMap[value] - if !ok { - freqMap[value] = 1 - } else { - freqMap[value] += 1 - } - } - return freqMap -} - -func topKFrequent(nums []int, k int) []int { - var result []int - freqMap := getElementFrequencyMap(nums) - fmt.Println(freqMap) - - //bucket sort - bucket := make([][]int, len(nums)+1) - for key, value := range freqMap { - bucket[value] = append(bucket[value], key) - } - - i := len(bucket) - 1 - for i >= 0 { - if len(bucket[i]) > 0 { - result = append(result, bucket[i]...) - if len(result) >= k { - return result[:k] - } - } - i-- - } - return result -} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go deleted file mode 100644 index dd8539393..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package topKFrequent - -import ( - "reflect" - "testing" -) - -func Test_topKFrequent(t *testing.T) { - type args struct { - nums []int - k int - } - tests := []struct { - name string - args args - want []int - }{ - { - name: "case1", - args: args{ - nums: []int{4, 1, -1, 2, -1, 2, 3}, - k: 2, - }, - want: []int{-1, 2}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := topKFrequent(tt.args.nums, tt.args.k); !reflect.DeepEqual(got, tt.want) { - t.Errorf("topKFrequent() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams.go deleted file mode 100644 index f16690908..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams.go +++ /dev/null @@ -1,23 +0,0 @@ -package groupAnagrams - -func groupAnagrams(strs []string) [][]string { - var result [][]string - strsMap := make(map[[26]int][]string) - var charArray [26]int - var anagramGroup []string - for i := 0; i < len(strs); i++ { - for _, char := range strs[i] { - charIndex := char - 'a' - charArray[charIndex] += 1 - } - anagramGroup = strsMap[charArray] - anagramGroup = append(anagramGroup, strs[i]) - strsMap[charArray] = anagramGroup - charArray = [26]int{} - } - // fmt.Println(strsMap) - for _, value := range strsMap { - result = append(result, value) - } - return result -} diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams_test.go b/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams_test.go deleted file mode 100644 index 32f86b980..000000000 --- a/go/01_arrays_and_hashing/665_Non_decreasing_Array/49_Group_Anagrams/49_Group_Anagrams_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package groupAnagrams - -import ( - "reflect" - "testing" -) - -func Test_groupAnagrams(t *testing.T) { - type args struct { - strs []string - } - tests := []struct { - name string - args args - want [][]string - }{ - { - name: "case1", - args: args{ - []string{ - "cat", - "bat", - "tac", - "ate", - "eat", - }, - }, - want: [][]string{ - {"cat", "tac"}, - {"bat"}, - {"ate", "eat"}, - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := groupAnagrams(tt.args.strs); !reflect.DeepEqual(got, tt.want) { - t.Errorf("groupAnagrams() = %v, want %v", got, tt.want) - } - }) - } -} From 7ed0b173669b97361aecc431d7c1e8fba325ec84 Mon Sep 17 00:00:00 2001 From: aa0 <71089234+Ahmad-A0@users.noreply.github.com> Date: Sat, 9 Jul 2022 17:20:50 +0100 Subject: [PATCH 08/19] Remove `.vscode` folder --- .vscode/settings.json | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 4e4bb40dc..000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "workbench.colorCustomizations": { - "sideBar.background": "#f9fdf9", - "editor.lineHighlightBackground": "#1073cf2d", - "editor.lineHighlightBorder": "#9fced11f", - "activityBar.background": "#422717", - "titleBar.activeBackground": "#5C3720", - "titleBar.activeForeground": "#FDFBFA" - } -} \ No newline at end of file From c51d9867aa4416636ad3ba84b2c260d482d11e59 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Sat, 9 Jul 2022 16:48:31 +0000 Subject: [PATCH 09/19] encode and decode --- .../271_encode_and_decode.go | 33 ++++++++++ .../271_encode_and_decode_test.go | 66 +++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode.go create mode 100644 go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode_test.go diff --git a/go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode.go b/go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode.go new file mode 100644 index 000000000..136a7b60d --- /dev/null +++ b/go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode.go @@ -0,0 +1,33 @@ +package encodeanddecode + +import ( + "fmt" + "strconv" + "strings" +) + +func encode(strs []string) string { + delimiter := "#" + for i := 0; i < len(strs); i++ { + strs[i] = strconv.Itoa(len(strs[i])) + delimiter + strs[i] + } + return strings.Join(strs, "") +} + +func decode(str string) []string { + var result []string + i := 0 + + for i < len(str) { + j := i + for str[j] != '#' { + j += 1 + } + lengthOfString, _ := strconv.Atoi(str[i:j]) + fmt.Println(i, lengthOfString) + result = append(result, str[j+1:j+1+lengthOfString]) + i = j + 1 + lengthOfString + fmt.Println(i) + } + return result +} diff --git a/go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode_test.go b/go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode_test.go new file mode 100644 index 000000000..7f2507f6e --- /dev/null +++ b/go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode_test.go @@ -0,0 +1,66 @@ +package encodeanddecode + +import ( + "reflect" + "testing" +) + +func Test_encode(t *testing.T) { + type args struct { + strs []string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "encode-1", + args: args{ + strs: []string{ + "this", + "is", + "testString", + }, + }, + want: "4#this2#is10#testString", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := encode(tt.args.strs); !reflect.DeepEqual(got, tt.want) { + t.Errorf("encode() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_decode(t *testing.T) { + type args struct { + str string + } + tests := []struct { + name string + args args + want []string + }{ + { + name: "decode", + args: args{ + str: "4#this2#is10#testString", + }, + want: []string{ + "this", + "is", + "testString", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := decode(tt.args.str); !reflect.DeepEqual(got, tt.want) { + t.Errorf("decode() = %v, want %v", got, tt.want) + } + }) + } +} From 5d1d2f9c7cfd845bfce735e495832ad7fd43a413 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Sat, 9 Jul 2022 17:21:01 +0000 Subject: [PATCH 10/19] Longest consecutive sequence --- .../128_longest_consecutive_sequence.go | 48 +++++++++++++++++++ .../128_longest_consecutive_sequence_test.go | 36 ++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go create mode 100644 go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go diff --git a/go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go b/go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go new file mode 100644 index 000000000..1c9e3a2c5 --- /dev/null +++ b/go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go @@ -0,0 +1,48 @@ +package longestconsecutivesequence + +import "fmt" + +func buildSet(nums []int) map[int]bool { + set := make(map[int]bool) + for _, val := range nums { + set[val] = true + } + return set +} + +func calculateConsecutiveSequence(value int, set map[int]bool) int { + length := 1 + currVal := value + for { + currVal += 1 + _, ok := set[currVal] + if ok { + length += 1 + } else { + break + } + } + return length +} + +func longestConsecutive(nums []int) int { + maxConsecutiveLength := 0 + set := buildSet(nums) + + for i := 0; i < len(nums); i++ { + _, ok := set[nums[i]-1] + if !ok { + fmt.Println("Left is not present => start of a sequence") + currLongestConsecutiveLength := calculateConsecutiveSequence(nums[i], set) + maxConsecutiveLength = max(maxConsecutiveLength, currLongestConsecutiveLength) + } + } + return maxConsecutiveLength +} + +func max(i int, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go b/go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go new file mode 100644 index 000000000..113ad5481 --- /dev/null +++ b/go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go @@ -0,0 +1,36 @@ +package longestconsecutivesequence + +import "testing" + +func Test_longestConsecutive(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + nums: []int{100, 4, 200, 1, 3, 2}, + }, + want: 4, + }, + { + name: "case2", + args: args{ + nums: []int{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}, + }, + want: 9, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := longestConsecutive(tt.args.nums); got != tt.want { + t.Errorf("longestConsecutive() = %v, want %v", got, tt.want) + } + }) + } +} From 0d9cbf4c0fb4e9b031992fae67b89f5ee430b693 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Sun, 10 Jul 2022 04:08:30 +0000 Subject: [PATCH 11/19] Added solutions for twoPointers technique --- .../125_ValidPalindrome.go | 29 +++++++++ .../125_ValidPalindrome_test.go | 43 +++++++++++++ go/TwoPointers/15_threeSum/15_threeSum.go | 35 +++++++++++ .../15_threeSum/15_threeSum_test.go | 51 +++++++++++++++ go/TwoPointers/167_Two_SumII/167_Two_SumII.go | 20 ++++++ .../167_Two_SumII/167_Two_SumII_test.go | 50 +++++++++++++++ .../42_Trapping_Rain_Water.go | 63 +++++++++++++++++++ .../42_Trapping_Rain_Water_test.go | 36 +++++++++++ 8 files changed, 327 insertions(+) create mode 100644 go/TwoPointers/125_ValidPalindrome/125_ValidPalindrome.go create mode 100644 go/TwoPointers/125_ValidPalindrome/125_ValidPalindrome_test.go create mode 100644 go/TwoPointers/15_threeSum/15_threeSum.go create mode 100644 go/TwoPointers/15_threeSum/15_threeSum_test.go create mode 100644 go/TwoPointers/167_Two_SumII/167_Two_SumII.go create mode 100644 go/TwoPointers/167_Two_SumII/167_Two_SumII_test.go create mode 100644 go/TwoPointers/42_Trapping_Rain_Water/42_Trapping_Rain_Water.go create mode 100644 go/TwoPointers/42_Trapping_Rain_Water/42_Trapping_Rain_Water_test.go diff --git a/go/TwoPointers/125_ValidPalindrome/125_ValidPalindrome.go b/go/TwoPointers/125_ValidPalindrome/125_ValidPalindrome.go new file mode 100644 index 000000000..b35bb199f --- /dev/null +++ b/go/TwoPointers/125_ValidPalindrome/125_ValidPalindrome.go @@ -0,0 +1,29 @@ +package validpalindrome + +import ( + "fmt" + "log" + "regexp" + "strings" +) + +func isPalindrome(s string) bool { + s = strings.ToLower(s) + s = strings.Replace(s, " ", "", -1) + reg, err := regexp.Compile("[^a-z0-9]+") + if err != nil { + log.Fatal(err) + } + s = reg.ReplaceAllString(s, "") + fmt.Println(s) + leftPointer := 0 + rightPointer := len(s) - 1 + for leftPointer <= rightPointer { + if s[leftPointer] != s[rightPointer] { + return false + } + leftPointer++ + rightPointer-- + } + return true +} diff --git a/go/TwoPointers/125_ValidPalindrome/125_ValidPalindrome_test.go b/go/TwoPointers/125_ValidPalindrome/125_ValidPalindrome_test.go new file mode 100644 index 000000000..7cb05f112 --- /dev/null +++ b/go/TwoPointers/125_ValidPalindrome/125_ValidPalindrome_test.go @@ -0,0 +1,43 @@ +package validpalindrome + +import "testing" + +func Test_isPalindrome(t *testing.T) { + type args struct { + s string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + s: "A man, a plan, a canal: Panama", + }, + want: true, + }, + { + name: "case2", + args: args{ + s: "race a car", + }, + want: false, + }, + { + name: "case3", + args: args{ + s: " ", + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isPalindrome(tt.args.s); got != tt.want { + t.Errorf("isPalindrome() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/TwoPointers/15_threeSum/15_threeSum.go b/go/TwoPointers/15_threeSum/15_threeSum.go new file mode 100644 index 000000000..ab485632d --- /dev/null +++ b/go/TwoPointers/15_threeSum/15_threeSum.go @@ -0,0 +1,35 @@ +package threesum + +import ( + "fmt" + "sort" +) + +func threeSum(nums []int) [][]int { + sort.Ints(nums) + fmt.Println(nums) + result := [][]int{} + for i := 0; i < len(nums); i++ { + if i > 0 && nums[i] == nums[i-1] { + continue + } + newTarget := 0 - nums[i] + leftPointer := i + 1 + rightPointer := len(nums) - 1 + for leftPointer < rightPointer { + if newTarget == nums[leftPointer]+nums[rightPointer] { + result = append(result, []int{nums[i], nums[leftPointer], nums[rightPointer]}) + leftPointer++ + for nums[leftPointer] == nums[leftPointer-1] && leftPointer < rightPointer { + leftPointer++ + } + } + if nums[leftPointer]+nums[rightPointer] < newTarget { + leftPointer++ + } else { + rightPointer-- + } + } + } + return result +} diff --git a/go/TwoPointers/15_threeSum/15_threeSum_test.go b/go/TwoPointers/15_threeSum/15_threeSum_test.go new file mode 100644 index 000000000..e4b801da4 --- /dev/null +++ b/go/TwoPointers/15_threeSum/15_threeSum_test.go @@ -0,0 +1,51 @@ +package threesum + +import ( + "reflect" + "testing" +) + +func Test_threeSum(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want [][]int + }{ + { + name: "case1", + args: args{ + nums: []int{-1, 0, 1, 2, -1, -4}, + }, + want: [][]int{ + {-1, -1, 2}, + {-1, 0, 1}, + }, + }, + { + name: "case2", + args: args{ + nums: []int{0, 1, 1}, + }, + want: [][]int{}, + }, + { + name: "case1", + args: args{ + nums: []int{0, 0, 0}, + }, + want: [][]int{ + {0, 0, 0}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := threeSum(tt.args.nums); !reflect.DeepEqual(got, tt.want) { + t.Errorf("threesum() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/TwoPointers/167_Two_SumII/167_Two_SumII.go b/go/TwoPointers/167_Two_SumII/167_Two_SumII.go new file mode 100644 index 000000000..733bfd66d --- /dev/null +++ b/go/TwoPointers/167_Two_SumII/167_Two_SumII.go @@ -0,0 +1,20 @@ +package twosumii + +func twoSum(numbers []int, target int) []int { + left := 0 + right := len(numbers) - 1 + currentSum := 0 + + for left < right { + currentSum = numbers[left] + numbers[right] + if currentSum == target { + return []int{left + 1, right + 1} + } else if currentSum > target { + //move the right pointer + right -= 1 + } else { + left += 1 + } + } + return nil +} diff --git a/go/TwoPointers/167_Two_SumII/167_Two_SumII_test.go b/go/TwoPointers/167_Two_SumII/167_Two_SumII_test.go new file mode 100644 index 000000000..267e83b85 --- /dev/null +++ b/go/TwoPointers/167_Two_SumII/167_Two_SumII_test.go @@ -0,0 +1,50 @@ +package twosumii + +import ( + "reflect" + "testing" +) + +func Test_twoSum(t *testing.T) { + type args struct { + numbers []int + target int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "case1", + args: args{ + numbers: []int{2, 7, 11, 15}, + target: 9, + }, + want: []int{1, 2}, + }, + { + name: "case2", + args: args{ + numbers: []int{2, 3, 4}, + target: 6, + }, + want: []int{1, 3}, + }, + { + name: "case3", + args: args{ + numbers: []int{-1, 0}, + target: -1, + }, + want: []int{1, 2}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := twoSum(tt.args.numbers, tt.args.target); !reflect.DeepEqual(got, tt.want) { + t.Errorf("twoSum() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/TwoPointers/42_Trapping_Rain_Water/42_Trapping_Rain_Water.go b/go/TwoPointers/42_Trapping_Rain_Water/42_Trapping_Rain_Water.go new file mode 100644 index 000000000..d511f896c --- /dev/null +++ b/go/TwoPointers/42_Trapping_Rain_Water/42_Trapping_Rain_Water.go @@ -0,0 +1,63 @@ +package trappingrainwater + +func populateMaxValuesToLeft(height []int) []int { + leftArray := make([]int, len(height)) + leftArray[0] = 0 + currMax := height[0] + for i := 1; i < len(leftArray); i++ { + if height[i] > currMax { + leftArray[i] = height[i] + currMax = height[i] + } else { + leftArray[i] = currMax + } + } + return leftArray +} + +func populateMaxValuesRight(height []int) []int { + rightMaxArray := make([]int, len(height)) + rightMaxArray[len(rightMaxArray)-1] = 0 + currMax := height[len(rightMaxArray)-1] + i := len(rightMaxArray) - 2 + for i >= 0 { + if height[i] > currMax { + rightMaxArray[i] = height[i] + currMax = height[i] + } else { + rightMaxArray[i] = currMax + } + i-- + } + return rightMaxArray +} + +func trap(height []int) int { + leftMaxArray := populateMaxValuesToLeft(height) + rightMaxArray := populateMaxValuesRight(height) + trappedWaterArray := make([]int, len(height)) + trappedWaterArray[0] = 0 + trappedWaterArray[len(height)-1] = 0 + for i := 1; i < len(height)-1; i++ { + minHeightToTrap := min(leftMaxArray[i], rightMaxArray[i]) + // trapped water is min height - current height + trappedWater := minHeightToTrap - height[i] + trappedWaterArray[i] = trappedWater + } + return sum(trappedWaterArray) +} + +func min(i, j int) int { + if i > j { + return j + } + return i +} + +func sum(arr []int) int { + var sum int + for _, value := range arr { + sum += value + } + return sum +} diff --git a/go/TwoPointers/42_Trapping_Rain_Water/42_Trapping_Rain_Water_test.go b/go/TwoPointers/42_Trapping_Rain_Water/42_Trapping_Rain_Water_test.go new file mode 100644 index 000000000..8ec69e6df --- /dev/null +++ b/go/TwoPointers/42_Trapping_Rain_Water/42_Trapping_Rain_Water_test.go @@ -0,0 +1,36 @@ +package trappingrainwater + +import "testing" + +func Test_trap(t *testing.T) { + type args struct { + height []int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + height: []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}, + }, + want: 6, + }, + { + name: "case2", + args: args{ + height: []int{4, 2, 0, 3, 2, 5}, + }, + want: 9, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := trap(tt.args.height); got != tt.want { + t.Errorf("trap() = %v, want %v", got, tt.want) + } + }) + } +} From 68c04ba7892be2d3f693d9080f09749dfa26b768 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Mon, 11 Jul 2022 06:08:58 +0000 Subject: [PATCH 12/19] Sliding window technique problems addition --- .../121_Best_Time_to_Buy_and_Sell_Stock.go | 26 +++++++++++ ...21_Best_Time_to_Buy_and_Sell_Stock_test.go | 38 ++++++++++++++++ ..._Substring_Without_Repeating_Characters.go | 35 +++++++++++++++ ...tring_Without_Repeating_Characters_test.go | 43 +++++++++++++++++++ .../11_container_with_most_water.go | 31 +++++++++++++ .../11_container_with_most_water_test.go | 36 ++++++++++++++++ 6 files changed, 209 insertions(+) create mode 100644 go/SlidingWindow/121_Best_Time_to_Buy_and_Sell_Stock/121_Best_Time_to_Buy_and_Sell_Stock.go create mode 100644 go/SlidingWindow/121_Best_Time_to_Buy_and_Sell_Stock/121_Best_Time_to_Buy_and_Sell_Stock_test.go create mode 100644 go/SlidingWindow/3_Longest_Substring_Without_Repeating_Characters/3_Longest_Substring_Without_Repeating_Characters.go create mode 100644 go/SlidingWindow/3_Longest_Substring_Without_Repeating_Characters/3_Longest_Substring_Without_Repeating_Characters_test.go create mode 100644 go/TwoPointers/11_container_with_most_water/11_container_with_most_water.go create mode 100644 go/TwoPointers/11_container_with_most_water/11_container_with_most_water_test.go diff --git a/go/SlidingWindow/121_Best_Time_to_Buy_and_Sell_Stock/121_Best_Time_to_Buy_and_Sell_Stock.go b/go/SlidingWindow/121_Best_Time_to_Buy_and_Sell_Stock/121_Best_Time_to_Buy_and_Sell_Stock.go new file mode 100644 index 000000000..460c1642c --- /dev/null +++ b/go/SlidingWindow/121_Best_Time_to_Buy_and_Sell_Stock/121_Best_Time_to_Buy_and_Sell_Stock.go @@ -0,0 +1,26 @@ +package besttimetobuyandsellstock + +func maxProfit(prices []int) int { + var maxProfit int + leftPointer := 0 + rightPointer := 1 + + for rightPointer < len(prices) { + if prices[leftPointer] < prices[rightPointer] { + profit := prices[rightPointer] - prices[leftPointer] + maxProfit = max(maxProfit, profit) + } else { + leftPointer = rightPointer + } + rightPointer++ + } + + return maxProfit +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/SlidingWindow/121_Best_Time_to_Buy_and_Sell_Stock/121_Best_Time_to_Buy_and_Sell_Stock_test.go b/go/SlidingWindow/121_Best_Time_to_Buy_and_Sell_Stock/121_Best_Time_to_Buy_and_Sell_Stock_test.go new file mode 100644 index 000000000..be0f915d2 --- /dev/null +++ b/go/SlidingWindow/121_Best_Time_to_Buy_and_Sell_Stock/121_Best_Time_to_Buy_and_Sell_Stock_test.go @@ -0,0 +1,38 @@ +package besttimetobuyandsellstock + +import ( + "testing" +) + +func Test_maxProfit(t *testing.T) { + type args struct { + prices []int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + prices: []int{7, 1, 5, 3, 6, 4}, + }, + want: 5, + }, + { + name: "case2", + args: args{ + prices: []int{7, 6, 4, 3, 1}, + }, + want: 0, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := maxProfit(tt.args.prices); got != tt.want { + t.Errorf("maxProfit() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/SlidingWindow/3_Longest_Substring_Without_Repeating_Characters/3_Longest_Substring_Without_Repeating_Characters.go b/go/SlidingWindow/3_Longest_Substring_Without_Repeating_Characters/3_Longest_Substring_Without_Repeating_Characters.go new file mode 100644 index 000000000..e325ecbc2 --- /dev/null +++ b/go/SlidingWindow/3_Longest_Substring_Without_Repeating_Characters/3_Longest_Substring_Without_Repeating_Characters.go @@ -0,0 +1,35 @@ +package longestsubstringwithoutrepeatingcharacters + +func lengthOfLongestSubstring(s string) int { + if s == "" { + return 0 + } + longestSubstring := 1 + charMap := make(map[byte]int) + leftPointer := 0 + rightPointer := 0 + + for rightPointer < len(s) { + _, ok := charMap[s[rightPointer]] + if !ok { + charMap[s[rightPointer]] = 1 + longestSubstring = max(longestSubstring, (rightPointer-leftPointer)+1) + // char is not present in set increment the window + rightPointer++ + + } else { + // Adding the character is making the window have duplicates. delete the left pointer data and incremenet by 1 + delete(charMap, s[leftPointer]) + leftPointer++ + } + } + + return longestSubstring +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/SlidingWindow/3_Longest_Substring_Without_Repeating_Characters/3_Longest_Substring_Without_Repeating_Characters_test.go b/go/SlidingWindow/3_Longest_Substring_Without_Repeating_Characters/3_Longest_Substring_Without_Repeating_Characters_test.go new file mode 100644 index 000000000..91c0703ce --- /dev/null +++ b/go/SlidingWindow/3_Longest_Substring_Without_Repeating_Characters/3_Longest_Substring_Without_Repeating_Characters_test.go @@ -0,0 +1,43 @@ +package longestsubstringwithoutrepeatingcharacters + +import "testing" + +func Test_lengthOfLongestSubstring(t *testing.T) { + type args struct { + s string + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + s: "abcabcbb", + }, + want: 3, + }, + { + name: "case2", + args: args{ + s: "bbbbb", + }, + want: 1, + }, + { + name: "case3", + args: args{ + s: "pwwkew", + }, + want: 3, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := lengthOfLongestSubstring(tt.args.s); got != tt.want { + t.Errorf("lengthOfLongestSubstring() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/TwoPointers/11_container_with_most_water/11_container_with_most_water.go b/go/TwoPointers/11_container_with_most_water/11_container_with_most_water.go new file mode 100644 index 000000000..e01a2aea9 --- /dev/null +++ b/go/TwoPointers/11_container_with_most_water/11_container_with_most_water.go @@ -0,0 +1,31 @@ +package containerwithmostwater + +func maxArea(height []int) int { + var maxArea int + leftPointer := 0 + rightPointer := len(height) - 1 + for leftPointer < rightPointer { + area := (rightPointer - leftPointer) * min(height[leftPointer], height[rightPointer]) + maxArea = max(area, maxArea) + if height[leftPointer] < height[rightPointer] { + leftPointer++ + } else { + rightPointer-- + } + } + return maxArea +} + +func min(i, j int) int { + if i < j { + return i + } + return j +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/TwoPointers/11_container_with_most_water/11_container_with_most_water_test.go b/go/TwoPointers/11_container_with_most_water/11_container_with_most_water_test.go new file mode 100644 index 000000000..4c220af25 --- /dev/null +++ b/go/TwoPointers/11_container_with_most_water/11_container_with_most_water_test.go @@ -0,0 +1,36 @@ +package containerwithmostwater + +import "testing" + +func Test_maxArea(t *testing.T) { + type args struct { + height []int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + height: []int{1, 8, 6, 2, 5, 4, 8, 3, 7}, + }, + want: 49, + }, + { + name: "case2", + args: args{ + height: []int{1, 1}, + }, + want: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := maxArea(tt.args.height); got != tt.want { + t.Errorf("maxArea() = %v, want %v", got, tt.want) + } + }) + } +} From b4e48e18294e828b10419fdcc600df229d4280df Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Wed, 13 Jul 2022 08:44:38 +0000 Subject: [PATCH 13/19] Added solution for longest repeating character replacem,ent and permutation of a string --- ...Longest_Repeating_Character_Replacement.go | 42 +++++++++++ ...st_Repeating_Character_Replacement_test.go | 39 +++++++++++ .../567_Permutation_in_String.go | 70 +++++++++++++++++++ .../567_Permutation_in_String_test.go | 39 +++++++++++ 4 files changed, 190 insertions(+) create mode 100644 go/SlidingWindow/424_Longest_Repeating_Character_Replacement/424_Longest_Repeating_Character_Replacement.go create mode 100644 go/SlidingWindow/424_Longest_Repeating_Character_Replacement/424_Longest_Repeating_Character_Replacement_test.go create mode 100644 go/SlidingWindow/567_Permutation_in_String/567_Permutation_in_String.go create mode 100644 go/SlidingWindow/567_Permutation_in_String/567_Permutation_in_String_test.go diff --git a/go/SlidingWindow/424_Longest_Repeating_Character_Replacement/424_Longest_Repeating_Character_Replacement.go b/go/SlidingWindow/424_Longest_Repeating_Character_Replacement/424_Longest_Repeating_Character_Replacement.go new file mode 100644 index 000000000..cf96f8f4d --- /dev/null +++ b/go/SlidingWindow/424_Longest_Repeating_Character_Replacement/424_Longest_Repeating_Character_Replacement.go @@ -0,0 +1,42 @@ +package longestrepeatingcharacterreplacement + +func characterReplacement(s string, k int) int { + var result int + var maxFrequency int + charMap := make(map[byte]int) + leftPointer := 0 + rightPointer := 0 + + for rightPointer < len(s) { + lengthOfWindow := rightPointer - leftPointer + 1 + + _, ok := charMap[s[rightPointer]] + if ok { + charMap[s[rightPointer]]++ + } else { + charMap[s[rightPointer]] = 1 + } + maxFrequency = max(maxFrequency, charMap[s[rightPointer]]) + + if lengthOfWindow-maxFrequency <= k { + // we can still add elements to the subarray so move the right pointer forward and + // update the result with the current max window + rightPointer++ + result = max(result, lengthOfWindow) + } else { + charMap[s[leftPointer]]-- + // since the previous condition failed and we didnt increment the right pointer + // if we dont do this the right pointer frequency will be incremented again. + charMap[s[rightPointer]]-- + leftPointer++ + } + } + return result +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/SlidingWindow/424_Longest_Repeating_Character_Replacement/424_Longest_Repeating_Character_Replacement_test.go b/go/SlidingWindow/424_Longest_Repeating_Character_Replacement/424_Longest_Repeating_Character_Replacement_test.go new file mode 100644 index 000000000..8d19286ed --- /dev/null +++ b/go/SlidingWindow/424_Longest_Repeating_Character_Replacement/424_Longest_Repeating_Character_Replacement_test.go @@ -0,0 +1,39 @@ +package longestrepeatingcharacterreplacement + +import "testing" + +func Test_characterReplacement(t *testing.T) { + type args struct { + s string + k int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + s: "ABAB", + k: 2, + }, + want: 4, + }, + { + name: "case2", + args: args{ + s: "AABABBA", + k: 1, + }, + want: 4, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := characterReplacement(tt.args.s, tt.args.k); got != tt.want { + t.Errorf("characterReplacement() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/SlidingWindow/567_Permutation_in_String/567_Permutation_in_String.go b/go/SlidingWindow/567_Permutation_in_String/567_Permutation_in_String.go new file mode 100644 index 000000000..31685daf6 --- /dev/null +++ b/go/SlidingWindow/567_Permutation_in_String/567_Permutation_in_String.go @@ -0,0 +1,70 @@ +package permutationinstring + +import "fmt" + +func checkInclusion(s1 string, s2 string) bool { + var charMap1, charMap2 [26]int + if len(s1) > len(s2) { + return false + } + + for i := range s1 { + charMap1[s1[i]-'a']++ + charMap2[s2[i]-'a']++ + } + + matchesCount := getMatchCount(charMap1, charMap2) + fmt.Println(matchesCount) + + if matchesCount == 26 { + return true + } + + leftPointer := 1 + rightPointer := len(s1) + for rightPointer < len(s2) { + if matchesCount == 26 { + return true + } + // moving the left pointer right means that we are removing one element. + // Check if this is causing the matches to be disturbed + // there are 2 cases arising here. + // Is already matched record becoming unmatched. By increasing count by 1 we are unmatching it + // Is unmatching count becoming matched by adding 1 + + charMap2[s2[leftPointer-1]-'a']-- // decrease the count by removing the element + val1 := charMap1[s2[leftPointer-1]-'a'] + val2 := charMap2[s2[leftPointer-1]-'a'] + if val1 == val2 { + matchesCount++ // unmatched count became matched + } else if val1 == val2+1 { + matchesCount-- + // matched count is becoming unmatched. How do we check if it became unmatched ? + // Add 1 to the charMap2 value because we subtracted it earlier and check if it was matching. If yes + // that means that it was previously matched and became unmatched + } + + charMap2[s2[rightPointer]-'a']++ + val1 = charMap1[s2[rightPointer]-'a'] + val2 = charMap2[s2[rightPointer]-'a'] + if val1 == val2 { + matchesCount++ + } else if val1+1 == val2 { + matchesCount-- + } + leftPointer++ + rightPointer++ + } + return matchesCount == 26 +} + +func getMatchCount(charMap1 [26]int, charMap2 [26]int) int { + var matchCount int + for charMap1Key, charMap1Val := range charMap1 { + charMap2Val := charMap2[charMap1Key] + if charMap2Val == charMap1Val { + matchCount++ + } + } + return matchCount +} diff --git a/go/SlidingWindow/567_Permutation_in_String/567_Permutation_in_String_test.go b/go/SlidingWindow/567_Permutation_in_String/567_Permutation_in_String_test.go new file mode 100644 index 000000000..75a4c477b --- /dev/null +++ b/go/SlidingWindow/567_Permutation_in_String/567_Permutation_in_String_test.go @@ -0,0 +1,39 @@ +package permutationinstring + +import "testing" + +func Test_checkInclusion(t *testing.T) { + type args struct { + s1 string + s2 string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + s1: "abc", + s2: "eidbacooo", + }, + want: true, + }, + { + name: "case2", + args: args{ + s1: "ab", + s2: "eidboaoo", + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := checkInclusion(tt.args.s1, tt.args.s2); got != tt.want { + t.Errorf("checkInclusion() = %v, want %v", got, tt.want) + } + }) + } +} From 6de14a087b735a29be325c4a1a5ae49345d800b5 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Wed, 13 Jul 2022 14:58:47 +0000 Subject: [PATCH 14/19] 76_Minimum_Window_Substring --- .../76_Minimum_Window_Substring.go | 77 +++++++++++++++++++ .../76_Minimum_Window_Substring_test.go | 63 +++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 go/SlidingWindow/76_Minimum_Window_Substring/76_Minimum_Window_Substring.go create mode 100644 go/SlidingWindow/76_Minimum_Window_Substring/76_Minimum_Window_Substring_test.go diff --git a/go/SlidingWindow/76_Minimum_Window_Substring/76_Minimum_Window_Substring.go b/go/SlidingWindow/76_Minimum_Window_Substring/76_Minimum_Window_Substring.go new file mode 100644 index 000000000..7a9cb62e0 --- /dev/null +++ b/go/SlidingWindow/76_Minimum_Window_Substring/76_Minimum_Window_Substring.go @@ -0,0 +1,77 @@ +package minimumwindowsubstring + +// When needCounter == haveCounter , it means that the substring we have calculated till this position is +// having all the values of t string +// next step is we will move the left pointer such the we break the condition of substring having all the values. +// once we break the condition we find the new substring to have all the values by moving the right pointer. +// repeat the process. The point where we are breaking the condition of having needCounter == haveCounter , we track the +// lengths and get the minimum value + +func minWindow(s string, t string) string { + var charMap1, charMap2 [60]int + var needCounter, haveCounter int + var beginPoint, endPoint, lengthOfString int + lengthOfString = 2147483647 + if len(s) < len(t) { + return "" + } + + charMap1, needCounter = getNeedCounter(t) + + leftPointer := 0 + rightPointer := 0 + for rightPointer < len(s) { + // add the character to the map and if the count of characters equal to the map we created for `t` + // increment the have counter + charMap2[s[rightPointer]-'A']++ + if charMap1[s[rightPointer]-'A'] == charMap2[s[rightPointer]-'A'] { + haveCounter++ + } + + // get the new string where the have counter and need counter mismatched + for needCounter == haveCounter { + if charMap2[s[leftPointer]-'A'] > 0 { + charMap2[s[leftPointer]-'A']-- + + } + + // haveCounter needs to be decremented only when the number of characters for the `s` string + // is less than the characters of `t` string. This means that the substring in `s` cannot form `t` + // string using the current set of characters + if charMap2[s[leftPointer]-'A'] < charMap1[s[leftPointer]-'A'] { + haveCounter-- + + // getting the (length, positions of left and right pointer) at the nearest place + // where moving the left pointer will make the substring not have all the values from the `t` string. + // update only when new length of string is less than the previous obtained length since we need minimum substring + + if (rightPointer - leftPointer + 1) < lengthOfString { + beginPoint = leftPointer + endPoint = rightPointer + lengthOfString = rightPointer - leftPointer + 1 + } + } + leftPointer++ + } + rightPointer++ + } + if lengthOfString <= len(s) { + return s[beginPoint : endPoint+1] + } + return "" +} + +func getNeedCounter(t string) ([60]int, int) { + var charMap1 [60]int + var needCounter int + for i := range t { + charMap1[t[i]-'A']++ + } + for i := range charMap1 { + if charMap1[i] > 0 { + needCounter++ + } + } + + return charMap1, needCounter +} diff --git a/go/SlidingWindow/76_Minimum_Window_Substring/76_Minimum_Window_Substring_test.go b/go/SlidingWindow/76_Minimum_Window_Substring/76_Minimum_Window_Substring_test.go new file mode 100644 index 000000000..7e3026176 --- /dev/null +++ b/go/SlidingWindow/76_Minimum_Window_Substring/76_Minimum_Window_Substring_test.go @@ -0,0 +1,63 @@ +package minimumwindowsubstring + +import "testing" + +func Test_minWindow(t *testing.T) { + type args struct { + s string + t string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "case1", + args: args{ + s: "ADOBECODEBANC", + t: "ABC", + }, + want: "BANC", + }, + { + name: "case2", + args: args{ + s: "a", + t: "a", + }, + want: "a", + }, + { + name: "case3", + args: args{ + s: "a", + t: "aa", + }, + want: "", + }, + { + name: "case4", + args: args{ + s: "abcd", + t: "e", + }, + want: "", + }, + { + name: "case5", + args: args{ + s: "cabwefgewcwaefgcf", + t: "cae", + }, + want: "cwae", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := minWindow(tt.args.s, tt.args.t); got != tt.want { + t.Errorf("minWindow() = %v, want %v", got, tt.want) + } + }) + } +} From 284d198abda60721934022e7ca382933f6dd0310 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Thu, 14 Jul 2022 05:34:07 +0000 Subject: [PATCH 15/19] Added problems for stacks --- .../150_Evaluate_Reverse_Polish_Notation.go | 41 +++++++++ ...0_Evaluate_Reverse_Polish_Notation_test.go | 43 ++++++++++ go/stack/155_Min_Stack/155_Min_Stack.go | 53 ++++++++++++ .../20_Valid_Parentheses.go | 72 ++++++++++++++++ .../20_Valid_Parentheses_test.go | 85 +++++++++++++++++++ .../22_Generate_Parentheses.go | 24 ++++++ .../22_Generate_Parentheses_test.go | 39 +++++++++ 7 files changed, 357 insertions(+) create mode 100644 go/stack/150_Evaluate_Reverse_Polish_Notation/150_Evaluate_Reverse_Polish_Notation.go create mode 100644 go/stack/150_Evaluate_Reverse_Polish_Notation/150_Evaluate_Reverse_Polish_Notation_test.go create mode 100644 go/stack/155_Min_Stack/155_Min_Stack.go create mode 100644 go/stack/20_Valid_Parentheses/20_Valid_Parentheses.go create mode 100644 go/stack/20_Valid_Parentheses/20_Valid_Parentheses_test.go create mode 100644 go/stack/22_Generate_Parentheses/22_Generate_Parentheses.go create mode 100644 go/stack/22_Generate_Parentheses/22_Generate_Parentheses_test.go diff --git a/go/stack/150_Evaluate_Reverse_Polish_Notation/150_Evaluate_Reverse_Polish_Notation.go b/go/stack/150_Evaluate_Reverse_Polish_Notation/150_Evaluate_Reverse_Polish_Notation.go new file mode 100644 index 000000000..3fb980c51 --- /dev/null +++ b/go/stack/150_Evaluate_Reverse_Polish_Notation/150_Evaluate_Reverse_Polish_Notation.go @@ -0,0 +1,41 @@ +package evaluatereversepolishnotation + +import "strconv" + +var validOperators = map[string]bool{ + "+": true, + "-": true, + "*": true, + "/": true, +} + +func evalRPN(tokens []string) int { + var stack []int + for i := range tokens { + _, ok := validOperators[tokens[i]] + if !ok { + integer, _ := strconv.Atoi(tokens[i]) + stack = append(stack, integer) + } else { + poppedVal1 := stack[len(stack)-1] + poppedVal2 := stack[len(stack)-2] + stack = stack[:len(stack)-2] + stack = append(stack, performOperaton(poppedVal1, poppedVal2, tokens[i])) + } + } + return stack[len(stack)-1] +} + +func performOperaton(num1 int, num2 int, operator string) int { + var result int + if operator == "+" { + result = num1 + num2 + } else if operator == "-" { + result = num2 - num1 + } else if operator == "/" { + result = num2 / num1 + } else if operator == "*" { + result = num1 * num2 + } + return result +} diff --git a/go/stack/150_Evaluate_Reverse_Polish_Notation/150_Evaluate_Reverse_Polish_Notation_test.go b/go/stack/150_Evaluate_Reverse_Polish_Notation/150_Evaluate_Reverse_Polish_Notation_test.go new file mode 100644 index 000000000..f16a9bfbe --- /dev/null +++ b/go/stack/150_Evaluate_Reverse_Polish_Notation/150_Evaluate_Reverse_Polish_Notation_test.go @@ -0,0 +1,43 @@ +package evaluatereversepolishnotation + +import "testing" + +func Test_evalRPN(t *testing.T) { + type args struct { + tokens []string + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + tokens: []string{"2", "1", "+", "3", "*"}, + }, + want: 9, + }, + { + name: "case2", + args: args{ + tokens: []string{"4", "13", "5", "/", "+"}, + }, + want: 6, + }, + { + name: "case3", + args: args{ + tokens: []string{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}, + }, + want: 22, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := evalRPN(tt.args.tokens); got != tt.want { + t.Errorf("evalRPN() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/stack/155_Min_Stack/155_Min_Stack.go b/go/stack/155_Min_Stack/155_Min_Stack.go new file mode 100644 index 000000000..9b29c39a5 --- /dev/null +++ b/go/stack/155_Min_Stack/155_Min_Stack.go @@ -0,0 +1,53 @@ +package minstack + +type MinStack struct { + stack []int + minStack []int +} + +func Constructor() MinStack { + var stack []int + var minStack []int + return MinStack{ + stack: stack, + minStack: minStack, + } +} + +func (this *MinStack) Push(val int) { + this.stack = append(this.stack, val) + if len(this.minStack) == 0 { + this.minStack = append(this.minStack, val) + } else { + if this.minStack[len(this.minStack)-1] < val { + this.minStack = append(this.minStack, this.minStack[len(this.minStack)-1]) + } else { + this.minStack = append(this.minStack, val) + } + } +} + +func (this *MinStack) Pop() { + if len(this.stack) > 0 { + this.stack = this.stack[:len(this.stack)-1] + this.minStack = this.minStack[:len(this.minStack)-1] + } + return +} + +func (this *MinStack) Top() int { + return this.stack[len(this.stack)-1] +} + +func (this *MinStack) GetMin() int { + return this.minStack[len(this.minStack)-1] +} + +/** + * Your MinStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(val); + * obj.Pop(); + * param_3 := obj.Top(); + * param_4 := obj.GetMin(); + */ diff --git a/go/stack/20_Valid_Parentheses/20_Valid_Parentheses.go b/go/stack/20_Valid_Parentheses/20_Valid_Parentheses.go new file mode 100644 index 000000000..0d85bf239 --- /dev/null +++ b/go/stack/20_Valid_Parentheses/20_Valid_Parentheses.go @@ -0,0 +1,72 @@ +package validparentheses + +type stack struct { + arr []byte +} + +func (s *stack) len() int { + return len(s.arr) +} + +func (s *stack) push(val byte) { + s.arr = append(s.arr, val) +} + +func (s *stack) pop() byte { + var poppedVal byte + if s.len() > 0 { + poppedVal = s.arr[len(s.arr)-1] + s.arr = s.arr[:s.len()-1] + return poppedVal + } + return poppedVal +} + +var charPairing = map[byte]byte{ + '{': '}', + '[': ']', + '(': ')', +} + +func isValid(s string) bool { + stack := stack{} + for i := range s { + if s[i] == '{' || s[i] == '[' || s[i] == '(' { + stack.push(s[i]) + } + if s[i] == '}' || s[i] == ']' || s[i] == ')' { + var poppedVal byte + if stack.len() > 0 { + poppedVal = stack.pop() + } else { + return false + } + if charPairing[poppedVal] != s[i] { + return false + } + } + } + return stack.len() == 0 +} + +func isValid_2(s string) bool { + stack := []byte{} + for i := range s { + if s[i] == '{' || s[i] == '[' || s[i] == '(' { + stack = append(stack, s[i]) + } + if s[i] == '}' || s[i] == ']' || s[i] == ')' { + var poppedVal byte + if len(stack) > 0 { + poppedVal = stack[len(stack)-1] + stack = stack[:len(stack)-1] + } else { + return false + } + if charPairing[poppedVal] != s[i] { + return false + } + } + } + return len(stack) == 0 +} diff --git a/go/stack/20_Valid_Parentheses/20_Valid_Parentheses_test.go b/go/stack/20_Valid_Parentheses/20_Valid_Parentheses_test.go new file mode 100644 index 000000000..ffa8bc570 --- /dev/null +++ b/go/stack/20_Valid_Parentheses/20_Valid_Parentheses_test.go @@ -0,0 +1,85 @@ +package validparentheses + +import ( + "testing" +) + +func Test_isValid(t *testing.T) { + type args struct { + s string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + s: "()", + }, + want: true, + }, + { + name: "case2", + args: args{ + s: "()[]{}", + }, + want: true, + }, + { + name: "case3", + args: args{ + s: "(]", + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isValid(tt.args.s); got != tt.want { + t.Errorf("isValid() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_isValid_2(t *testing.T) { + type args struct { + s string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + s: "()", + }, + want: true, + }, + { + name: "case2", + args: args{ + s: "()[]{}", + }, + want: true, + }, + { + name: "case3", + args: args{ + s: "(]", + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isValid_2(tt.args.s); got != tt.want { + t.Errorf("isValid_2() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/stack/22_Generate_Parentheses/22_Generate_Parentheses.go b/go/stack/22_Generate_Parentheses/22_Generate_Parentheses.go new file mode 100644 index 000000000..e8ad6bdcb --- /dev/null +++ b/go/stack/22_Generate_Parentheses/22_Generate_Parentheses.go @@ -0,0 +1,24 @@ +package generateparentheses + +func generateParenthesis(n int) []string { + var result []string + backTrack(0, 0, n, &result, "") + return result +} + +func backTrack(open int, closed int, n int, result *[]string, cur string) { + if (open == closed) && (closed == n) && (open == n) { + *result = append(*result, cur) + return + } + if closed > open { + return + } + + if open < n { + backTrack(open+1, closed, n, result, cur+"(") + } + if closed < n { + backTrack(open, closed+1, n, result, cur+")") + } +} diff --git a/go/stack/22_Generate_Parentheses/22_Generate_Parentheses_test.go b/go/stack/22_Generate_Parentheses/22_Generate_Parentheses_test.go new file mode 100644 index 000000000..ecab62c3c --- /dev/null +++ b/go/stack/22_Generate_Parentheses/22_Generate_Parentheses_test.go @@ -0,0 +1,39 @@ +package generateparentheses + +import ( + "reflect" + "testing" +) + +func Test_generateParenthesis(t *testing.T) { + type args struct { + n int + } + tests := []struct { + name string + args args + want []string + }{ + { + name: "case1", + args: args{ + n: 3, + }, + want: []string{"((()))", "(()())", "(())()", "()(())", "()()()"}, + }, + { + name: "case2", + args: args{ + n: 1, + }, + want: []string{"()"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := generateParenthesis(tt.args.n); !reflect.DeepEqual(got, tt.want) { + t.Errorf("generateParenthesis() = %v, want %v", got, tt.want) + } + }) + } +} From d90c3df92ce98140133ed1072e2f28e59b5ff558 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Sun, 17 Jul 2022 15:26:14 +0000 Subject: [PATCH 16/19] Added Solutions for Linked List and Binary Search --- .../128_longest_consecutive_sequence.go | 0 .../128_longest_consecutive_sequence_test.go | 0 .../217_ContainsDuplicate.go | 0 .../217_ContainsDuplicate_test.go | 0 .../238_Product_of_Array_Except_Self.go | 21 +++++++ .../238_Product_of_Array_Except_Self_test.go | 26 ++++++++ .../242_Valid_Anagram/242_Valid_Anagram.go | 0 .../242_Valid_Anagram_test.go | 0 .../271_encode_and_decode.go | 0 .../271_encode_and_decode_test.go | 0 .../347_Top_K_Frequent_Elements.go | 0 .../347_Top_K_Frequent_Elements_test.go | 0 .../36_validSudoku/36_validSudoku.go | 0 .../36_validSudoku/36_validSudoku_test.go | 0 .../49_Group_Anagrams/49_Group_Anagrams.go | 0 .../49_Group_Anagrams_test.go | 0 .../665_Non_decreasing_Array.go | 0 .../665_Non_decreasing_Array_test.go | 0 .../138_copy-list-with-random-pointer.go | 32 ++++++++++ .../141_Linked_list_cycle.go | 22 +++++++ .../143_Reorder_List/143_Reorder_List.go | 59 ++++++++++++++++++ .../19_remove-nth-node-from-end-of-list.go | 38 ++++++++++++ .../206_reverse-linked-list.go | 23 +++++++ .../21_Merge_Two_Sorted_Lists.go | 38 ++++++++++++ ...53_find-minimum-in-rotated-sorted-array.go | 27 +++++++++ ...nd-minimum-in-rotated-sorted-array_test.go | 57 ++++++++++++++++++ .../33_Search_in_Rotated_Sorted_Array.go | 37 ++++++++++++ .../33_Search_in_Rotated_Sorted_Array_test.go | 47 +++++++++++++++ .../704_Binary_Search/binarySearch.go | 20 +++++++ .../704_Binary_Search/binarySearch_test.go | 39 ++++++++++++ .../74_Search_a_2D_Matrix.go | 39 ++++++++++++ .../74_Search_a_2D_Matrix_test.go | 47 +++++++++++++++ .../875_Koko_Eating_Bananas.go | 36 +++++++++++ .../875_Koko_Eating_Bananas_test.go | 47 +++++++++++++++ .../981_time-based-key-value-store.go | 60 +++++++++++++++++++ .../739_Daily_Temperatures.go | 31 ++++++++++ .../739_Daily_Temperatures_test.go | 46 ++++++++++++++ go/stack/853_Car_Fleet/853_Car_Fleet.go | 56 +++++++++++++++++ go/stack/853_Car_Fleet/853_Car_Fleet_test.go | 60 +++++++++++++++++++ 39 files changed, 908 insertions(+) rename go/{01_arrays_and_hashing => ArraysAndHashing}/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/217_ContainsDuplicate/217_ContainsDuplicate.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/217_ContainsDuplicate/217_ContainsDuplicate_test.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go (82%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go (51%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/242_Valid_Anagram/242_Valid_Anagram.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/242_Valid_Anagram/242_Valid_Anagram_test.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/271_encode_and_decode/271_encode_and_decode.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/271_encode_and_decode/271_encode_and_decode_test.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/36_validSudoku/36_validSudoku.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/36_validSudoku/36_validSudoku_test.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/49_Group_Anagrams/49_Group_Anagrams.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/49_Group_Anagrams/49_Group_Anagrams_test.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/665_Non_decreasing_Array/665_Non_decreasing_Array.go (100%) rename go/{01_arrays_and_hashing => ArraysAndHashing}/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go (100%) create mode 100644 go/LinkedList/138_copy-list-with-random-pointer/138_copy-list-with-random-pointer.go create mode 100644 go/LinkedList/141_Linked_List_Cycle/141_Linked_list_cycle.go create mode 100644 go/LinkedList/143_Reorder_List/143_Reorder_List.go create mode 100644 go/LinkedList/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list.go create mode 100644 go/LinkedList/206_reverse-linked-list/206_reverse-linked-list.go create mode 100644 go/LinkedList/21_Merge_Two_Sorted_Lists/21_Merge_Two_Sorted_Lists.go create mode 100644 go/binarySearch/153_find-minimum-in-rotated-sorted-array/153_find-minimum-in-rotated-sorted-array.go create mode 100644 go/binarySearch/153_find-minimum-in-rotated-sorted-array/153_find-minimum-in-rotated-sorted-array_test.go create mode 100644 go/binarySearch/33_Search_in_Rotated_Sorted_Array/33_Search_in_Rotated_Sorted_Array.go create mode 100644 go/binarySearch/33_Search_in_Rotated_Sorted_Array/33_Search_in_Rotated_Sorted_Array_test.go create mode 100644 go/binarySearch/704_Binary_Search/binarySearch.go create mode 100644 go/binarySearch/704_Binary_Search/binarySearch_test.go create mode 100644 go/binarySearch/74_Search_a_2D_Matrix/74_Search_a_2D_Matrix.go create mode 100644 go/binarySearch/74_Search_a_2D_Matrix/74_Search_a_2D_Matrix_test.go create mode 100644 go/binarySearch/875_Koko_Eating_Bananas/875_Koko_Eating_Bananas.go create mode 100644 go/binarySearch/875_Koko_Eating_Bananas/875_Koko_Eating_Bananas_test.go create mode 100644 go/binarySearch/981_time-based-key-value-store/981_time-based-key-value-store.go create mode 100644 go/stack/739_Daily_Temperatures/739_Daily_Temperatures.go create mode 100644 go/stack/739_Daily_Temperatures/739_Daily_Temperatures_test.go create mode 100644 go/stack/853_Car_Fleet/853_Car_Fleet.go create mode 100644 go/stack/853_Car_Fleet/853_Car_Fleet_test.go diff --git a/go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go b/go/ArraysAndHashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go similarity index 100% rename from go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go rename to go/ArraysAndHashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence.go diff --git a/go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go b/go/ArraysAndHashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go similarity index 100% rename from go/01_arrays_and_hashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go rename to go/ArraysAndHashing/128_longest_consecutive_sequence/128_longest_consecutive_sequence_test.go diff --git a/go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate.go b/go/ArraysAndHashing/217_ContainsDuplicate/217_ContainsDuplicate.go similarity index 100% rename from go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate.go rename to go/ArraysAndHashing/217_ContainsDuplicate/217_ContainsDuplicate.go diff --git a/go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate_test.go b/go/ArraysAndHashing/217_ContainsDuplicate/217_ContainsDuplicate_test.go similarity index 100% rename from go/01_arrays_and_hashing/217_ContainsDuplicate/217_ContainsDuplicate_test.go rename to go/ArraysAndHashing/217_ContainsDuplicate/217_ContainsDuplicate_test.go diff --git a/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go b/go/ArraysAndHashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go similarity index 82% rename from go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go rename to go/ArraysAndHashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go index 53c4b9a25..037b9559c 100644 --- a/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go +++ b/go/ArraysAndHashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self.go @@ -58,3 +58,24 @@ func productExceptSelf(nums []int) []int { // } // result[i] = postFix * prefixArray[i] // } + +func productExceptSelfOptimised(nums []int) []int { + res := make([]int, len(nums)) + + prefix := 1 + res[0] = 1 + for i := 0; i < len(nums); i++ { + res[i] = prefix + + prefix *= nums[i] + } + + postfix := 1 + for i := len(nums) - 1; i >= 0; i-- { + res[i] *= postfix + + postfix *= nums[i] + } + + return res +} diff --git a/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go b/go/ArraysAndHashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go similarity index 51% rename from go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go rename to go/ArraysAndHashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go index 77d416e04..d5ab1503e 100644 --- a/go/01_arrays_and_hashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go +++ b/go/ArraysAndHashing/238_Product_of_Array_Except_Self/238_Product_of_Array_Except_Self_test.go @@ -30,3 +30,29 @@ func Test_productExceptSelf(t *testing.T) { }) } } + +func Test_productExceptSelfOptimised(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "case1", + args: args{ + []int{1, 2, 3, 4}, + }, + want: []int{24, 12, 8, 6}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := productExceptSelfOptimised(tt.args.nums); !reflect.DeepEqual(got, tt.want) { + t.Errorf("productExceptSelfOptimised() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram.go b/go/ArraysAndHashing/242_Valid_Anagram/242_Valid_Anagram.go similarity index 100% rename from go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram.go rename to go/ArraysAndHashing/242_Valid_Anagram/242_Valid_Anagram.go diff --git a/go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram_test.go b/go/ArraysAndHashing/242_Valid_Anagram/242_Valid_Anagram_test.go similarity index 100% rename from go/01_arrays_and_hashing/242_Valid_Anagram/242_Valid_Anagram_test.go rename to go/ArraysAndHashing/242_Valid_Anagram/242_Valid_Anagram_test.go diff --git a/go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode.go b/go/ArraysAndHashing/271_encode_and_decode/271_encode_and_decode.go similarity index 100% rename from go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode.go rename to go/ArraysAndHashing/271_encode_and_decode/271_encode_and_decode.go diff --git a/go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode_test.go b/go/ArraysAndHashing/271_encode_and_decode/271_encode_and_decode_test.go similarity index 100% rename from go/01_arrays_and_hashing/271_encode_and_decode/271_encode_and_decode_test.go rename to go/ArraysAndHashing/271_encode_and_decode/271_encode_and_decode_test.go diff --git a/go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go b/go/ArraysAndHashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go similarity index 100% rename from go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go rename to go/ArraysAndHashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements.go diff --git a/go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go b/go/ArraysAndHashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go similarity index 100% rename from go/01_arrays_and_hashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go rename to go/ArraysAndHashing/347_Top_K_Frequent_Elements/347_Top_K_Frequent_Elements_test.go diff --git a/go/01_arrays_and_hashing/36_validSudoku/36_validSudoku.go b/go/ArraysAndHashing/36_validSudoku/36_validSudoku.go similarity index 100% rename from go/01_arrays_and_hashing/36_validSudoku/36_validSudoku.go rename to go/ArraysAndHashing/36_validSudoku/36_validSudoku.go diff --git a/go/01_arrays_and_hashing/36_validSudoku/36_validSudoku_test.go b/go/ArraysAndHashing/36_validSudoku/36_validSudoku_test.go similarity index 100% rename from go/01_arrays_and_hashing/36_validSudoku/36_validSudoku_test.go rename to go/ArraysAndHashing/36_validSudoku/36_validSudoku_test.go diff --git a/go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams.go b/go/ArraysAndHashing/49_Group_Anagrams/49_Group_Anagrams.go similarity index 100% rename from go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams.go rename to go/ArraysAndHashing/49_Group_Anagrams/49_Group_Anagrams.go diff --git a/go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams_test.go b/go/ArraysAndHashing/49_Group_Anagrams/49_Group_Anagrams_test.go similarity index 100% rename from go/01_arrays_and_hashing/49_Group_Anagrams/49_Group_Anagrams_test.go rename to go/ArraysAndHashing/49_Group_Anagrams/49_Group_Anagrams_test.go diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array.go b/go/ArraysAndHashing/665_Non_decreasing_Array/665_Non_decreasing_Array.go similarity index 100% rename from go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array.go rename to go/ArraysAndHashing/665_Non_decreasing_Array/665_Non_decreasing_Array.go diff --git a/go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go b/go/ArraysAndHashing/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go similarity index 100% rename from go/01_arrays_and_hashing/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go rename to go/ArraysAndHashing/665_Non_decreasing_Array/665_Non_decreasing_Array_test.go diff --git a/go/LinkedList/138_copy-list-with-random-pointer/138_copy-list-with-random-pointer.go b/go/LinkedList/138_copy-list-with-random-pointer/138_copy-list-with-random-pointer.go new file mode 100644 index 000000000..fe7d50ff2 --- /dev/null +++ b/go/LinkedList/138_copy-list-with-random-pointer/138_copy-list-with-random-pointer.go @@ -0,0 +1,32 @@ +package copylistwithrandompointer + +type Node struct { + Val int + Next *Node + Random *Node +} + +func copyRandomList(head *Node) *Node { + oldToNewNodeMap := make(map[*Node]*Node) + dummy := head + for dummy != nil { + newNode := &Node{ + Val: dummy.Val, + Next: nil, + Random: nil, + } + oldToNewNodeMap[dummy] = newNode + dummy = dummy.Next + } + dummy = head + var newHead *Node + for dummy != nil { + newHead = oldToNewNodeMap[dummy] + newHead.Next = oldToNewNodeMap[dummy.Next] + newHead.Random = oldToNewNodeMap[dummy.Random] + oldToNewNodeMap[dummy] = newHead + dummy = dummy.Next + } + + return oldToNewNodeMap[head] +} diff --git a/go/LinkedList/141_Linked_List_Cycle/141_Linked_list_cycle.go b/go/LinkedList/141_Linked_List_Cycle/141_Linked_list_cycle.go new file mode 100644 index 000000000..023291d6e --- /dev/null +++ b/go/LinkedList/141_Linked_List_Cycle/141_Linked_list_cycle.go @@ -0,0 +1,22 @@ +package linkedlistcycle + +type ListNode struct { + Val int + Next *ListNode +} + +func hasCycle(head *ListNode) bool { + //Creating a hashmap to store the list of pointers which are already seen + hashMap := make(map[*ListNode]int) + + for head != nil { + _, ok := hashMap[head] + if ok { + return true + } else { + hashMap[head] = 1 + } + head = head.Next + } + return false +} diff --git a/go/LinkedList/143_Reorder_List/143_Reorder_List.go b/go/LinkedList/143_Reorder_List/143_Reorder_List.go new file mode 100644 index 000000000..885e0d719 --- /dev/null +++ b/go/LinkedList/143_Reorder_List/143_Reorder_List.go @@ -0,0 +1,59 @@ +package reorderlist + +import "fmt" + +type ListNode struct { + Val int + Next *ListNode +} + +func reorderList(head *ListNode) { + if head == nil { + return + } + fast := head.Next + slow := head + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + } + secondHalfList := slow.Next + slow.Next = nil + secondHalfList = reverseList(secondHalfList) + + firstHalfList := head + + for secondHalfList != nil { + tempFirstListNode, tempSecondListNode := firstHalfList.Next, secondHalfList.Next + firstHalfList.Next = secondHalfList // insert between + secondHalfList.Next = tempFirstListNode // join first half after inserting in between + firstHalfList = tempFirstListNode + secondHalfList = tempSecondListNode + } +} + +func reverseList(head *ListNode) *ListNode { + if head == nil { + return nil + } + var previousNode *ListNode + currentNode := head + for currentNode != nil { + tempNode := currentNode.Next + currentNode.Next = previousNode + previousNode = currentNode + currentNode = tempNode // for the last value currentNode will become nil and previous will store all the nodes + } + + head = previousNode + return head +} + +func printList(head *ListNode) { + for head != nil { + fmt.Print(head.Val) + fmt.Print(" ") + head = head.Next + } + fmt.Println(" ") +} diff --git a/go/LinkedList/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list.go b/go/LinkedList/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list.go new file mode 100644 index 000000000..ff17680cf --- /dev/null +++ b/go/LinkedList/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list/19_remove-nth-node-from-end-of-list.go @@ -0,0 +1,38 @@ +package removenthnodefromendoflist + +type ListNode struct { + Val int + Next *ListNode +} + +func removeNthFromEnd(head *ListNode, n int) *ListNode { + fast := head + slow := head + + // Logic is to remove nth element from end the slow pointer needs to move + // len(list) - n from the begining + // for eg: if we want to remove last 2nd element + // move the fast pointer by 2 and then move both slow pointer and fast pointer + // in equal pace till fast pointer is at the end of the list. + // If fast pointer is at the end it implies slow pointer is at the position where we + // want to delete the node. + + // move the fast pointer n steps to maintain distance between fast and slow pointer as n + for i := 1; i <= n; i++ { + fast = fast.Next + } + + //remove the first element from the list + if fast == nil { + return slow.Next + } + + for fast.Next != nil { + fast = fast.Next + slow = slow.Next + } + slow.Next = slow.Next.Next + + return head + +} diff --git a/go/LinkedList/206_reverse-linked-list/206_reverse-linked-list.go b/go/LinkedList/206_reverse-linked-list/206_reverse-linked-list.go new file mode 100644 index 000000000..dc8919ad9 --- /dev/null +++ b/go/LinkedList/206_reverse-linked-list/206_reverse-linked-list.go @@ -0,0 +1,23 @@ +package reverselinkedlist + +type ListNode struct { + Val int + Next *ListNode +} + +func reverseList(head *ListNode) *ListNode { + if head == nil { + return nil + } + var previousNode *ListNode + currentNode := head + for currentNode != nil { + tempNode := currentNode.Next + currentNode.Next = previousNode + previousNode = currentNode + currentNode = tempNode // for the last value currentNode will become nil and previous will store all the nodes + } + + head = previousNode + return head +} diff --git a/go/LinkedList/21_Merge_Two_Sorted_Lists/21_Merge_Two_Sorted_Lists.go b/go/LinkedList/21_Merge_Two_Sorted_Lists/21_Merge_Two_Sorted_Lists.go new file mode 100644 index 000000000..fa00bdd18 --- /dev/null +++ b/go/LinkedList/21_Merge_Two_Sorted_Lists/21_Merge_Two_Sorted_Lists.go @@ -0,0 +1,38 @@ +package mergetwosortedlists + +type ListNode struct { + Val int + Next *ListNode +} + +func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { + dummy := &ListNode{} + tail := dummy + if list1 == nil { + return list2 + } + if list2 == nil { + return list1 + } + + for list1 != nil && list2 != nil { + if list1.Val <= list2.Val { + tail.Next = list1 + list1 = list1.Next + } else { + tail.Next = list2 + list2 = list2.Next + } + tail = tail.Next + } + + if list1 != nil { + tail.Next = list1 + } + + if list2 != nil { + tail.Next = list2 + } + + return dummy.Next +} diff --git a/go/binarySearch/153_find-minimum-in-rotated-sorted-array/153_find-minimum-in-rotated-sorted-array.go b/go/binarySearch/153_find-minimum-in-rotated-sorted-array/153_find-minimum-in-rotated-sorted-array.go new file mode 100644 index 000000000..714027014 --- /dev/null +++ b/go/binarySearch/153_find-minimum-in-rotated-sorted-array/153_find-minimum-in-rotated-sorted-array.go @@ -0,0 +1,27 @@ +package findminimuminrotatedsortedarray + +func findMin(nums []int) int { + result := nums[0] + left, right := 0, len(nums)-1 + for left <= right { + if nums[left] <= nums[right] { + result = min(result, nums[left]) + break + } + mid := (left + right) / 2 + result = min(result, nums[mid]) + if nums[mid] >= nums[left] { + left = mid + 1 + } else { + right = mid - 1 + } + } + return result +} + +func min(i, j int) int { + if i < j { + return i + } + return j +} diff --git a/go/binarySearch/153_find-minimum-in-rotated-sorted-array/153_find-minimum-in-rotated-sorted-array_test.go b/go/binarySearch/153_find-minimum-in-rotated-sorted-array/153_find-minimum-in-rotated-sorted-array_test.go new file mode 100644 index 000000000..6c930798d --- /dev/null +++ b/go/binarySearch/153_find-minimum-in-rotated-sorted-array/153_find-minimum-in-rotated-sorted-array_test.go @@ -0,0 +1,57 @@ +package findminimuminrotatedsortedarray + +import "testing" + +func Test_findMin(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + nums: []int{4, 5, 6, 7, 0, 1, 2}, + }, + want: 0, + }, + { + name: "case2", + args: args{ + nums: []int{3, 4, 5, 1, 2}, + }, + want: 1, + }, + { + name: "case2", + args: args{ + nums: []int{11, 13, 15, 17}, + }, + want: 11, + }, + { + name: "case3", + args: args{ + nums: []int{2, 1}, + }, + want: 1, + }, + { + name: "case4", + args: args{ + nums: []int{3, 1, 2}, + }, + want: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := findMin(tt.args.nums); got != tt.want { + t.Errorf("findMin() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/binarySearch/33_Search_in_Rotated_Sorted_Array/33_Search_in_Rotated_Sorted_Array.go b/go/binarySearch/33_Search_in_Rotated_Sorted_Array/33_Search_in_Rotated_Sorted_Array.go new file mode 100644 index 000000000..e60de045d --- /dev/null +++ b/go/binarySearch/33_Search_in_Rotated_Sorted_Array/33_Search_in_Rotated_Sorted_Array.go @@ -0,0 +1,37 @@ +package searchinrotatedsortedarray + +func search(nums []int, target int) int { + left, right := 0, len(nums)-1 + + for left <= right { + mid := (left + right) / 2 + if nums[mid] == target { + return mid + } + + // Are we in the left sorted array or right sorted array. How to decide? + // If the middle element is > nums[left] then we are in left sorted array + // in right sorted array all the elements will be less than nums[0] + + if nums[mid] >= nums[left] { + if target > nums[mid] { + left = mid + 1 // search in right portion + } else if target < nums[mid] && target < nums[left] { + left = mid + 1 // search in right portion + } else { + // if target is less than nums[mid] and target is greater than nums[left] search in left side + right = mid - 1 + } + } else { // nums[mid] < nums[left]. pivot happened here all the elements after pivot would be less than nums[left] + if target < nums[mid] { + right = mid - 1 // search in left portion + } else if target > nums[mid] && target > nums[right] { + right = mid - 1 // search in left portion + } else { + left = mid + 1 // search in right portion + } + } + } + + return -1 +} diff --git a/go/binarySearch/33_Search_in_Rotated_Sorted_Array/33_Search_in_Rotated_Sorted_Array_test.go b/go/binarySearch/33_Search_in_Rotated_Sorted_Array/33_Search_in_Rotated_Sorted_Array_test.go new file mode 100644 index 000000000..6dcf65a46 --- /dev/null +++ b/go/binarySearch/33_Search_in_Rotated_Sorted_Array/33_Search_in_Rotated_Sorted_Array_test.go @@ -0,0 +1,47 @@ +package searchinrotatedsortedarray + +import "testing" + +func Test_search(t *testing.T) { + type args struct { + nums []int + target int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + nums: []int{4, 5, 6, 7, 0, 1, 2}, + target: 0, + }, + want: 4, + }, + { + name: "case2", + args: args{ + nums: []int{4, 5, 6, 7, 0, 1, 2}, + target: 3, + }, + want: -1, + }, + { + name: "case3", + args: args{ + nums: []int{1}, + target: 0, + }, + want: -1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := search(tt.args.nums, tt.args.target); got != tt.want { + t.Errorf("search() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/binarySearch/704_Binary_Search/binarySearch.go b/go/binarySearch/704_Binary_Search/binarySearch.go new file mode 100644 index 000000000..7bde67b13 --- /dev/null +++ b/go/binarySearch/704_Binary_Search/binarySearch.go @@ -0,0 +1,20 @@ +package binarysearch + +func search(nums []int, target int) int { + return binarySearch(&nums, target, 0, len(nums)-1) +} + +func binarySearch(nums *[]int, target int, start int, end int) int { + if start > end { + return -1 + } + mid := (start + end) / 2 + if (*nums)[mid] < target { + return binarySearch(nums, target, mid+1, end) + } else if (*nums)[mid] > target { + return binarySearch(nums, target, start, mid-1) + } else { + return mid + } + +} diff --git a/go/binarySearch/704_Binary_Search/binarySearch_test.go b/go/binarySearch/704_Binary_Search/binarySearch_test.go new file mode 100644 index 000000000..6cea6b3c7 --- /dev/null +++ b/go/binarySearch/704_Binary_Search/binarySearch_test.go @@ -0,0 +1,39 @@ +package binarysearch + +import "testing" + +func Test_search(t *testing.T) { + type args struct { + nums []int + target int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + nums: []int{-1, 0, 3, 5, 9, 12}, + target: 9, + }, + want: 4, + }, + { + name: "case1", + args: args{ + nums: []int{-1, 0, 3, 5, 9, 12}, + target: 2, + }, + want: -1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := search(tt.args.nums, tt.args.target); got != tt.want { + t.Errorf("search() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/binarySearch/74_Search_a_2D_Matrix/74_Search_a_2D_Matrix.go b/go/binarySearch/74_Search_a_2D_Matrix/74_Search_a_2D_Matrix.go new file mode 100644 index 000000000..e5542b386 --- /dev/null +++ b/go/binarySearch/74_Search_a_2D_Matrix/74_Search_a_2D_Matrix.go @@ -0,0 +1,39 @@ +package searcha2dmatrix + +func searchMatrix(matrix [][]int, target int) bool { + maxRowIndex, maxColIndex := len(matrix)-1, len(matrix[0])-1 + // first find the row in which the target might be present + top, bottom := 0, maxRowIndex + var probableRow int + for top <= bottom { + probableRow = (top + bottom) / 2 + if target > matrix[probableRow][maxColIndex] { + top = probableRow + 1 + } else if target < matrix[probableRow][0] { + bottom = probableRow - 1 + } else { + break + } + } + if top > bottom { + return false + } + + // find in the column the element using binary search + left, right := 0, maxColIndex + for left <= right { + targetPosition := (left + right) / 2 + if target > matrix[probableRow][targetPosition] { + left = targetPosition + 1 + } else if target < matrix[probableRow][targetPosition] { + right = targetPosition - 1 + } else { + return true + } + } + if left > right { + return false + } + + return false +} diff --git a/go/binarySearch/74_Search_a_2D_Matrix/74_Search_a_2D_Matrix_test.go b/go/binarySearch/74_Search_a_2D_Matrix/74_Search_a_2D_Matrix_test.go new file mode 100644 index 000000000..b64e81f2a --- /dev/null +++ b/go/binarySearch/74_Search_a_2D_Matrix/74_Search_a_2D_Matrix_test.go @@ -0,0 +1,47 @@ +package searcha2dmatrix + +import "testing" + +func Test_searchMatrix(t *testing.T) { + type args struct { + matrix [][]int + target int + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "case1", + args: args{ + matrix: [][]int{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, + target: 3, + }, + want: true, + }, + { + name: "case2", + args: args{ + matrix: [][]int{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, + target: 13, + }, + want: false, + }, + { + name: "case3", + args: args{ + matrix: [][]int{{1, 3, 5}}, + target: 1, + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := searchMatrix(tt.args.matrix, tt.args.target); got != tt.want { + t.Errorf("searchMatrix() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/binarySearch/875_Koko_Eating_Bananas/875_Koko_Eating_Bananas.go b/go/binarySearch/875_Koko_Eating_Bananas/875_Koko_Eating_Bananas.go new file mode 100644 index 000000000..e06346ec8 --- /dev/null +++ b/go/binarySearch/875_Koko_Eating_Bananas/875_Koko_Eating_Bananas.go @@ -0,0 +1,36 @@ +package kokoeatingbananas + +import ( + "fmt" + "math" +) + +func minEatingSpeed(piles []int, h int) int { + left := 1 + right := getMax(piles) + fmt.Println(right) + for left < right { + middle := (left + right) / 2 + hours := 0.0 + for _, value := range piles { + hours += math.Ceil(float64(value) / float64(middle)) + } + + if int(hours) <= h { + right = middle + } else { + left = middle + 1 + } + } + return right +} + +func getMax(arr []int) int { + maxValue := -2147483648 + for i := range arr { + if arr[i] > maxValue { + maxValue = arr[i] + } + } + return maxValue +} diff --git a/go/binarySearch/875_Koko_Eating_Bananas/875_Koko_Eating_Bananas_test.go b/go/binarySearch/875_Koko_Eating_Bananas/875_Koko_Eating_Bananas_test.go new file mode 100644 index 000000000..20eb94873 --- /dev/null +++ b/go/binarySearch/875_Koko_Eating_Bananas/875_Koko_Eating_Bananas_test.go @@ -0,0 +1,47 @@ +package kokoeatingbananas + +import "testing" + +func Test_minEatingSpeed(t *testing.T) { + type args struct { + piles []int + h int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + piles: []int{3, 6, 7, 11}, + h: 8, + }, + want: 11, + }, + { + name: "case2", + args: args{ + piles: []int{30, 11, 23, 4, 20}, + h: 5, + }, + want: 30, + }, + { + name: "case3", + args: args{ + piles: []int{30, 11, 23, 4, 20}, + h: 6, + }, + want: 23, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := minEatingSpeed(tt.args.piles, tt.args.h); got != tt.want { + t.Errorf("minEatingSpeed() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/binarySearch/981_time-based-key-value-store/981_time-based-key-value-store.go b/go/binarySearch/981_time-based-key-value-store/981_time-based-key-value-store.go new file mode 100644 index 000000000..7f71b384a --- /dev/null +++ b/go/binarySearch/981_time-based-key-value-store/981_time-based-key-value-store.go @@ -0,0 +1,60 @@ +package timebasedkeyvaluestore + +type timeStampValue struct { + value string + timestamp int +} + +type TimeMap struct { + timeMapKey map[string][]timeStampValue +} + +func Constructor() TimeMap { + timeMap := make(map[string][]timeStampValue) + return TimeMap{ + timeMapKey: timeMap, + } +} + +func (this *TimeMap) Set(key string, value string, timestamp int) { + timeStampVal := timeStampValue{ + value: value, + timestamp: timestamp, + } + val, ok := this.timeMapKey[key] + if ok { + this.timeMapKey[key] = append(val, timeStampVal) + } else { + this.timeMapKey[key] = append(this.timeMapKey[key], timeStampVal) + } +} + +func (this *TimeMap) Get(key string, timestamp int) string { + var result string + values, ok := this.timeMapKey[key] + if !ok { + return "" + } + left, right := 0, len(values)-1 + for left <= right { + mid := (left + right) / 2 + if timestamp == values[mid].timestamp { + return values[mid].value + } + if values[mid].timestamp <= timestamp { + // upto this point the closest to the current target timestamp is the current + result = values[mid].value + left = mid + 1 + } else { + right = mid - 1 + } + } + return result +} + +/** + * Your TimeMap object will be instantiated and called as such: + * obj := Constructor(); + * obj.Set(key,value,timestamp); + * param_2 := obj.Get(key,timestamp); + */ diff --git a/go/stack/739_Daily_Temperatures/739_Daily_Temperatures.go b/go/stack/739_Daily_Temperatures/739_Daily_Temperatures.go new file mode 100644 index 000000000..f91eecc51 --- /dev/null +++ b/go/stack/739_Daily_Temperatures/739_Daily_Temperatures.go @@ -0,0 +1,31 @@ +package dailytemperatures + +type keyPair struct { + index int + value int +} + +func dailyTemperatures(temperatures []int) []int { + result := make([]int, len(temperatures)) + var stack []keyPair + for key, value := range temperatures { + // check if the current value in temperatures is greater than the top of the stack value + // if yes then for the index of the top the stack assign value (currIndex - indexAtTop). This gives the number of days until we found a greater value + // pop the value from the stack since we assigned the number of days + // add the current value and index to the stack + for len(stack) > 0 && value > stack[len(stack)-1].value { + result[stack[len(stack)-1].index] = key - stack[len(stack)-1].index + stack = stack[:len(stack)-1] + } + stack = append(stack, keyPair{ + index: key, + value: value, + }) + } + // for remaining elements we can simply assign them 0 + for len(stack) > 0 { + result[stack[len(stack)-1].index] = 0 + stack = stack[:len(stack)-1] + } + return result +} diff --git a/go/stack/739_Daily_Temperatures/739_Daily_Temperatures_test.go b/go/stack/739_Daily_Temperatures/739_Daily_Temperatures_test.go new file mode 100644 index 000000000..422c63d12 --- /dev/null +++ b/go/stack/739_Daily_Temperatures/739_Daily_Temperatures_test.go @@ -0,0 +1,46 @@ +package dailytemperatures + +import ( + "reflect" + "testing" +) + +func Test_dailyTemperatures(t *testing.T) { + type args struct { + temperatures []int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "case1", + args: args{ + temperatures: []int{73, 74, 75, 71, 69, 72, 76, 73}, + }, + want: []int{1, 1, 4, 2, 1, 1, 0, 0}, + }, + { + name: "case2", + args: args{ + temperatures: []int{30, 40, 50, 60}, + }, + want: []int{1, 1, 1, 0}, + }, + { + name: "case3", + args: args{ + temperatures: []int{30, 60, 90}, + }, + want: []int{1, 1, 0}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := dailyTemperatures(tt.args.temperatures); !reflect.DeepEqual(got, tt.want) { + t.Errorf("dailyTemperatures() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go/stack/853_Car_Fleet/853_Car_Fleet.go b/go/stack/853_Car_Fleet/853_Car_Fleet.go new file mode 100644 index 000000000..58e7599e9 --- /dev/null +++ b/go/stack/853_Car_Fleet/853_Car_Fleet.go @@ -0,0 +1,56 @@ +package carfleet + +import ( + "sort" +) + +// custom Sort +type positionAndSpeed struct { + position int + speed int +} + +type positionAndSpeedSlice []positionAndSpeed + +func (p positionAndSpeedSlice) Less(i, j int) bool { + return p[i].position < p[j].position +} + +func (p positionAndSpeedSlice) Len() int { + return len(p) +} + +func (p positionAndSpeedSlice) Swap(i, j int) { + p[i].position, p[j].position = p[j].position, p[i].position + p[i].speed, p[j].speed = p[j].speed, p[i].speed +} + +func carFleet(target int, position []int, speed []int) int { + arr := make(positionAndSpeedSlice, len(position)) + var stack []float64 + for i := 0; i < len(position); i++ { + arr[i] = positionAndSpeed{ + position: position[i], + speed: speed[i], + } + } + sort.Sort(arr) + // simpler way to sort without custom Less, Swap + //********** + // sort.SliceStable(arr, func(i, j int) bool { + // return arr[i].position < arr[j].position + // }) + //********** + i := len(arr) - 1 + for i >= 0 { + // inserting the time taken to reach the final target + stack = append(stack, float64(target-arr[i].position)/float64(arr[i].speed)) + + // if there are more than 2 elements on the stack and if the 2 elements are colliding with eah other. + if len(stack) >= 2 && stack[len(stack)-1] <= stack[len(stack)-2] { + stack = stack[:len(stack)-1] + } + i-- + } + return len(stack) +} diff --git a/go/stack/853_Car_Fleet/853_Car_Fleet_test.go b/go/stack/853_Car_Fleet/853_Car_Fleet_test.go new file mode 100644 index 000000000..236e651ef --- /dev/null +++ b/go/stack/853_Car_Fleet/853_Car_Fleet_test.go @@ -0,0 +1,60 @@ +package carfleet + +import "testing" + +func Test_carFleet(t *testing.T) { + type args struct { + target int + position []int + speed []int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "case1", + args: args{ + target: 12, + position: []int{10, 8, 0, 5, 3}, + speed: []int{2, 4, 1, 1, 3}, + }, + want: 3, + }, + { + name: "case2", + args: args{ + target: 10, + position: []int{3}, + speed: []int{3}, + }, + want: 1, + }, + { + name: "case3", + args: args{ + target: 100, + position: []int{0, 2, 4}, + speed: []int{4, 2, 1}, + }, + want: 1, + }, + { + name: "case4", + args: args{ + target: 10, + position: []int{6, 8}, + speed: []int{3, 2}, + }, + want: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := carFleet(tt.args.target, tt.args.position, tt.args.speed); got != tt.want { + t.Errorf("carFleet() = %v, want %v", got, tt.want) + } + }) + } +} From e917e7e5f86c6db7ced29c269a6383428c680c4d Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Fri, 22 Jul 2022 05:48:28 +0000 Subject: [PATCH 17/19] Binary Tree and BST solutions --- .vscode/settings.json | 7 ++ go/BinaryTree/100_Same_Tree/100_Same_Tree.go | 21 +++++ .../102_level_order_traversal.go | 86 +++++++++++++++++++ .../104_Maximum_Depth_of_Binary_Tree.go | 48 +++++++++++ ...05_construct_tree_from_inroder_preorder.go | 31 +++++++ .../110_balanced-binary-tree.go | 39 +++++++++ .../199_Binary_Tree_Right_Side_View.go | 35 ++++++++ .../226_Invert_Binary_Tree.go | 20 +++++ .../230_kth-smallest-element-in-a-bst.go | 32 +++++++ .../235_lowest_common_ancesstor.go | 31 +++++++ .../543_diameter-of-binary-tree.go | 33 +++++++ .../572_subtree_of_another_tree.go | 37 ++++++++ .../98_Validate_Binary_Search_Tree.go | 25 ++++++ go/LinkedList/146_LRU_Cache/146_LRU_Cache.go | 85 ++++++++++++++++++ .../287_Find_the_Duplicate_Number.go | 19 ++++ .../2_add-two-numbers/2_add-two-numbers.go | 43 ++++++++++ 16 files changed, 592 insertions(+) create mode 100644 .vscode/settings.json create mode 100644 go/BinaryTree/100_Same_Tree/100_Same_Tree.go create mode 100644 go/BinaryTree/102_level_order_traversal/102_level_order_traversal.go create mode 100644 go/BinaryTree/104_Maximum_Depth_of_Binary_Tree/104_Maximum_Depth_of_Binary_Tree.go create mode 100644 go/BinaryTree/105_construct_tree_from_inroder_preorder/105_construct_tree_from_inroder_preorder.go create mode 100644 go/BinaryTree/110_balanced-binary-tree/110_balanced-binary-tree.go create mode 100644 go/BinaryTree/199_Binary_Tree_Right_Side_View/199_Binary_Tree_Right_Side_View.go create mode 100644 go/BinaryTree/226_Invert_Binary_Tree/226_Invert_Binary_Tree.go create mode 100644 go/BinaryTree/230_kth-smallest-element-in-a-bst/230_kth-smallest-element-in-a-bst.go create mode 100644 go/BinaryTree/235_lowest_common_ancesstor/235_lowest_common_ancesstor.go create mode 100644 go/BinaryTree/543_diameter-of-binary-tree/543_diameter-of-binary-tree.go create mode 100644 go/BinaryTree/572_subtree_of_another_tree/572_subtree_of_another_tree.go create mode 100644 go/BinaryTree/98_Validate_Binary_Search_Tree/98_Validate_Binary_Search_Tree.go create mode 100644 go/LinkedList/146_LRU_Cache/146_LRU_Cache.go create mode 100644 go/LinkedList/287_Find_the_Duplicate_Number/287_Find_the_Duplicate_Number.go create mode 100644 go/LinkedList/2_add-two-numbers/2_add-two-numbers.go diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..100778634 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,7 @@ +{ + "workbench.colorCustomizations": { + "sideBar.background": "#f9fdf9", + "editor.lineHighlightBackground": "#1073cf2d", + "editor.lineHighlightBorder": "#9fced11f" + } +} \ No newline at end of file diff --git a/go/BinaryTree/100_Same_Tree/100_Same_Tree.go b/go/BinaryTree/100_Same_Tree/100_Same_Tree.go new file mode 100644 index 000000000..4e2d04015 --- /dev/null +++ b/go/BinaryTree/100_Same_Tree/100_Same_Tree.go @@ -0,0 +1,21 @@ +package sametree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == nil && q == nil { + return true + } + if (q == nil) || (p == nil) { + return false + } else if p.Val != q.Val { + return false + } + + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) + +} diff --git a/go/BinaryTree/102_level_order_traversal/102_level_order_traversal.go b/go/BinaryTree/102_level_order_traversal/102_level_order_traversal.go new file mode 100644 index 000000000..3542470ac --- /dev/null +++ b/go/BinaryTree/102_level_order_traversal/102_level_order_traversal.go @@ -0,0 +1,86 @@ +package levelordertraversal + +import ( + "container/list" + "fmt" +) + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func levelOrder(root *TreeNode) [][]int { + height := heightOfTree(root) + fmt.Println("Height", height) + var levelOrderList [][]int + for i := 0; i <= height; i++ { + levelOrderTraversalUtil(root, i, &levelOrderList, i) + } + return levelOrderList +} + +func levelOrderTraversalUtil(root *TreeNode, level int, arr *[][]int, index int) { + if root == nil { + return + } + if len(*arr) <= index { + (*arr) = append((*arr), []int{}) + } + if level == 0 { + levelArr := (*arr)[index] + levelArr = append(levelArr, root.Val) + (*arr) = append((*arr), levelArr) + } + levelOrderTraversalUtil(root.Left, level-1, arr, index) + levelOrderTraversalUtil(root.Right, level-1, arr, index) +} + +func heightOfTree(root *TreeNode) int { + if root == nil { + return -1 + } + return 1 + max(heightOfTree(root.Left), heightOfTree(root.Right)) +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} + +func levelOrderBFS(root *TreeNode) [][]int { + var result [][]int + queue := list.New() + queue.PushBack(root) + for queue.Len() > 0 { + numberOfNodes := queue.Len() + level := list.New() + for numberOfNodes > 0 { + node := queue.Remove(queue.Front()).(*TreeNode) + if node != nil { + level.PushBack(node.Val) + queue.PushBack(node.Left) + queue.PushBack(node.Right) + } + numberOfNodes-- + } + if level.Len() > 0 { + copyList(&result, level) + } + } + return result +} + +func copyList(result *[][]int, level *list.List) { + var levelArr []int + levelLen := level.Len() + for levelLen > 0 { + val := level.Remove(level.Front()).(int) + levelArr = append(levelArr, val) + levelLen-- + } + (*result) = append(*result, levelArr) +} diff --git a/go/BinaryTree/104_Maximum_Depth_of_Binary_Tree/104_Maximum_Depth_of_Binary_Tree.go b/go/BinaryTree/104_Maximum_Depth_of_Binary_Tree/104_Maximum_Depth_of_Binary_Tree.go new file mode 100644 index 000000000..fde0f06cb --- /dev/null +++ b/go/BinaryTree/104_Maximum_Depth_of_Binary_Tree/104_Maximum_Depth_of_Binary_Tree.go @@ -0,0 +1,48 @@ +package maximumdepthofbinarytree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func maxDepth(root *TreeNode) int { + if root == nil { + return 0 + } + leftDepth := maxDepth(root.Left) + rightDepth := maxDepth(root.Right) + return 1 + max(leftDepth, rightDepth) +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} + +func maxDepthBFS(root *TreeNode) int { + if root == nil { + return 0 + } + queue := make([]*TreeNode, 0) + level := 0 + queue = append(queue, root) + for len(queue) > 0 { + queueSize := len(queue) + for i := 0; i < queueSize; i++ { + node := queue[0] + queue = queue[1:] + if node.Left != nil { + queue = append(queue, node.Left) + } + if node.Right != nil { + queue = append(queue, node.Right) + } + } + level += 1 + } + return level + +} diff --git a/go/BinaryTree/105_construct_tree_from_inroder_preorder/105_construct_tree_from_inroder_preorder.go b/go/BinaryTree/105_construct_tree_from_inroder_preorder/105_construct_tree_from_inroder_preorder.go new file mode 100644 index 000000000..6025058a1 --- /dev/null +++ b/go/BinaryTree/105_construct_tree_from_inroder_preorder/105_construct_tree_from_inroder_preorder.go @@ -0,0 +1,31 @@ +package constructtreefrominroderpreorder + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func buildTree(preorder []int, inorder []int) *TreeNode { + if len(preorder) == 0 || len(inorder) == 0 { + return nil + } + rootNode := &TreeNode{ + Val: preorder[0], + } + // midPoint := slices.Index(inorder, preorder[0]) In go 1.18 you can do this simply + midPoint := Index(inorder, preorder[0]) + rootNode.Left = buildTree(preorder[1:midPoint+1], inorder[:midPoint]) + rootNode.Right = buildTree(preorder[midPoint+1:], inorder[midPoint+1:]) + + return rootNode +} + +func Index(arr []int, element int) int { + for key, val := range arr { + if val == element { + return key + } + } + return -1 +} diff --git a/go/BinaryTree/110_balanced-binary-tree/110_balanced-binary-tree.go b/go/BinaryTree/110_balanced-binary-tree/110_balanced-binary-tree.go new file mode 100644 index 000000000..026fce9a5 --- /dev/null +++ b/go/BinaryTree/110_balanced-binary-tree/110_balanced-binary-tree.go @@ -0,0 +1,39 @@ +package balancedbinarytree + +import "math" + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func isBalanced(root *TreeNode) bool { + if root == nil { + return true + } + + leftHeight := heightOfBinaryTree(root.Left) + rightHeight := heightOfBinaryTree(root.Right) + if math.Abs(float64(leftHeight)-float64(rightHeight)) > 1 { + return false + } + return isBalanced(root.Left) && isBalanced(root.Right) + +} + +func heightOfBinaryTree(root *TreeNode) int { + if root == nil { + return -1 + } + leftHeight := heightOfBinaryTree(root.Left) + rightHeight := heightOfBinaryTree(root.Right) + return 1 + max(leftHeight, rightHeight) +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/BinaryTree/199_Binary_Tree_Right_Side_View/199_Binary_Tree_Right_Side_View.go b/go/BinaryTree/199_Binary_Tree_Right_Side_View/199_Binary_Tree_Right_Side_View.go new file mode 100644 index 000000000..d25452582 --- /dev/null +++ b/go/BinaryTree/199_Binary_Tree_Right_Side_View/199_Binary_Tree_Right_Side_View.go @@ -0,0 +1,35 @@ +package binarytreerightsideview + +import "container/list" + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func rightSideView(root *TreeNode) []int { + var result []int + if root == nil { + return result + } + queue := list.New() + queue.PushBack(root) + for queue.Len() > 0 { + var rightSideElem *TreeNode + numberOfNodes := queue.Len() + for numberOfNodes > 0 { + poppedVal := queue.Remove(queue.Front()).(*TreeNode) + if poppedVal != nil { + rightSideElem = poppedVal + queue.PushBack(poppedVal.Left) + queue.PushBack(poppedVal.Right) + } + numberOfNodes-- + } + if rightSideElem != nil { + result = append(result, rightSideElem.Val) + } + } + return result +} diff --git a/go/BinaryTree/226_Invert_Binary_Tree/226_Invert_Binary_Tree.go b/go/BinaryTree/226_Invert_Binary_Tree/226_Invert_Binary_Tree.go new file mode 100644 index 000000000..9eb167f00 --- /dev/null +++ b/go/BinaryTree/226_Invert_Binary_Tree/226_Invert_Binary_Tree.go @@ -0,0 +1,20 @@ +package binarytree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func invertTree(root *TreeNode) *TreeNode { + if root == nil { + return root + } + + invertTree(root.Left) + invertTree(root.Right) + + root.Left, root.Right = root.Right, root.Left + return root + +} diff --git a/go/BinaryTree/230_kth-smallest-element-in-a-bst/230_kth-smallest-element-in-a-bst.go b/go/BinaryTree/230_kth-smallest-element-in-a-bst/230_kth-smallest-element-in-a-bst.go new file mode 100644 index 000000000..457c349c9 --- /dev/null +++ b/go/BinaryTree/230_kth-smallest-element-in-a-bst/230_kth-smallest-element-in-a-bst.go @@ -0,0 +1,32 @@ +package kthsmallestelementinabst + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func kthSmallest(root *TreeNode, k int) int { + var count int + node := kthSmallestUtil(root, k, &count) + if node == nil { + return -1 + } + return node.Val +} + +func kthSmallestUtil(root *TreeNode, k int, count *int) *TreeNode { + if root == nil { + return nil + } + left := kthSmallestUtil(root.Left, k, count) + if left != nil { + return left + } + *count++ + if *count == k { + return root + } + + return kthSmallestUtil(root.Right, k, count) +} diff --git a/go/BinaryTree/235_lowest_common_ancesstor/235_lowest_common_ancesstor.go b/go/BinaryTree/235_lowest_common_ancesstor/235_lowest_common_ancesstor.go new file mode 100644 index 000000000..22d7d687e --- /dev/null +++ b/go/BinaryTree/235_lowest_common_ancesstor/235_lowest_common_ancesstor.go @@ -0,0 +1,31 @@ +package lowestcommonancesstor + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + current := root + for current != nil { + if p.Val > current.Val && q.Val > current.Val { + current = current.Right + } else if p.Val < current.Val && q.Val < current.Val { + current = current.Left + } else { + break + } + } + return current +} + +func lowestCommonAncestorRecursion(root, p, q *TreeNode) *TreeNode { + + if p.Val > root.Val && q.Val > root.Val { + return lowestCommonAncestor(root.Right, p, q) + } else if p.Val < root.Val && q.Val < root.Val { + return lowestCommonAncestor(root.Left, p, q) + } + return root +} diff --git a/go/BinaryTree/543_diameter-of-binary-tree/543_diameter-of-binary-tree.go b/go/BinaryTree/543_diameter-of-binary-tree/543_diameter-of-binary-tree.go new file mode 100644 index 000000000..b21a894ad --- /dev/null +++ b/go/BinaryTree/543_diameter-of-binary-tree/543_diameter-of-binary-tree.go @@ -0,0 +1,33 @@ +package diameterofbinarytree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +var maxDiameter int = 0 + +func diameterOfBinaryTree(root *TreeNode) int { + maxDiameter = 0 + dfs(root) + return maxDiameter +} + +func dfs(root *TreeNode) int { + if root == nil { + return -1 + } + leftHeight := dfs(root.Left) + rightHeight := dfs(root.Right) + diameter := leftHeight + rightHeight + 2 + maxDiameter = max(maxDiameter, diameter) + return 1 + max(leftHeight, rightHeight) +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/BinaryTree/572_subtree_of_another_tree/572_subtree_of_another_tree.go b/go/BinaryTree/572_subtree_of_another_tree/572_subtree_of_another_tree.go new file mode 100644 index 000000000..8ea039ead --- /dev/null +++ b/go/BinaryTree/572_subtree_of_another_tree/572_subtree_of_another_tree.go @@ -0,0 +1,37 @@ +package subtreeofanothertree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func isSubtree(root *TreeNode, subRoot *TreeNode) bool { + if subRoot == nil { + return true + } + if root == nil { + return false + } + + if isSameTree(root, subRoot) { + return true + } + + return isSubtree(root.Left, subRoot) || isSubtree(root.Right, subRoot) + +} + +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == nil && q == nil { + return true + } + if (q == nil) || (p == nil) { + return false + } else if p.Val != q.Val { + return false + } + + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) + +} diff --git a/go/BinaryTree/98_Validate_Binary_Search_Tree/98_Validate_Binary_Search_Tree.go b/go/BinaryTree/98_Validate_Binary_Search_Tree/98_Validate_Binary_Search_Tree.go new file mode 100644 index 000000000..76de39c0f --- /dev/null +++ b/go/BinaryTree/98_Validate_Binary_Search_Tree/98_Validate_Binary_Search_Tree.go @@ -0,0 +1,25 @@ +package validatebinarysearchtree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func isValidBST(root *TreeNode) bool { + max := 1 << 32 + left := -1 * max + right := max + return isValidBSTUtil(root, left, right) +} + +func isValidBSTUtil(root *TreeNode, left int, right int) bool { + if root == nil { + return true + } + + if !(root.Val > left && root.Val < right) { + return false + } + return isValidBSTUtil(root.Left, left, root.Val) && isValidBSTUtil(root.Right, root.Val, right) +} diff --git a/go/LinkedList/146_LRU_Cache/146_LRU_Cache.go b/go/LinkedList/146_LRU_Cache/146_LRU_Cache.go new file mode 100644 index 000000000..8681821bb --- /dev/null +++ b/go/LinkedList/146_LRU_Cache/146_LRU_Cache.go @@ -0,0 +1,85 @@ +package lrucache + +import "fmt" + +type Node struct { + Key int + Val int + Prev *Node + Next *Node +} + +type LRUCache struct { + cache map[int]*Node + capacity int + Left *Node + Right *Node +} + +func Constructor(capacity int) LRUCache { + cache := make(map[int]*Node) + leftNode := &Node{} + rightNode := &Node{} + leftNode.Next, rightNode.Prev = rightNode, leftNode + lruCache := LRUCache{ + cache: cache, + capacity: capacity, + Left: leftNode, + Right: rightNode, + } + return lruCache +} + +func (this *LRUCache) remove(node *Node) { + if node == nil { + return + } + prev, next := node.Prev, node.Next + prev.Next, next.Prev = next, prev +} + +func (this *LRUCache) insert(node *Node) { + prev, next := this.Right.Prev, this.Right + prev.Next = node + next.Prev = node + node.Next, node.Prev = next, prev +} + +func (this *LRUCache) Get(key int) int { + val, ok := this.cache[key] + if ok { + this.remove(val) + this.insert(val) + // PrintList(this.Left) + return val.Val + } + return -1 +} + +func (this *LRUCache) Put(key int, value int) { + _, ok := this.cache[key] + if ok { + this.remove(this.cache[key]) + } + this.cache[key] = &Node{ + Key: key, + Val: value, + } + this.insert(this.cache[key]) + if len(this.cache) > this.capacity { + lru := this.Left.Next + delete(this.cache, lru.Key) + this.remove(lru) + + } + // PrintList(this.Left) +} + +func PrintList(node *Node) { + fmt.Print("List L -> R ") + for node != nil { + fmt.Print(node.Key, " ") + node = node.Next + } + fmt.Println(" ") +} diff --git a/go/LinkedList/287_Find_the_Duplicate_Number/287_Find_the_Duplicate_Number.go b/go/LinkedList/287_Find_the_Duplicate_Number/287_Find_the_Duplicate_Number.go new file mode 100644 index 000000000..18dc1ac8a --- /dev/null +++ b/go/LinkedList/287_Find_the_Duplicate_Number/287_Find_the_Duplicate_Number.go @@ -0,0 +1,19 @@ +package findtheduplicatenumber + +func findDuplicate(nums []int) int { + tortoise, hare := nums[0], nums[0] + + for { + tortoise = nums[tortoise] + hare = nums[nums[hare]] + if tortoise == hare { + break + } + } + tortoise = nums[0] + for tortoise != hare { + tortoise = nums[tortoise] + hare = nums[hare] + } + return hare +} diff --git a/go/LinkedList/2_add-two-numbers/2_add-two-numbers.go b/go/LinkedList/2_add-two-numbers/2_add-two-numbers.go new file mode 100644 index 000000000..2cb527cc1 --- /dev/null +++ b/go/LinkedList/2_add-two-numbers/2_add-two-numbers.go @@ -0,0 +1,43 @@ +package addtwonumbers + +type ListNode struct { + Val int + Next *ListNode +} + +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { + dummyHead := &ListNode{} + current := dummyHead + carry := 0 + l1Value := 0 + l2Value := 0 + for l1 != nil || l2 != nil || carry != 0 { + if l1 != nil { + l1Value = l1.Val + } else { + l1Value = 0 + } + if l2 != nil { + l2Value = l2.Val + } else { + l2Value = 0 + } + sum := l1Value + l2Value + carry + carry = sum / 10 + newNode := &ListNode{ + Val: (sum % 10), + Next: nil, + } + current.Next = newNode + current = newNode + if l1 != nil { + l1 = l1.Next + } + if l2 != nil { + l2 = l2.Next + } + + } + return dummyHead.Next + +} From 6bdd443804313a2250f776aa10374fba26e2257a Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Fri, 22 Jul 2022 05:48:45 +0000 Subject: [PATCH 18/19] remove vs code file --- .vscode/settings.json | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 100778634..000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "workbench.colorCustomizations": { - "sideBar.background": "#f9fdf9", - "editor.lineHighlightBackground": "#1073cf2d", - "editor.lineHighlightBorder": "#9fced11f" - } -} \ No newline at end of file From f660760e0cb5c3b74495201b23e4407a0cac7657 Mon Sep 17 00:00:00 2001 From: khvr1993 Date: Fri, 22 Jul 2022 14:26:26 +0000 Subject: [PATCH 19/19] binary tree max path sum and k sorted lists --- .../124_binary-tree-maximum-path-sum.go | 36 +++++++++ .../1448_count-good-nodes-in-binary-tree.go | 35 ++++++++ .../23_merge-k-sorted-lists.go | 81 +++++++++++++++++++ 3 files changed, 152 insertions(+) create mode 100644 go/BinaryTree/124_binary-tree-maximum-path-sum/124_binary-tree-maximum-path-sum.go create mode 100644 go/BinaryTree/1448_count-good-nodes-in-binary-tree/1448_count-good-nodes-in-binary-tree.go create mode 100644 go/LinkedList/23_merge-k-sorted-lists/23_merge-k-sorted-lists.go diff --git a/go/BinaryTree/124_binary-tree-maximum-path-sum/124_binary-tree-maximum-path-sum.go b/go/BinaryTree/124_binary-tree-maximum-path-sum/124_binary-tree-maximum-path-sum.go new file mode 100644 index 000000000..c73d9ccfe --- /dev/null +++ b/go/BinaryTree/124_binary-tree-maximum-path-sum/124_binary-tree-maximum-path-sum.go @@ -0,0 +1,36 @@ +package binarytreemaximumpathsum + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func maxPathSum(root *TreeNode) int { + var maxValue int + maxVal := 1 << 32 + minVal := maxVal * -1 + maxValue = minVal + var maxPathAtNode func(root *TreeNode) int + maxPathAtNode = func(root *TreeNode) int { + if root == nil { + return 0 + } + leftMax := maxPathAtNode(root.Left) + rightMax := maxPathAtNode(root.Right) + leftMax = max(leftMax, 0) + rightMax = max(rightMax, 0) + // If the split has happened + maxValue = max(maxValue, leftMax+rightMax+root.Val) + return root.Val + max(leftMax, rightMax) + } + maxPathAtNode(root) + return maxValue +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/BinaryTree/1448_count-good-nodes-in-binary-tree/1448_count-good-nodes-in-binary-tree.go b/go/BinaryTree/1448_count-good-nodes-in-binary-tree/1448_count-good-nodes-in-binary-tree.go new file mode 100644 index 000000000..ec498ab0d --- /dev/null +++ b/go/BinaryTree/1448_count-good-nodes-in-binary-tree/1448_count-good-nodes-in-binary-tree.go @@ -0,0 +1,35 @@ +package countgoodnodesinbinarytree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func goodNodes(root *TreeNode) int { + maxValue := root.Val + return goodNodesUtil(root, maxValue) +} + +func goodNodesUtil(node *TreeNode, maxValue int) int { + var result int + if node == nil { + return 0 + } + if node.Val >= maxValue { + result = 1 + } else { + result = 0 + } + maxValue = max(node.Val, maxValue) + result += goodNodesUtil(node.Left, maxValue) + result += goodNodesUtil(node.Right, maxValue) + return result +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/go/LinkedList/23_merge-k-sorted-lists/23_merge-k-sorted-lists.go b/go/LinkedList/23_merge-k-sorted-lists/23_merge-k-sorted-lists.go new file mode 100644 index 000000000..6d2e8f6ec --- /dev/null +++ b/go/LinkedList/23_merge-k-sorted-lists/23_merge-k-sorted-lists.go @@ -0,0 +1,81 @@ +package mergeksortedlists + +type ListNode struct { + Val int + Next *ListNode +} + +func mergeKLists(lists []*ListNode) *ListNode { + if len(lists) == 0 { + return nil + } + for len(lists) > 1 { + mergedList := []*ListNode{} + + for i := 0; i < len(lists); i = i + 2 { + var newList1 *ListNode + var newList2 *ListNode + newList1 = lists[i] + if i+1 < len(lists) { + newList2 = lists[i+1] + } + newMergedList := merge2sortedLists(newList1, newList2) + mergedList = append(mergedList, newMergedList) + } + lists = make([]*ListNode, 0) + lists = append(lists, mergedList...) + } + return lists[0] +} + +func merge2sortedLists(list1 *ListNode, list2 *ListNode) *ListNode { + if list1 == nil { + return list2 + } + if list2 == nil { + return list1 + } + dummy := &ListNode{ + Val: 0, + } + head := dummy + for list1 != nil && list2 != nil { + if list1.Val <= list2.Val { + dummy.Next = list1 + list1 = list1.Next + } else { + dummy.Next = list2 + list2 = list2.Next + } + dummy = dummy.Next + } + if list1 != nil { + dummy.Next = list1 + } + if list2 != nil { + dummy.Next = list2 + } + return head.Next +} + +// The solution in leetcode sol is much faster one. here we are not copying the array. +// Initially interval is 1(incrementer: 2) . Indexes that will be considered are [0,2,4] an pairs are (0,1)(2,3)(4,5) +// Basically we are storing the result of (lists[0],lists[1]) pair in lists[0] and (lists[2],lists[3]) pair in lists[2] and (lists[4],lists[5]) in lists[4] +// In the next iteration we get new pair since interval is multiplied by 2 +// Interval is 2(Incrementer: 4) so the new indexes will be 0,4,8 and pairs are (0,2)(4,6)(8,10) +// New pair is (lists[0],lists[2]) and this will be stored in lists[0] +func mergeKListsFasterSolution(lists []*ListNode) *ListNode { + if len(lists) == 0 { + return nil + } + amount := len(lists) + interval := 1 + for interval < amount { + incrementer := interval * 2 + for i := 0; i < (amount - interval); i += incrementer { + lists[i] = merge2sortedLists(lists[i], lists[i+interval]) + } + interval *= 2 + } + return lists[0] +}