├── .gitignore ├── CodeChef └── Beginner │ ├── Chef Watson uses Social Network.py │ ├── Chef and Keyboard.py │ └── Task for Alexey.py ├── CodeForces ├── 4_A_Watermelon.go └── 71A_Way_too_long.go ├── Docs └── README.md ├── GeeksForGeeks ├── Go │ ├── HashMap │ │ ├── printAllAnagrams.go │ │ └── twoSums.go │ ├── RESTAPI │ │ ├── gin_auth.go │ │ └── jsonUnmarshal.go │ ├── Search_Sort │ │ ├── binary-search.go │ │ └── linear-search-using-multi-threading.go │ ├── Tree │ │ ├── binaryTree.go │ │ └── dfs_binaryTree.go │ ├── arrays │ │ ├── check-for-balanced-parentheses-in-an-expression.go │ │ ├── check-if-first-and-last-digit-same.go │ │ ├── missing_number.go │ │ ├── next-greater-element.go │ │ └── print-a-given-matrix-in-spiral-form.go │ ├── channels-and-goroutine │ │ ├── ChannelExample.go │ │ ├── ChannelWaitGroup.go │ │ ├── bufferedChannels.go │ │ ├── channelIsClosed.go │ │ └── channelQuit.go │ ├── linked-lists │ │ └── linkedList.go │ ├── other │ │ ├── 2Darray.go │ │ ├── callByReference.go │ │ ├── find-the-element-that-appears-once.go │ │ └── interfacesExample.go │ ├── queue │ │ └── queue.go │ ├── stacks │ │ └── stacks.go │ └── strings │ │ └── wordMatch.go └── Python │ ├── Array │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-34.pyc │ │ ├── arr_insert.cpython-34.pyc │ │ ├── arr_printer.cpython-34.pyc │ │ ├── arr_remove.cpython-34.pyc │ │ └── arr_search.cpython-34.pyc │ ├── arr_init.py │ ├── arr_insert.py │ ├── arr_printer.py │ ├── arr_remove.py │ └── arr_search.py │ ├── charRemoveTopalindrome.py │ ├── hello.py │ └── matrix_spiral.py ├── Go_Samples ├── gin_basic_auth_middleware │ └── server.go ├── mux_basic_auth_middleware │ └── server.go ├── net_http_login_with_body │ └── server.go └── samples │ ├── simple_any.go │ ├── simple_channel.go │ ├── simple_defer.go │ ├── simple_filereader_using_buffer.go │ ├── simple_generics.go │ ├── simple_http.go │ ├── simple_interface.go │ ├── simple_pointer.go │ ├── simple_select.go │ ├── simple_slices.go │ ├── simple_string_concat.go │ ├── simple_unmarshal.go │ └── simple_wg_routines.go ├── HackerEarth ├── Akash and the Assignment.cpp ├── Assorted Arrangements.py ├── Counting Traingles.cs ├── Crazy Kangaroo.c ├── KGBD.py ├── Mind Palaces.cpp ├── Roy and Matrix Sum.cpp ├── Roys Chocolate.c ├── Roys Life Cycle.cpp ├── Vanya and Array.py ├── Will you be my Friend.java ├── ZrZr.py ├── algorithms │ ├── PalindromeCount.go │ ├── possibleSums.go │ └── xorry.go └── challenges │ └── expand-it-1.go ├── HackerRank ├── 30_days_of_code │ ├── 10_binary_numbers.py │ ├── 11_2d_arrays.py │ ├── 12_inheritance.py │ ├── 15_linked_list.py │ ├── 18_queues_and_stacks.py │ ├── 20_sorting.py │ ├── 29_bitwise_and.py │ └── 9_recursion.py ├── DataStructure │ └── Array │ │ ├── 2D_Array.go │ │ └── Arrays_DS.go ├── cracking_the_coding_interview │ ├── arrays_left_rotation.py │ ├── ctci-balanced-brackets.go │ ├── ctci-ransom-note.go │ └── ctci_making_anagrams.go ├── interview-preparation-kit │ ├── GreedyAlgorithms │ │ └── greedy-florist.go │ ├── arrays │ │ └── minimum-swap-2.go │ ├── dictAndmaps │ │ ├── count-triplets.go │ │ └── sherlock-and-anagrams.go │ ├── linkedLists │ │ └── reverseDoublyLL.go │ └── stack │ │ ├── balancedBrackets.go │ │ └── stack.go └── other_programs │ ├── HandShake.c │ ├── Insertion_Sort_1.c │ ├── Insertion_sort_2.c │ ├── Lonely_Integer.c │ ├── Maximum_Draws.c │ ├── Pangrams.c │ ├── alternating_character.java │ ├── anagram.java │ ├── angry_professor.c │ ├── chocolate_feast.cpp │ ├── compare_the_triplets.py │ ├── funny_string.c │ ├── gem_stones.java │ ├── is_fibo.c │ ├── kangaroo.py │ ├── love_letter_mystery.java │ ├── luck_balance.py │ ├── make_it_anagram.cpp │ ├── making_anagrams.java │ ├── maximizing_xor.cpp │ ├── palindrom_index.java │ ├── sherlcok_and_squares.c │ ├── staircase.cpp │ ├── swap_case.py │ └── utopian_tree.c ├── LeetCode ├── 30_day_challenge │ └── 2020_aug │ │ └── single_number.go ├── Card │ └── Recursion │ │ └── reverse_a_string.go ├── Easy │ ├── Computation │ │ ├── counting-words-with-a-given-prefix.go │ │ ├── fibonacci-number.go │ │ └── number-of-steps-to-reduce-a-number-to-zero.go │ ├── LinkedList │ │ ├── intersection-of-two-linked-lists.go │ │ ├── linked-list-cycle.go │ │ ├── linked_list_remove_duplicates.go │ │ ├── linkedlist_reverse.go │ │ ├── middle_of_ll.go │ │ └── palindrome-linked-list.go │ ├── Stack_Queue │ │ └── valid-parentheses.go │ ├── array │ │ ├── best-time-to-buy-and-sell-stock.go │ │ ├── contains_duplicate.go │ │ ├── decompress_encoded_list.go │ │ ├── divide-array-into-equal-pairs.go │ │ ├── intersect_of_2_arrays.go │ │ ├── kth-largest-element-in-a-stream.go │ │ ├── last-stone-weight.go │ │ ├── longest-common-prefix.go │ │ ├── maximum-subarray.go │ │ ├── maximum-units-on-a-truck.go │ │ ├── merge-sorted-array.go │ │ ├── missing_number.go │ │ ├── move-zeroes.go │ │ ├── plus_one.go │ │ ├── remove_dup_from_sorted_array.go │ │ ├── remove_duplicates_from_sorted_array.go │ │ ├── remove_element.go │ │ ├── remove_one_element_to_make_array_increasing.go │ │ ├── reverse_integer.go │ │ ├── running-sum-of-1d-array.go │ │ ├── search-insert-position.go │ │ ├── single_number.go │ │ └── sort-array-by-parity.go │ ├── hashmap │ │ ├── hashmap_Two_Sum.go │ │ └── hashmap_contains-duplicate.go │ ├── strings │ │ ├── count-asterisks.go │ │ ├── find-words-formed-by-characters.go │ │ ├── first_unique_char.go │ │ ├── implement-strstr.go │ │ ├── is_anagram.go │ │ ├── length-of-last-word.go │ │ ├── longest_common_prefix.go │ │ ├── palindrome.go │ │ ├── ransom-note.go │ │ ├── reverse-words-in-a-string.go │ │ ├── roman_to_number.go │ │ ├── string_reverse_a_string.go │ │ └── valid-palindrome-ii.go │ └── trees │ │ ├── binary-tree-inorder-traversal.go │ │ ├── invert-binary-tree.go │ │ ├── minimum-depth-of-binary-tree.go │ │ ├── path-sum.go │ │ ├── same-tree.go │ │ ├── search-in-a-binary-search-tree.go │ │ └── symmetric-tree.go └── Medium │ ├── Array │ ├── array_rotate.go │ ├── maximum-erasure-value.go │ ├── minimum-deletions.go │ └── two-sum-ii-input-array-is-sorted.go │ ├── LinkedList │ ├── linked_list_add_two_numbers.go │ ├── linked_list_remove_duplicate.go │ ├── linked_list_swap_nodes_in_pairs.go │ └── swapping-nodes-in-a-linked-list.go │ ├── Trees │ ├── binary-tree-level-order-traversal.go │ ├── binary-tree-right-side-view.go │ └── populating-next-right-pointers-in-each-node.go │ ├── hashmap │ ├── hashmap_3Sum.go │ └── hashmap_find_replace_pattern.go │ ├── recursive_dp │ └── recursive_subsets.go │ └── strings │ └── string_manp_longest_substring_without_repeating_chars.go ├── README.md └── go_sample.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | -------------------------------------------------------------------------------- /CodeChef/Beginner/Chef Watson uses Social Network.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | 4 | input_count = input().strip().split() 5 | frnd_count = int(input_count[1]) 6 | special_frdns = input().strip().split() 7 | special_frdns = list(map(int, special_frdns)) 8 | spl_posts = {} 9 | normal_posts = {} 10 | while (frnd_count): 11 | entry = input().strip().split() 12 | if (int(entry[0]) in special_frdns): 13 | spl_posts[int(entry[1])] = entry[2] 14 | else: 15 | normal_posts[int(entry[1])] = entry[2] 16 | frnd_count = frnd_count - 1 17 | 18 | for i in sorted(spl_posts, reverse=True): 19 | print(spl_posts[i]) 20 | 21 | for i in sorted(normal_posts, reverse=True): 22 | print(normal_posts[i]) 23 | -------------------------------------------------------------------------------- /CodeChef/Beginner/Chef and Keyboard.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # TODO: TLE for 10^5 3 | 4 | input_count = int(input()) 5 | while (input_count): 6 | input_data = input().strip().split() 7 | n = int(input_data[0]) 8 | m = int(input_data[1]) 9 | c = int(input_data[2]) 10 | count = 0 11 | for i in range(1, m + 1): 12 | if (i <= c): 13 | for j in range(1, n + 1): 14 | if (j <= c): 15 | if (i * j == c): 16 | count = count + 1 17 | print(count) 18 | input_count = input_count - 1 19 | -------------------------------------------------------------------------------- /CodeChef/Beginner/Task for Alexey.py: -------------------------------------------------------------------------------- 1 | # TODO: TLE for 10^8 2 | from fractions import gcd 3 | 4 | input_count = int(input().strip().split()[0]) 5 | 6 | while (input_count): 7 | min_lcm = 100000000 8 | junk_numbers = input().strip().split() 9 | input_digit = input().strip().split() 10 | input_digit = sorted(list(map(int, input_digit))) 11 | for i in range(0, len(input_digit) - 1): 12 | for j in range(i + 1, len(input_digit)): 13 | temp_lcm = (input_digit[i] * input_digit[j]) / gcd(input_digit[i], input_digit[j]) 14 | if (temp_lcm <= min_lcm): 15 | min_lcm = temp_lcm 16 | print(int(min_lcm)) 17 | input_count = input_count - 1 18 | -------------------------------------------------------------------------------- /CodeForces/4_A_Watermelon.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://codeforces.com/problemset/problem/4/A 5 | Status: Accepted 6 | Runtime: 62 ms 7 | Memory Usage: 10400 KB 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func main() { 14 | var kg int 15 | fmt.Scanf("%d", &kg) 16 | if kg != 2 && kg%2 == 0 { 17 | fmt.Println("YES") 18 | } else { 19 | fmt.Println("NO") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CodeForces/71A_Way_too_long.go: -------------------------------------------------------------------------------- 1 | /* 2 | URL: https://codeforces.com/problemset/problem/71/A 3 | Status: Accepted 4 | Runtime: 62 ms 5 | Memory Usage: 10400 KB 6 | */ 7 | package main 8 | 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func main() { 14 | var wLen int 15 | fmt.Scanf("%d\n", &wLen) // \n is must for codeforces :) 16 | var wArray []string 17 | word := "" 18 | for i := 0; i < wLen; i++ { 19 | fmt.Scanf("%s\n", &word) 20 | wArray = append(wArray, word) 21 | } 22 | for i := range wArray { 23 | wLength := len(wArray[i]) 24 | if wLength <= 10 { 25 | fmt.Println(wArray[i]) 26 | continue 27 | } 28 | fmt.Printf("%s%d%s\n", string(wArray[i][0]), wLength-2, string(wArray[i][wLength-1])) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Docs/README.md: -------------------------------------------------------------------------------- 1 | # List of useful Docs links 2 | 3 | 1. [Guide to Go Profiling, Tracing and Observability](https://github.com/DataDog/go-profiler-notes/blob/main/guide/README.md) 4 | 5 | 6 | 2. [Traps, Gotchas, and Common Mistakes for New Golang Devs](http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/) 7 | 8 | 9 | 3. [Good read on memory leak investigation](https://blog.detectify.com/2019/09/05/how-we-tracked-down-a-memory-leak-in-one-of-our-go-microservices/) 10 | 11 | 12 | 4. [Gotchas in the Go Network Packages Defaults (http.Client)](https://martin.baillie.id/wrote/gotchas-in-the-go-network-packages-defaults/) 13 | 14 | 15 | 5. [Go resiliency pattern (semaphore, timeout, circuit-breaker](https://github.com/eapache/go-resiliency) 16 |
Resiliency patterns are a type of service architecture that help to prevent cascading failures and to preserve functionality in the event of service failure. 17 | 18 | 19 | 6. [Array Interview Questions](https://igotanoffer.com/blogs/tech/array-interview-questions) 20 | 21 | 22 | 7. [VIDEO: Introduction to System Design](https://www.youtube.com/watch?v=MbjObHmDbZo) 23 | 24 | 25 | 8. [Go Proverbs](http://go-proverbs.github.io/) 26 | 27 | 28 | 9. [Go code review helper](https://github.com/golang/go/wiki/CodeReviewComments#go-code-review-comments) 29 | 30 | 31 | 10. [What's up with slice pointer by reference](https://medium.com/swlh/golang-tips-why-pointers-to-slices-are-useful-and-how-ignoring-them-can-lead-to-tricky-bugs-cac90f72e77b) 32 | 33 | 11. [Understanding golang data types](https://www.digitalocean.com/community/tutorials/understanding-data-types-in-go) 34 | 35 | 12. [High-performance JSON parsing in Go](https://www.cockroachlabs.com/blog/high-performance-json-parsing/) 36 | 37 | 13. [How to build a production ready microservice](https://www.oreilly.com/library/view/production-ready-microservices/9781491965962/ch01.html) 38 | 39 | 40 | 14. [How to scale from zero to millions](https://systeminterview.com/scale-from-zero-to-millions-of-users.php) 41 | 42 | 15. [Scaling a go application](https://github.com/zeromicro/go-zero) 43 | 44 | 16. [Problems with Integer. Good Read](https://jvns.ca/blog/2023/01/18/examples-of-problems-with-integers/) 45 | 46 | 17. [Golang quirks and tricks](https://eblog.fly.dev/quirks.html) 47 | 48 | 49 |

50 | SRE / Application metrics/ Go Trace: 51 | 52 | 1. [The Four Golden Signals](https://sre.google/sre-book/monitoring-distributed-systems/#xref_monitoring_golden-signals) 53 | 54 | 2. [Go tracer which supposed to be better that go-tracer](https://github.com/dominikh/gotraceui) 55 | 56 |

57 | Principles / Design patterns: 58 | 59 | 1. [Adapter pattern in Go](https://bitfieldconsulting.com/golang/adapter) 60 | 61 | 2. [How to ace System Design Interview?](https://helloacm.com/facebook-onsite-interview-preparation-part-3-how-to-ace-a-design-interview/) 62 | 63 | 64 | 65 |

66 | Interview Docs: 67 | 68 | 1. [Interview Best Practices](https://careers.google.com/interview-tips/?src=Online%2FSocial%2FKeyword_blog&utm_campaign=&utm_medium=Google%20Website&utm_source=Online) 69 | 70 | 2. [Mock Interview Videos](https://interviewing.io/recordings/) 71 | 72 | 3. [How to write a CV?](https://somehowimanage.blog/2019/01/28/somehow-i-recruit-cv-yeah-yeah-cv/) 73 | 74 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/HashMap/printAllAnagrams.go: -------------------------------------------------------------------------------- 1 | //https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/ 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "sort" 7 | "strings" 8 | ) 9 | 10 | func sortWord(str string) string{ 11 | chars := strings.Split(str,"") 12 | sort.Strings(chars) 13 | return strings.Join(chars,"") 14 | } 15 | 16 | func printAllAnagrams(words []string) { 17 | wordMap := make(map[string][]int) 18 | countMap := make(map[int]string) 19 | for i, word := range words { 20 | sortedWord := sortWord(word) 21 | wordMap[sortedWord] =append(wordMap[sortedWord],i) 22 | } 23 | maxCount := 0 24 | for key := range wordMap{ 25 | countMap[len(wordMap[key])] = key 26 | if maxCount < len(wordMap[key]){ 27 | maxCount = len(wordMap[key]) 28 | } 29 | } 30 | for i:= maxCount;i>=1;i--{ 31 | key := countMap[i] 32 | wordIdxs := wordMap[key] 33 | for _,idx := range wordIdxs{ 34 | fmt.Print(words[idx]," ") 35 | } 36 | } 37 | } 38 | 39 | func main() { 40 | strngs := []string{"cat", "tac", "dog", "god", "act"} 41 | printAllAnagrams(strngs) 42 | } 43 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/HashMap/twoSums.go: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/two-sum/solution/ 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func twoSum(nums []int, target int) []int { 9 | sumMap := make(map[int]int) 10 | for i,val := range nums{ 11 | if idx,ok := sumMap[target-val];ok{ 12 | return []int{idx,i} 13 | } 14 | sumMap[val] = i 15 | } 16 | return nil 17 | } 18 | 19 | func main(){ 20 | values := []int{2, 7, 11, 15} 21 | target := 9 22 | idxs :=twoSum(values,target) 23 | fmt.Println(idxs) 24 | values = []int{20, 70, 1, 15} 25 | target = 38 26 | idxs =twoSum(values,target) 27 | fmt.Println(idxs) 28 | } 29 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/RESTAPI/gin_auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | curl request 5 | curl --request GET \ 6 | --url http://localhost:8085/rest/names \ 7 | --header 'authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' //the encoded string of usernam:password 8 | */ 9 | import ( 10 | "encoding/base64" 11 | "encoding/json" 12 | //"io/ioutil" 13 | "io" 14 | "net/http" 15 | "strings" 16 | 17 | "github.com/gin-gonic/gin" 18 | ) 19 | 20 | var ( 21 | Names = []string{"Bharath Kumar", "Jon Snow"} 22 | ) 23 | 24 | type Name struct { 25 | Name string `json:"name",omitempty` 26 | } 27 | 28 | func authMiddleware() gin.HandlerFunc { 29 | //authenticate the creds here 30 | return func(c *gin.Context) { 31 | 32 | s := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2) 33 | if len(s) != 2 { 34 | c.JSON(http.StatusBadRequest, "Authorization header is not passed") 35 | c.Abort() 36 | return 37 | } 38 | 39 | b, err := base64.StdEncoding.DecodeString(s[1]) 40 | if err != nil { 41 | c.JSON(http.StatusUnauthorized, "Auth Decode error") 42 | c.Abort() 43 | return 44 | } 45 | 46 | pair := strings.SplitN(string(b), ":", 2) 47 | if len(pair) != 2 { 48 | c.JSON(http.StatusUnauthorized, "Decoded string is not correct") 49 | c.Abort() 50 | return 51 | } 52 | 53 | if pair[0] != "username" || pair[1] != "password" { 54 | c.JSON(http.StatusUnauthorized, "Username/password is not correct") 55 | c.Abort() 56 | return 57 | } 58 | 59 | } 60 | } 61 | 62 | func getNames(c *gin.Context) { 63 | c.JSON(http.StatusOK, Names) 64 | } 65 | 66 | func putNames(c *gin.Context) { 67 | var name Name 68 | //c.BindJSON(&name) //this can be used instead of unmarshal 69 | //bodyByte, err := ioutil.ReadAll(c.Request.Body) 70 | bodyByte, err := io.ReadAll(c.Request.Body) 71 | if err != nil { 72 | c.JSON(http.StatusInternalServerError, "Check the body sent") 73 | return 74 | } 75 | err = json.Unmarshal(bodyByte, &name) 76 | if err != nil { 77 | c.JSON(http.StatusInternalServerError, "Check the body sent") 78 | return 79 | } 80 | 81 | Names = append(Names, name.Name) 82 | c.JSON(http.StatusAccepted, Names) 83 | } 84 | 85 | func main() { 86 | //create a new gin router 87 | router := gin.New() 88 | //create a new router group, this will create localhost:/rest/names 89 | names := router.Group("/rest/names") 90 | //All middlewares must be passed will come under USE 91 | names.Use(authMiddleware()) 92 | names.GET("", getNames) 93 | names.POST("", putNames) 94 | 95 | //start the server at port 8085 96 | router.Run(":8085") 97 | } 98 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/RESTAPI/jsonUnmarshal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | type Items struct { 9 | Vegetables map[string]int `json:"vegetables"` 10 | Fruits Seasonal `json:"fruits"` 11 | } 12 | 13 | type Seasonal struct { 14 | Fruits map[string]int `json:"seasonal"` 15 | } 16 | 17 | func main() { 18 | var items *Items 19 | data := []byte("{\"vegetables\":{\"carrot\":5,\"beans\":4},\"fruits\":{\"seasonal\":{\"apple\":3,\"banana\":2}}}") 20 | json.Unmarshal(data, &items) 21 | 22 | for key, value := range items.Vegetables { 23 | fmt.Printf("%s: %d\n", key, value) 24 | } 25 | 26 | for key, value := range items.Fruits.Fruits { 27 | fmt.Printf("%s: %d\n", key, value) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/Search_Sort/binary-search.go: -------------------------------------------------------------------------------- 1 | //https://www.geeksforgeeks.org/binary-search/ 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | 9 | func binarySearch(elements []int,low, high, key int) int { 10 | if high < low { 11 | return -1 12 | } 13 | 14 | mid := (low +high)/2 15 | if elements[mid] == key{ 16 | return mid 17 | } 18 | 19 | if key > elements[mid] { 20 | return binarySearch(elements,mid+1,high,key) 21 | } 22 | return binarySearch(elements,low,mid-1,key) 23 | } 24 | 25 | func main() { 26 | elems := []int{1,2,3,4,5,6,7,10,20} 27 | key:= 20 28 | pos := binarySearch(elems,0,len(elems),key) 29 | if pos == -1 { 30 | fmt.Printf("Couldnt find the key %d in element list %+v\n",key,elems) 31 | } 32 | fmt.Printf("found the key %d in element list %+v, at position %d\n",key,elems,pos) 33 | 34 | 35 | elems = []int{10,30,50,80,80} 36 | key = 20 37 | pos = binarySearch(elems,0,len(elems),key) 38 | if pos == -1 { 39 | fmt.Printf("Couldnt find the key %d in element list %+v\n",key,elems) 40 | } 41 | fmt.Printf("found the key %d in element list %+v, at position %d\n",key,elems,pos) 42 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Go/Search_Sort/linear-search-using-multi-threading.go: -------------------------------------------------------------------------------- 1 | //https://www.geeksforgeeks.org/linear-search-using-multi-threading/ 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func linearSearch(element, key, pos int, chanEle chan int) chan int { 9 | fmt.Println("pos",pos) 10 | if element == key { 11 | chanEle <- pos 12 | } 13 | return chanEle 14 | } 15 | 16 | func main() { 17 | 18 | chanElem := make(chan int) 19 | elements := []int{1, 4, 13, 24, 55, 68} 20 | 21 | for pos, elem := range elements { 22 | go linearSearch(elem, 13, pos, chanElem) 23 | } 24 | fmt.Println("position is: ", <-chanElem) 25 | 26 | } 27 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/Tree/binaryTree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // tree node structure 6 | type Node struct { 7 | data int 8 | leftChild *Node 9 | rightChild *Node 10 | } 11 | 12 | type queue struct { 13 | queue []*Node 14 | } 15 | 16 | // add the element to the end 17 | func (q *queue) enque(node *Node) { 18 | q.queue = append(q.queue, node) 19 | } 20 | 21 | // remove the first element and return it 22 | func (q *queue) deque() *Node { 23 | if len(q.queue) <= 0 { 24 | return nil 25 | } 26 | node := q.queue[0] 27 | q.queue = q.queue[1:] 28 | return node 29 | } 30 | 31 | func newNode(data int) *Node { 32 | newNode := new(Node) 33 | newNode.data = data 34 | return newNode 35 | } 36 | 37 | // find the parent value and create a new node. New node is placed on parent node based on the leftChild value 38 | // TODO: we can change the logic to insert to the next previous node too. 39 | /* 40 | if (temp->left != NULL){ 41 | q.push(temp->left); 42 | else { 43 | temp->left = CreateNode(data); 44 | }} 45 | */ 46 | func addNode(root *Node, parentVal, newNodeVal int, leftChild bool) { 47 | node := newNode(newNodeVal) 48 | q := &queue{} 49 | q.enque(root) 50 | for { 51 | // keep on going until the queue is empty 52 | if len(q.queue) <= 0 { 53 | break 54 | } 55 | queueNode := q.deque() // pop 56 | // if the parent node is the node we are searching for,stop the op 57 | if queueNode.data == parentVal { 58 | if leftChild { 59 | queueNode.leftChild = &Node{data: newNodeVal} 60 | return 61 | } 62 | queueNode.rightChild = node 63 | return 64 | } 65 | 66 | if queueNode.leftChild != nil { 67 | q.enque(queueNode.leftChild) 68 | } 69 | if queueNode.rightChild != nil { 70 | q.enque(queueNode.rightChild) 71 | } 72 | } 73 | } 74 | 75 | func inOrder(node *Node) { 76 | if node == nil { 77 | return 78 | } 79 | inOrder(node.leftChild) 80 | fmt.Printf("%d->", node.data) 81 | inOrder(node.rightChild) 82 | } 83 | 84 | // keep on checking children sum for left and right child, until we hit the leaf. 85 | // If one of the sum found to be not equal, return false 86 | // https://www.geeksforgeeks.org/check-for-children-sum-property-in-a-binary-tree/ 87 | func checkForChildreSum(node *Node) bool { 88 | if node == nil { 89 | return false 90 | } 91 | var l, r int 92 | if node.leftChild != nil { 93 | l = node.leftChild.data 94 | } 95 | if node.rightChild != nil { 96 | r = node.rightChild.data 97 | } 98 | fmt.Printf("Node: %d, l:%d, r:%d\n", node.data, l, r) 99 | 100 | if node.data == l+r { 101 | return true 102 | } 103 | 104 | return checkForChildreSum(node.leftChild) || checkForChildreSum(node.rightChild) 105 | } 106 | 107 | func main() { 108 | // node structure 109 | // 60 110 | // 20 30 111 | // 10 40 10 90 112 | // root node 113 | root := newNode(60) 114 | addNode(root, 60, 20, true) 115 | addNode(root, 60, 30, false) 116 | addNode(root, 20, 10, true) 117 | addNode(root, 20, 40, false) 118 | addNode(root, 30, 10, true) 119 | addNode(root, 30, 90, false) 120 | // inOrder(root) 121 | fmt.Println(checkForChildreSum(root)) 122 | } 123 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/Tree/dfs_binaryTree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Node struct { 6 | data int 7 | leftChild *Node 8 | rightChild *Node 9 | } 10 | 11 | func newNode(data int) *Node { 12 | newNode := new(Node) 13 | newNode.data = data 14 | return newNode 15 | } 16 | 17 | // DFS 18 | func CreateTree() *Node { 19 | //initialize the root 20 | root := newNode(1) 21 | 22 | root.leftChild = newNode(2) 23 | root.rightChild = newNode(3) 24 | 25 | root.leftChild.leftChild = newNode(4) 26 | root.leftChild.rightChild = newNode(5) 27 | 28 | return root 29 | } 30 | 31 | func InOrder(node *Node) { 32 | if node == nil { 33 | return 34 | } 35 | InOrder(node.leftChild) 36 | fmt.Printf("%d->", node.data) 37 | InOrder(node.rightChild) 38 | } 39 | 40 | // using stack 41 | func preorderTraversal(root *TreeNode) []int { 42 | var ans []int 43 | if root == nil { 44 | return ans 45 | } 46 | stack := []*TreeNode{root} 47 | for len(stack) > 0 { 48 | top := stack[len(stack)-1] 49 | stack = stack[:len(stack)-1] 50 | ans = append(ans, top.Val) 51 | if top.Right != nil { 52 | stack = append(stack, top.Right) 53 | } 54 | if top.Left != nil { 55 | stack = append(stack, top.Left) 56 | } 57 | } 58 | return ans 59 | } 60 | 61 | func PreOrder(node *Node) { 62 | if node == nil { 63 | return 64 | } 65 | fmt.Printf("%d->", node.data) 66 | PreOrder(node.leftChild) 67 | PreOrder(node.rightChild) 68 | } 69 | 70 | func PostOrder(node *Node) { 71 | if node == nil { 72 | return 73 | } 74 | PostOrder(node.leftChild) 75 | PostOrder(node.rightChild) 76 | fmt.Printf("%d->", node.data) 77 | } 78 | 79 | func main() { 80 | root := CreateTree() 81 | 82 | //print preorder 83 | fmt.Println("\nPre Order:") 84 | PreOrder(root) 85 | 86 | //print inorder 87 | fmt.Println("\n\nIn Order:") 88 | InOrder(root) 89 | 90 | //print postorder 91 | fmt.Println("\n\nPost Order:") 92 | PostOrder(root) 93 | } 94 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/arrays/check-for-balanced-parentheses-in-an-expression.go: -------------------------------------------------------------------------------- 1 | //https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/ 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | var MatchingBraces = map[string]string{ 9 | ")": "(", 10 | "]": "[", 11 | "}": "{", 12 | } 13 | 14 | func isBlanced(expression string) bool { 15 | fmt.Printf("Passed string is %s : ",expression) 16 | if len(expression)%2 != 0 { 17 | return false 18 | } 19 | m := len(expression) / 2 20 | for i := 0; i < m; i++ { 21 | if string(expression[m-1-i]) != MatchingBraces[string(expression[m+i])] { 22 | return false 23 | } 24 | } 25 | return true 26 | } 27 | 28 | func main() { 29 | fmt.Println(isBlanced("([])")) 30 | fmt.Println(isBlanced("([)")) 31 | fmt.Println(isBlanced("([[[[)")) 32 | return 33 | } 34 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/arrays/check-if-first-and-last-digit-same.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func isFirstLastDigitSame(arr []int) { 8 | for i, val := range arr { 9 | first := val % 10 10 | for { 11 | if val < 10 { 12 | break 13 | } 14 | val = val / 10 15 | } 16 | if first == val { 17 | fmt.Println(arr[i]) 18 | } 19 | } 20 | } 21 | 22 | func main() { 23 | arr := []int{111, 123, 343} 24 | isFirstLastDigitSame(arr) 25 | } 26 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/arrays/missing_number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://www.geeksforgeeks.org/find-the-missing-number/ 5 | */ 6 | import ( 7 | "fmt" 8 | ) 9 | 10 | // we are dealing with n-1 elements. and we need to calculate summation for n * n+1 /2 11 | // array has to be continuos and the extra element should always be 1 to n+1 12 | // input 1,3,4. Here 2 is missing. Here 'n' is 4. 13 | func missingNumber(nums []int) int { 14 | len := len(nums) 15 | summation := ((len + 1) * ((len + 2) / 2)) 16 | sum := 0 17 | for _, num := range nums { 18 | sum += num 19 | } 20 | return summation - sum 21 | } 22 | 23 | // for the given array [2,3], calculate xor for idx and numbers with given 'n'. i.e 1^2 ^2^3 ^3 24 | func missingNumberXor(nums []int) int { 25 | xor := len(nums) + 1 26 | for idx, num := range nums { 27 | xor = xor ^ num ^ idx + 1 28 | } 29 | return xor 30 | } 31 | 32 | func main() { 33 | fmt.Println("input: <>, output:", missingNumberXor([]int{2, 3})) 34 | } 35 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/arrays/next-greater-element.go: -------------------------------------------------------------------------------- 1 | //https://www.geeksforgeeks.org/next-greater-element/ 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | func nextGreaterElement(elements []int) { 10 | eleLen := len(elements) 11 | nextBiggerElements := make([]int, eleLen) 12 | for i := eleLen - 1; i >= 0; i-- { 13 | nextMinimum := -1 14 | for j := i + 1; j <= eleLen-1; j++ { 15 | if elements[j] > elements[i] { 16 | if nextMinimum == -1 || nextMinimum > elements[j] { 17 | nextMinimum = elements[j] 18 | } 19 | } 20 | } 21 | nextBiggerElements[i] = nextMinimum 22 | } 23 | fmt.Printf("Element is %v\n", nextBiggerElements) 24 | } 25 | 26 | func main() { 27 | ele := []int{4, 5, 2, 25} 28 | nextGreaterElement(ele) 29 | 30 | ele = []int{13, 7, 6, 12} 31 | nextGreaterElement(ele) 32 | 33 | ele = []int{11, 13, 21, 3} 34 | nextGreaterElement(ele) 35 | 36 | ele = []int{2,5,9,6,3,4,8,15,12} 37 | nextGreaterElement(ele) 38 | } 39 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/arrays/print-a-given-matrix-in-spiral-form.go: -------------------------------------------------------------------------------- 1 | //https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func printInSpiral(matrix [4][4]int, rowLen, columnLen int) { 9 | 10 | for i := 0; i < rowLen/2; i++ { 11 | //print LR top row 12 | for lr := i; lr < columnLen-i-1; lr++ { 13 | fmt.Printf("%d->", matrix[i][lr]) 14 | } 15 | 16 | //print TB right column 17 | for tb := i; tb < rowLen-i-1; tb++ { 18 | fmt.Printf("%d->", matrix[tb][columnLen-i-1]) 19 | } 20 | 21 | //print RL below row 22 | for rl := columnLen - 1 - i; rl > i; rl-- { 23 | fmt.Printf("%d->", matrix[rowLen-1-i][rl]) 24 | } 25 | 26 | //print BT left column 27 | for bt := rowLen - 1 - i; bt > i; bt-- { 28 | fmt.Printf("%d->", matrix[bt][i]) 29 | } 30 | } 31 | 32 | } 33 | 34 | func main() { 35 | var matrix [4][4]int 36 | 37 | for i := 0; i < 4; i++ { 38 | for j := 0; j < 4; j++ { 39 | matrix[i][j] = i*1 + j*2 40 | } 41 | } 42 | fmt.Println(matrix) 43 | printInSpiral(matrix, 4, 4) 44 | fmt.Println() 45 | 46 | //matrix2 := make([][]int, 6*6) 47 | // 48 | //for i := 0; i < 6; i++ { 49 | // for j := 0; j < 6; j++ { 50 | // matrix2[i][j] = i*2 + j + 3 51 | // } 52 | //} 53 | //fmt.Println(matrix2) 54 | //printInSpiral(matrix2, 6, 6) 55 | //fmt.Println() 56 | 57 | } 58 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/channels-and-goroutine/ChannelExample.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func sumTwo(x, y int, sum chan int) { 8 | sum <- x + y 9 | //if x%2 != 0 { 10 | // time.Sleep(time.Second) 11 | //} 12 | } 13 | 14 | func main() { 15 | //single channel 16 | sum := make(chan int) 17 | go func() { 18 | sumTwo(5, 10, sum) 19 | 20 | }() 21 | fmt.Println(<-sum) 22 | go func() { 23 | sumTwo(10, 15, sum) 24 | }() 25 | fmt.Println(<-sum) 26 | } 27 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/channels-and-goroutine/ChannelWaitGroup.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | func sumIt(x, y int, sum chan int) { 9 | sum <- x + y 10 | 11 | //time.Sleep(time.Second) 12 | } 13 | 14 | func main() { 15 | var wg sync.WaitGroup 16 | wg.Add(2) 17 | //single channel 18 | sum := make(chan int) 19 | go func() { 20 | go sumIt(5, 10, sum) 21 | fmt.Println(<-sum) 22 | wg.Done() 23 | }() 24 | 25 | go func() { 26 | go sumIt(10, 15, sum) 27 | fmt.Println(<-sum) 28 | wg.Done() 29 | }() 30 | wg.Wait() 31 | } 32 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/channels-and-goroutine/bufferedChannels.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func twoNums(y int, nums chan int) { 6 | nums <- y + 1 7 | //close(nums) 8 | nums <- y - 1 9 | } 10 | 11 | func main() { 12 | //single channel 13 | nums := make(chan int, 2) 14 | twoNums(5, nums) 15 | fmt.Println(<-nums) 16 | fmt.Println(<-nums) 17 | } 18 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/channels-and-goroutine/channelIsClosed.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // <- is used to make sure that, 6 | // this function is not writing to the channel 7 | func IsClosed(ch <-chan int) bool { 8 | select { 9 | case <-ch: 10 | return true 11 | default: 12 | } 13 | 14 | return false 15 | } 16 | 17 | func main() { 18 | c := make(chan int) 19 | fmt.Println(IsClosed(c)) // false 20 | close(c) 21 | fmt.Println(IsClosed(c)) // true 22 | } 23 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/channels-and-goroutine/channelQuit.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | 7 | "time" 8 | ) 9 | 10 | func quitChannel(quit chan bool) { 11 | time.Sleep(time.Second) 12 | // Do stuff 13 | s1 := rand.NewSource(time.Now().UnixNano()) 14 | r1 := rand.New(s1) 15 | rand := r1.Int63n(100) 16 | if rand%2 == 0 { 17 | quit <- true 18 | quit <- true 19 | } 20 | fmt.Println("got odd, closing channel", rand) 21 | close(quit) 22 | } 23 | 24 | func main() { 25 | quit := make(chan bool) 26 | go quitChannel(quit) 27 | for { 28 | select { 29 | case <-quit: 30 | fmt.Println("Received quit") 31 | return 32 | default: 33 | println("Waiting to get data or close channel...") 34 | time.Sleep(time.Millisecond * 300) 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/linked-lists/linkedList.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Node struct { 8 | data int 9 | next *Node 10 | } 11 | 12 | func PrintLinkedList(head *Node) { 13 | if head == nil { 14 | fmt.Println("Linked List Head is nil") 15 | } 16 | node := head 17 | for { 18 | fmt.Print(node.data, "->") 19 | if node.next == nil { 20 | break 21 | } 22 | node = node.next 23 | } 24 | fmt.Println("nil") 25 | } 26 | 27 | func AddNode(head *Node, value int) *Node { 28 | newNode := new(Node) 29 | newNode.data = value 30 | if head == nil { 31 | head = newNode 32 | return head 33 | } 34 | 35 | node := head 36 | for { 37 | if node.next == nil { 38 | break 39 | } 40 | node = node.next 41 | } 42 | node.next = newNode 43 | return head 44 | } 45 | 46 | func DeleteNode(head *Node, position int) *Node { 47 | if head == nil { 48 | fmt.Println("The Linked list head is nil") 49 | return head 50 | } 51 | if position == 0 { 52 | head = nil 53 | return head 54 | } 55 | 56 | nodeRef := head 57 | i := 0 58 | for { 59 | lastNodeRef := nodeRef 60 | if nodeRef.next != nil { 61 | nodeRef = nodeRef.next 62 | i++ 63 | } else { 64 | fmt.Println("Node Not found for position: ", position) 65 | return head 66 | } 67 | 68 | if i == position { 69 | fmt.Println("Deleted the Node at position: ", position) 70 | lastNodeRef.next = nodeRef.next 71 | return head 72 | } 73 | } 74 | 75 | return head 76 | } 77 | 78 | func main() { 79 | var head *Node 80 | head = AddNode(head, 20) 81 | AddNode(head, 30) 82 | AddNode(head, 40) 83 | AddNode(head, 50) 84 | // PrintLinkedList(head) 85 | // RemoveDuplicates(head) 86 | // head = DeleteNode(head, 1) 87 | // head = DeleteNode(head, 5) 88 | // PrintMiddleNode(head) 89 | // head = ReverseLinkedList(head) 90 | // head = ReverseWithGroup(head, 2) 91 | /* var head1 *Node;head1 = AddNode(head1, 22);AddNode(head1, 23);AddNode(head1, 24);ListAlternate(head, head1) */ 92 | PrintLinkedList(head) 93 | } 94 | 95 | // solutions to the g4g questions 96 | 97 | // https://www.geeksforgeeks.org/write-a-c-function-to-print-the-middle-of-the-linked-list/ 98 | func PrintMiddleNode(head *Node) { 99 | if head == nil { 100 | fmt.Println("No LL") 101 | return 102 | } 103 | ptr := head 104 | ptr2 := head 105 | for { 106 | if ptr2.next == nil { 107 | fmt.Println("Middle Node", ptr.data) 108 | break 109 | } 110 | if ptr2.next.next == nil { 111 | fmt.Println("Middle Node", ptr.next.data) 112 | break 113 | } 114 | ptr2 = ptr2.next.next 115 | ptr = ptr.next 116 | } 117 | } 118 | 119 | // https://www.geeksforgeeks.org/reverse-a-linked-list/ 120 | func ReverseLinkedList(head *Node) *Node { 121 | var prev, next *Node 122 | currentNode := head 123 | for { 124 | if currentNode == nil { 125 | return prev 126 | } 127 | next = currentNode.next 128 | currentNode.next = prev 129 | prev = currentNode 130 | currentNode = next 131 | } 132 | } 133 | 134 | // https://practice.geeksforgeeks.org/problems/remove-duplicate-element-from-sorted-linked-list/1 135 | func RemoveDuplicates(head *Node) { 136 | currentNode := head 137 | for { 138 | if currentNode == nil || currentNode.next == nil { 139 | return 140 | } 141 | if currentNode.data == currentNode.next.data { 142 | currentNode.next = currentNode.next.next 143 | continue 144 | } 145 | currentNode = currentNode.next 146 | } 147 | } 148 | 149 | // https://practice.geeksforgeeks.org/problems/reverse-a-linked-list-in-groups-of-given-size/1 150 | func ReverseWithGroup(head *Node, group int) *Node { 151 | var prev, next *Node 152 | currentNode := head 153 | for { 154 | // same old reversal logic with group limit 155 | for i := 0; i < group; i++ { 156 | if currentNode == nil { 157 | break 158 | } 159 | next = currentNode.next 160 | currentNode.next = prev 161 | prev = currentNode 162 | currentNode = next 163 | } 164 | // If the next node exist, set the head.next (first node of current recursive list) with the next reversed group 165 | if next != nil { 166 | head.next = ReverseWithGroup(next, group) 167 | } 168 | // return the last node of the group, which is the first node after the reversing the current group 169 | return prev 170 | } 171 | } 172 | 173 | // https://www.geeksforgeeks.org/merge-a-linked-list-into-another-linked-list-at-alternate-positions/ 174 | func ListAlternate(head, head2 *Node) { 175 | cur1 := head 176 | cur2 := head2 177 | for { 178 | if (cur1 == nil && cur2 == nil) || cur2 == nil { 179 | return 180 | } 181 | if cur1 != nil && cur1.next == nil { 182 | cur1.next = cur2 183 | cur2 = cur2.next 184 | cur1 = cur1.next 185 | } 186 | next2 := cur2.next 187 | next1 := cur1.next 188 | cur1.next = cur2 189 | cur1.next.next = next1 190 | cur2 = next2 191 | cur1 = cur1.next.next 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/other/2Darray.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main(){ 8 | value := [2][2]int{} 9 | value[0][0] = 6 10 | fmt.Println(value) 11 | 12 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Go/other/callByReference.go: -------------------------------------------------------------------------------- 1 | // It is not possible to use the same address location in golang, 2 | // So Call by reference doesnot work 3 | package main 4 | 5 | import "fmt" 6 | 7 | func fn(m *int) { 8 | fmt.Printf("%v\n",m) 9 | *m = 1 10 | } 11 | 12 | func main() { 13 | var m int 14 | fn(&m) 15 | fmt.Printf("%v\n",&m) 16 | fmt.Println(m) 17 | } 18 | 19 | //output is: 20 | //0xc000006028 21 | //0xc000006028 22 | //1 23 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/other/find-the-element-that-appears-once.go: -------------------------------------------------------------------------------- 1 | // https://www.geeksforgeeks.org/find-element-appears-array-every-element-appears-twice 2 | // https://www.geeksforgeeks.org/find-the-element-that-appears-once 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | func getSingleAppeared(elements []int) int { 9 | sum := elements[0] 10 | for i := 1; i < len(elements); i++ { 11 | sum = sum ^ elements[i] 12 | } 13 | return sum 14 | } 15 | 16 | func main() { 17 | fmt.Println("[]string{1,2,1,3,2} :", getSingleAppeared([]int{1, 2, 1, 3, 2})) 18 | fmt.Println("[]string{1,3,1,3,2} :", getSingleAppeared([]int{1, 3, 1, 3, 2})) 19 | } 20 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/other/interfacesExample.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Val struct { 6 | number int 7 | strings string 8 | } 9 | 10 | type MyInterface interface { 11 | PrintValues() 12 | } 13 | 14 | func (v *Val) PrintValues() { 15 | fmt.Printf("number: %d, string: %s\n", v.number, v.strings) 16 | } 17 | 18 | //func SomeFunction(v Val){ 19 | // //do all Val related operations here 20 | // v.PrintValues() 21 | //} 22 | 23 | func newFunc(v MyInterface){ 24 | v.PrintValues() 25 | } 26 | 27 | func main() { 28 | newVal := Val{10, "ten"} 29 | //SomeFunction(newVal) 30 | //you can pass the struct object as an interface, 31 | //writing UT for interface will be simpler 32 | newFunc(&newVal) 33 | 34 | val2 := Val{20, "twenty"} 35 | newFunc(&val2) 36 | } 37 | -------------------------------------------------------------------------------- /GeeksForGeeks/Go/queue/queue.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | type Queue struct { 9 | items []int 10 | lock sync.RWMutex 11 | } 12 | 13 | func (q *Queue) enqueue(item int){ 14 | q.lock.Lock() 15 | q.items = append(q.items,item) 16 | q.lock.Unlock() 17 | } 18 | 19 | func (q *Queue) deque(){ 20 | q.lock.Lock() 21 | q.items = q.items[1:len(q.items)] 22 | q.lock.Unlock() 23 | } 24 | 25 | func main(){ 26 | queueElem := new(Queue) 27 | queueElem.enqueue(1) 28 | queueElem.enqueue(5) 29 | queueElem.enqueue(3) 30 | fmt.Println(queueElem.items) 31 | queueElem.deque() 32 | fmt.Println(queueElem.items) 33 | queueElem.enqueue(4) 34 | fmt.Println(queueElem.items) 35 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Go/stacks/stacks.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | type Stack struct { 9 | items []int 10 | lock sync.RWMutex 11 | } 12 | 13 | func (s *Stack) push(item int){ 14 | s.lock.Lock() 15 | s.items = append(s.items,item) 16 | s.lock.Unlock() 17 | } 18 | 19 | func (s *Stack) pop(){ 20 | s.lock.Lock() 21 | s.items = s.items[0:len(s.items)-1] 22 | s.lock.Unlock() 23 | } 24 | 25 | func main(){ 26 | stackElem := new(Stack) 27 | stackElem.push(1) 28 | stackElem.push(5) 29 | stackElem.push(3) 30 | fmt.Println(stackElem.items) 31 | stackElem.pop() 32 | fmt.Println(stackElem.items) 33 | stackElem.push(4) 34 | fmt.Println(stackElem.items) 35 | } -------------------------------------------------------------------------------- /GeeksForGeeks/Go/strings/wordMatch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func wordMatch(string1, string2 string) []string { 8 | var matchedString []string 9 | str2len := len(string2) 10 | str1len := len(string1) 11 | 12 | for i := 0; i < str1len; i++ { 13 | if string1[i] == string2[0] { 14 | if i+str2len > str1len { 15 | return matchedString 16 | } 17 | for j := 1; j < str2len && string1[i+j] == string2[j]; j++ { 18 | if j == str2len-1 { 19 | //all string2 are matched now, print till next word 20 | temp := string1[i : i+str2len] 21 | i = i + str2len 22 | for ; i < str1len; i++ { 23 | if []byte(" ")[0] == string1[i] || []byte(".")[0] == string1[i] { 24 | break 25 | } 26 | temp = temp + string(string1[i]) 27 | } 28 | matchedString = append(matchedString, temp) 29 | } 30 | } 31 | } 32 | } 33 | return matchedString 34 | } 35 | 36 | func main() { 37 | str1 := "this is the best way to get the best knowledge out there." 38 | str2 := "th" 39 | fmt.Println(wordMatch(str1, str2)) 40 | str2 = "kno" 41 | fmt.Println(wordMatch(str1, str2)) 42 | fmt.Print("Closing the main function") 43 | } 44 | -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__init__.py -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/__pycache__/__init__.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/__init__.cpython-34.pyc -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/__pycache__/arr_insert.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/arr_insert.cpython-34.pyc -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/__pycache__/arr_printer.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/arr_printer.cpython-34.pyc -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/__pycache__/arr_remove.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/arr_remove.cpython-34.pyc -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/__pycache__/arr_search.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/arr_search.cpython-34.pyc -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/arr_init.py: -------------------------------------------------------------------------------- 1 | from Array import arr_insert,arr_printer,arr_remove,arr_search 2 | 3 | #Initialize an array variable 4 | arr = [] 5 | 6 | #Insert an element 7 | print("Insert some elements to the array") 8 | for i in range (15) : 9 | arr_insert.insert_one(arr,(5*i+9)) 10 | arr_printer.print_arr(arr) 11 | 12 | #Remove the last element 13 | print("Remove the last element of an array") 14 | arr_remove.remove_last(arr) 15 | arr_printer.print_arr(arr) 16 | 17 | #1.http://www.geeksforgeeks.org/search-insert-and-delete-in-an-unsorted-array/ 18 | #Remove a key from array 19 | print("Remove a key from an array") 20 | delete_element = 34 21 | arr_remove.remove_key(arr,delete_element) 22 | arr_printer.print_arr(arr) 23 | 24 | #Search an element 25 | print("search for a key in an array") 26 | search_element = 39 27 | if(arr_search.linear_search(arr,search_element)): 28 | print("Found the key %s in the array\n"% search_element) 29 | else: 30 | print("%s: Key not found\n" % search_element) 31 | 32 | 33 | #2.http://www.geeksforgeeks.org/search-insert-and-delete-in-a-sorted-array/ 34 | #insert an element into sorted array 35 | print("Insert an element to a sorted array") 36 | insert_element = 43 37 | arr_insert.sort_insert(arr,insert_element) 38 | arr_printer.print_arr(arr) 39 | 40 | 41 | #serach an element from sorted array 42 | print("[Binary] search an element from a sorted array") 43 | search_element = 54 44 | n = len(arr) - 1 45 | pos = arr_search.binary_search(arr,0,int(n),search_element) 46 | if (pos == -1 ): 47 | print("%s: Key not found\n" % search_element) 48 | else: 49 | print("Found the key %s in the array in position \n"% search_element) 50 | 51 | #delete an element from sorted array 52 | 53 | print("Delete a given key from an array") 54 | delete_element = 59 55 | arr_remove.sort_remove(arr,delete_element) 56 | arr_printer.print_arr(arr) -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/arr_insert.py: -------------------------------------------------------------------------------- 1 | def insert_one(arr , val ): 2 | arr.append(val) 3 | 4 | def sort_insert(arr, val): 5 | #append a calue to the last, which will append the new value 6 | arr.append(val) 7 | for i in range(len(arr)-2,0,-1): 8 | if(arr[i] < val): 9 | break 10 | arr[i+1] = arr[i] 11 | 12 | arr[i+1] = val 13 | -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/arr_printer.py: -------------------------------------------------------------------------------- 1 | def print_arr(arr): 2 | print("Array List is:",end="") 3 | for i in arr: 4 | print (i,end=",") 5 | print("\n") -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/arr_remove.py: -------------------------------------------------------------------------------- 1 | from Array import arr_search 2 | 3 | def remove_last(arr): 4 | try: 5 | elem = arr.pop() 6 | print("Successfully deleted the last element %s"% elem) 7 | except Exception as e: 8 | print("Error deleting the last element of an array") 9 | 10 | def remove_key(arr,key): 11 | try: 12 | arr.remove(key) 13 | print("Successfully deleted the key %s"% key) 14 | except Exception as e: 15 | print("Key %s not found in array to delete"% key) 16 | 17 | def sort_remove(arr,key): 18 | pos = arr_search.binary_search(arr,0,len(arr)-1,key) 19 | if (pos == -1 ): 20 | print("Key %s is not found to delete\n" % key) 21 | else: 22 | for i in range (pos,len(arr)-1): 23 | arr[i]=arr[i+1] -------------------------------------------------------------------------------- /GeeksForGeeks/Python/Array/arr_search.py: -------------------------------------------------------------------------------- 1 | def linear_search(arr,element): 2 | for i in arr: 3 | if(i == element): 4 | return 1 5 | return 0 6 | 7 | def binary_search(arr, low, high, element): 8 | if(high 1]) #set defined here 36 | print("Sets example", duplicates) 37 | 38 | #array 39 | a= [1,"c"] 40 | for i in a: 41 | print("Array ex ", i) 42 | 43 | 44 | 45 | 46 | #dictionary 47 | d = {'x': 1} 48 | for key, value in d.items(): 49 | print("dicttionary example ",key,value) 50 | 51 | 52 | 53 | 54 | #tuples 55 | 56 | t = ('a','b') 57 | print ("tuples ", t) 58 | 59 | 60 | 61 | #list 62 | l = [1,2] 63 | print("list exaample", l) 64 | 65 | 66 | 67 | #list comprehensions 68 | #used to construct lists in a very natural, easy way, like a mathematician is used to do. 69 | x = [x**2 for x in range(0,5)] 70 | print ("list comprehensions ",x,type(x)) 71 | 72 | #prime using list comprehensions 73 | noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] 74 | primes = [x for x in range(2, 50) if x not in noprimes] 75 | print("prime using list comprehensions ",primes) 76 | 77 | 78 | #lambda in map 79 | items = [1, 2, 3, 4, 5] 80 | squared = list(map(lambda x: x**2, items)) 81 | print("lambda in map ",squared) 82 | 83 | #lambda in filter 84 | #creates a list of elements for which a function returns true 85 | number_list = range(-5, 5) 86 | less_than_zero = list(filter(lambda x: x < 0, number_list)) 87 | print("lambda in filter ",less_than_zero) 88 | 89 | 90 | #lambda in reduce 91 | #performing some computation on a list and returning the result 92 | product = reduce((lambda x, y: x * y), [1, 2, 3, 4]) 93 | print("lambda in reduce ",product) 94 | 95 | 96 | #ternary operator 97 | 98 | is_fat = True 99 | state = "fat" if is_fat else "not fat" 100 | print ("Ternary example ", state) 101 | 102 | 103 | 104 | #repr() and str() 105 | #repr() is mainly used for debugging and development 106 | s = 'Hello, Geeks.' 107 | print ("str() ex ", str(s), str(2.0/11.0)) 108 | print ("repr() ex ", repr(s), repr(2.0/11.0)) 109 | 110 | 111 | 112 | #iterator, next, generator, yield 113 | def generator_function(): 114 | for i in range(3): 115 | yield i 116 | 117 | gen = generator_function() 118 | print("generator next(0)",next(gen)) # Output: 0 119 | print("generator next(1)",next(gen)) # Output: 1 120 | 121 | 122 | 123 | 124 | 125 | 126 | # try, catch, exception, finally 127 | 128 | try: 129 | file = open('test.txt', 'rb') 130 | except IOError as e: 131 | print("Except example: An error occurred.") 132 | #raise e 133 | finally: 134 | print("Finally example: This would be printed whether or not an exception occurred!") 135 | 136 | 137 | 138 | #Control statements 139 | 140 | # has pass, continue, break options 141 | 142 | #for loop 143 | for i in range (0,1): 144 | print("for loop ex: ",i) 145 | 146 | 147 | 148 | #while loop 149 | count = 0 150 | while (count < 1): 151 | print ('While loop ex: ', count) 152 | count = count + 1 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | #json encoding and decoding 161 | data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'} 162 | dump_data = json.dumps(data) 163 | print("Dumped json data is ", dump_data) 164 | load_data = json.loads(dump_data) 165 | print("Loaded json data is ", load_data) 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | #classes and multiple inheritance 179 | 180 | """ 181 | class X: pass 182 | class Y: pass 183 | class Z: pass 184 | 185 | class A(X,Y): pass // multiple inheritance 186 | class B(Y,Z): pass 187 | 188 | class M(B,A,Z): pass // multilevel inheritance 189 | 190 | # Output: 191 | # [, , 192 | # , , 193 | # , , 194 | # ] 195 | 196 | print(M.mro()) 197 | 198 | """ 199 | 200 | 201 | 202 | 203 | 204 | 205 | #default dict 206 | 207 | 208 | #multithreading 209 | """ 210 | import thread 211 | def shout(n): 212 | print("Thread here", ('n',)) 213 | 214 | thread.start_new_thread(shout,1) 215 | """ 216 | 217 | -------------------------------------------------------------------------------- /GeeksForGeeks/Python/matrix_spiral.py: -------------------------------------------------------------------------------- 1 | #https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ 2 | 3 | #row_cloumn = input().strip().split(" ") 4 | 5 | #row = int(row_cloumn[0]) 6 | #column = int(row_cloumn[1]) 7 | 8 | #print(row, column) 9 | 10 | def print_one_spiral (matrix, count, size_row, size_col): 11 | print(count,matrix) 12 | #print top row 13 | 14 | 15 | #print right 16 | 17 | #print left 18 | 19 | 20 | def print_spiral (matrix, size_row, size_col): 21 | if size_row % 2 == 1 : 22 | spiral_needed = (size_row/2) +1 23 | else: 24 | spiral_needed = (size_row / 2) 25 | 26 | for i in range(int(spiral_needed)): 27 | print_one_spiral(matrix, i, size_row, size_col) 28 | 29 | matrix = [[1,2,3], 30 | [4,5,6], 31 | [1,2,3], 32 | [4,5,6] 33 | ] 34 | print_spiral(matrix,4,3) 35 | 36 | -------------------------------------------------------------------------------- /Go_Samples/gin_basic_auth_middleware/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | curl request 5 | 6 | curl --request GET \ 7 | --url http://localhost:8085/rest/names \ 8 | --header 'authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' 9 | 10 | */ 11 | import ( 12 | "encoding/base64" 13 | "net/http" 14 | "strings" 15 | 16 | "github.com/gin-gonic/gin" 17 | ) 18 | 19 | func AuthMiddleware() gin.HandlerFunc { 20 | //authenticate the creds here 21 | return func(c *gin.Context) { 22 | 23 | s := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2) 24 | if len(s) != 2 { 25 | c.JSON(http.StatusUnauthorized, "Authorization header is not correct") 26 | c.Abort() 27 | return 28 | } 29 | 30 | b, err := base64.StdEncoding.DecodeString(s[1]) 31 | if err != nil { 32 | c.JSON(http.StatusUnauthorized, "Decode error") 33 | c.Abort() 34 | return 35 | } 36 | 37 | pair := strings.SplitN(string(b), ":", 2) 38 | if len(pair) != 2 { 39 | c.JSON(http.StatusUnauthorized, "Decoded string is not correct") 40 | c.Abort() 41 | return 42 | } 43 | 44 | if pair[0] != "username" || pair[1] != "password" { 45 | c.JSON(http.StatusUnauthorized, "Username/password is not correct") 46 | c.Abort() 47 | return 48 | } 49 | 50 | } 51 | } 52 | 53 | func getNames(c *gin.Context) { 54 | var names []string 55 | 56 | names = []string{"bharath", "kumar"} 57 | c.JSON(http.StatusOK, names) 58 | } 59 | 60 | func main() { 61 | //create a new gin router 62 | router := gin.New() 63 | //create a new router group, this will create localhost:/rest 64 | rest := router.Group("/rest") 65 | //create a new group under /rest group, this will create localhost:/rest/names 66 | names := rest.Group("/names") 67 | //All middlewares must be passed will come under USE 68 | names.Use(AuthMiddleware()) 69 | 70 | names.GET("", getNames) 71 | 72 | //start the server at port 8085 73 | router.Run(":8085") 74 | } 75 | -------------------------------------------------------------------------------- /Go_Samples/mux_basic_auth_middleware/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // mux router to authenticate basic auth [base64 encoded] using middleware 4 | 5 | /* 6 | curl request: 7 | 8 | curl --request GET \ 9 | --url http://localhost:9900/form \ 10 | --header 'authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' 11 | 12 | */ 13 | import ( 14 | "encoding/base64" 15 | "net/http" 16 | "strings" 17 | 18 | "github.com/gorilla/mux" 19 | ) 20 | 21 | func main() { 22 | 23 | r := mux.NewRouter() 24 | r.HandleFunc("/form", use(myHandler, basicAuth)) 25 | http.Handle("/", r) 26 | 27 | http.ListenAndServe(":9900", nil) 28 | } 29 | 30 | // use provides a cleaner interface for chaining middleware for single routes. 31 | // Middleware functions are simple HTTP handlers (w http.ResponseWriter, r *http.Request) 32 | // 33 | // r.HandleFunc("/login", use(loginHandler, rateLimit, csrf)) 34 | // r.HandleFunc("/form", use(formHandler, csrf)) 35 | // r.HandleFunc("/about", aboutHandler) 36 | // 37 | 38 | func use(h http.HandlerFunc, middlewares ...func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc { 39 | for _, middleware := range middlewares { 40 | h = middleware(h) 41 | } 42 | 43 | return h 44 | } 45 | 46 | func myHandler(w http.ResponseWriter, r *http.Request) { 47 | w.Write([]byte("Authenticated!")) 48 | return 49 | } 50 | 51 | // Leverages nemo's answer in http://stackoverflow.com/a/21937924/556573 52 | func basicAuth(h http.HandlerFunc) http.HandlerFunc { 53 | return func(w http.ResponseWriter, r *http.Request) { 54 | 55 | w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) 56 | 57 | s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) 58 | if len(s) != 2 { 59 | http.Error(w, "Not authorized", 401) 60 | return 61 | } 62 | 63 | b, err := base64.StdEncoding.DecodeString(s[1]) 64 | if err != nil { 65 | http.Error(w, err.Error(), 401) 66 | return 67 | } 68 | 69 | pair := strings.SplitN(string(b), ":", 2) 70 | if len(pair) != 2 { 71 | http.Error(w, "Not authorized", 401) 72 | return 73 | } 74 | 75 | if pair[0] != "username" || pair[1] != "password" { 76 | http.Error(w, "Not authorized", 401) 77 | return 78 | } 79 | 80 | h.ServeHTTP(w, r) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Go_Samples/net_http_login_with_body/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // Simple net/http server which checks the body passed by the curl request for authentication 4 | 5 | /* 6 | curl request to check the code, 7 | 8 | curl --request POST \ 9 | --url http://localhost:8085/login \ 10 | --header 'content-type: application/json' \ 11 | --data '{ 12 | "username":"admin", 13 | "password":"pass" 14 | }' 15 | 16 | */ 17 | import ( 18 | "encoding/json" 19 | "fmt" 20 | "io/ioutil" 21 | "log" 22 | "net/http" 23 | ) 24 | 25 | type loginStruct struct { 26 | Username string `json:username` 27 | Password string `json:password` 28 | } 29 | 30 | func LoginCheck(w http.ResponseWriter, r *http.Request) { 31 | userName := "admin" 32 | passWord := "pass" 33 | 34 | var creds loginStruct 35 | credsBody, err := ioutil.ReadAll(r.Body) 36 | if err != nil { 37 | log.Printf("Bad Request: Error while reading") 38 | w.WriteHeader(400) 39 | } 40 | err = json.Unmarshal(credsBody, &creds) 41 | 42 | if err != nil { 43 | log.Printf("Internal Error: Error while unmarshalling") 44 | w.WriteHeader(500) 45 | } 46 | 47 | if creds.Username == "" || creds.Password == "" { 48 | w.WriteHeader(400) 49 | w.Write([]byte("username or password is required")) 50 | } 51 | if creds.Username != userName || creds.Password != passWord { 52 | 53 | w.WriteHeader(401) 54 | } else { 55 | 56 | w.WriteHeader(200) 57 | } 58 | 59 | } 60 | 61 | func main() { 62 | fmt.Printf("Starting the server.. localhost:8085") 63 | 64 | mux := http.NewServeMux() 65 | mux.HandleFunc("/login", LoginCheck) 66 | 67 | log.Fatal(http.ListenAndServe(":8085", mux)) 68 | } 69 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_any.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | keys, vals := getKeys(map[any]any{1: "one", "two": 2}) 7 | fmt.Printf("keys: %v, values: %v", keys, vals) 8 | } 9 | 10 | func getKeys(m map[any]any) ([]any, []any) { 11 | var keys []any 12 | var vals []any 13 | for k, v := range m { 14 | keys = append(keys, k) 15 | vals = append(vals, v) 16 | } 17 | return keys, vals 18 | } 19 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_channel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | // Blogs to read: 9 | // https://www.ardanlabs.com/blog/2018/11/goroutine-leaks-the-forgotten-sender.html 10 | // https://www.dolthub.com/blog/2023-03-13-golang-concurrency-examples/ 11 | 12 | type chanStruct struct { 13 | intVal int 14 | strVal string 15 | } 16 | 17 | func main() { 18 | ch := make(chan chanStruct, 0) // unbuffered channel 19 | go updateChannel(ch) 20 | fmt.Println("Hello from channel:", <-ch) // waits until the data is written as it is unbuffered 21 | 22 | bufferedChannelSameThread() 23 | unbufferedWithDifferentThread() 24 | bufferedWithDifferentThread() 25 | } 26 | 27 | func updateChannel(ch chan chanStruct) { 28 | obj := chanStruct{intVal: 4, strVal: "bks"} 29 | ch <- obj 30 | } 31 | 32 | /* 33 | output: 34 | Hello from channel: {4 bks} 35 | */ 36 | 37 | func bufferedChannelSameThread() { 38 | // create a buffered channel, which can write as many times as needed without worrying about the write. 39 | queue := make(chan string, 2) // this has to be 2 if we are reading and writing in the same thread 40 | queue <- "one" 41 | queue <- "two" 42 | close(queue) // make sure that you close the channel before ranging over it. Otherwise for loop will never break. 43 | 44 | for elem := range queue { 45 | fmt.Println(elem) 46 | } 47 | } 48 | 49 | /* 50 | output: 51 | one 52 | two 53 | */ 54 | 55 | // range for unbuffered channel by using multiple thread 56 | func unbufferedWithDifferentThread() { 57 | done := make(chan string) // you can make this buffered to process faster, as 'range' will wait until the data is written on the channel after a 'read' 58 | go func() { 59 | for _, word := range []string{"foo", "bar", "baz"} { 60 | done <- word 61 | } 62 | close(done) 63 | //done <- "dd" NOT VALID. after closing the channel, you cannot send anything. 64 | }() 65 | for word := range done { 66 | fmt.Println(word) 67 | } 68 | fmt.Println("read after closing the channel:", <-done) // read after closing the channel. VALID. 69 | } 70 | 71 | /* 72 | output: 73 | foo 74 | bar 75 | baz 76 | read after closing the channel: 77 | */ 78 | 79 | func bufferedWithDifferentThread() { 80 | ch := make(chan int, 1) // we can write multiple times if the channel is used in different thread even with the less size 81 | for i := 0; i < 4; i++ { 82 | go updateBufferedChannel(i, ch) 83 | } 84 | 85 | for i := 0; i < 2; i++ { 86 | time.Sleep(time.Second) 87 | recvdVal := <-ch 88 | fmt.Println("Reading data", recvdVal) 89 | } 90 | close(ch) 91 | } 92 | 93 | func updateBufferedChannel(val int, ch chan int) { 94 | fmt.Println("writing data", val) 95 | ch <- val 96 | } 97 | 98 | /* 99 | output: 100 | writing data 3 101 | writing data 2 102 | writing data 1 103 | writing data 0 104 | Reading data 3 105 | Reading data 2 106 | */ 107 | 108 | 109 | // code for not panic'ing inside the go routine 110 | 111 | type caughtPanicError struct { 112 | val any 113 | stack []byte 114 | } 115 | 116 | func (e *caughtPanicError) Error() string { 117 | return fmt.Sprintf( 118 | "panic: %q\n%s", 119 | e.val, 120 | string(e.stack) 121 | ) 122 | } 123 | 124 | func main() { 125 | done := make(chan error) 126 | go func() { 127 | defer func() { 128 | if v := recover(); v != nil { 129 | done <- caughtPanicError{ 130 | val: v, 131 | stack: debug.Stack() 132 | } 133 | } else { 134 | done <- nil 135 | } 136 | }() 137 | doSomethingThatMightPanic() 138 | }() 139 | err := <-done 140 | if err != nil { 141 | panic(err) 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_defer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | func deferExample() (err error) { 9 | defer fmt.Println("err1:", err) // nil , err will not get overwritten 10 | err = errors.New("new err") 11 | defer func() { 12 | fmt.Println("err2:", err) // err2: new global err, will get overwritten 13 | }() 14 | defer func(err error) { 15 | err = errors.New("local err") 16 | fmt.Println("err3:", err) // err3: local err 17 | }(err) 18 | err = errors.New("new global err") 19 | return 20 | } 21 | 22 | func main() { 23 | fmt.Println("Hello", deferExample()) // prints 'Hello new global err' 24 | } 25 | 26 | /* 27 | output: 28 | err3: local err 29 | err2: new global err 30 | err1: 31 | Hello new global err 32 | */ 33 | 34 | // only the defer body will get run as part of defer. This doesnot work if we are passing a variable though as updating varaible updates 35 | // value inside defer aswell. 36 | func main() { 37 | defer func(tt time.Time) { 38 | fmt.Println("Hello defer", tt) // Hello 2023-03-22 15:22:56.278517 +0100 CET m=+0.000082018 39 | }(time.Now()) 40 | fmt.Println("Hello", time.Now()) // Hello 2023-03-22 15:22:56.278517 +0100 CET m=+0.000082118 41 | time.Sleep(1 * time.Second) 42 | fmt.Println("Hello", time.Now()) // Hello 2023-03-22 15:22:57.279791 +0100 CET m=+1.001350562 43 | } 44 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_filereader_using_buffer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "log" 8 | "os" 9 | ) 10 | 11 | func main() { 12 | f, err := os.Open("/Users/bharkum3/tmp/sam.config") 13 | if err != nil { 14 | log.Fatal(err) 15 | } 16 | defer f.Close() 17 | r := bufio.NewReader(f) 18 | b := make([]byte, 3) 19 | for { 20 | n, err := r.Read(b) 21 | if err != nil { 22 | if err != io.EOF { 23 | fmt.Println("Error reading file:", err) 24 | } 25 | break 26 | } 27 | fmt.Print(string(b[0:n])) 28 | } 29 | } 30 | 31 | func stdinReader() { 32 | reader := bufio.NewReader(os.Stdin) 33 | fmt.Println("Simple Shell") 34 | fmt.Println("---------------------") 35 | 36 | for { 37 | fmt.Print("-> ") 38 | text, _ := reader.ReadString('\n') 39 | // convert CRLF to LF 40 | text = strings.Replace(text, "\n", "", -1) 41 | 42 | if strings.Compare("hi", text) == 0 { 43 | fmt.Println("hello, Yourself") 44 | } 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_generics.go: -------------------------------------------------------------------------------- 1 | 2 | import "fmt" 3 | 4 | type allInterface interface { 5 | int | float64 | string 6 | } 7 | 8 | func main() { 9 | n, m, p := 2, 4.5, "stringToo" 10 | fmt.Println(printAll(n), printAll(m), printAll(p)) 11 | } 12 | 13 | func printAll[V allInterface](allVar V) V { 14 | return allVar 15 | } 16 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_http.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "bytes" 6 | "io/ioutil" 7 | "net/http" 8 | ) 9 | 10 | func main() { 11 | url := "http://restapi3.apiary-mock.com/notes" 12 | fmt.Println("URL:>", url) 13 | 14 | var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`) 15 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) 16 | req.Header.Set("X-Custom-Header", "myvalue") 17 | req.Header.Set("Content-Type", "application/json") 18 | 19 | client := &http.Client{} 20 | resp, err := client.Do(req) 21 | if err != nil { 22 | panic(err) 23 | } 24 | defer resp.Body.Close() 25 | 26 | fmt.Println("response Status:", resp.Status) 27 | fmt.Println("response Headers:", resp.Header) 28 | body, _ := ioutil.ReadAll(resp.Body) 29 | fmt.Println("response Body:", string(body)) 30 | } 31 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_interface.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | // SafeCounter is safe to use concurrently. 10 | type SafeCounter struct { 11 | v map[string]int 12 | mux sync.Mutex 13 | } 14 | 15 | // Inc increments the counter for the given key. 16 | func (c *SafeCounter) Inc(key string) { 17 | c.mux.Lock() 18 | // Lock so only one goroutine at a time can access the map c.v. 19 | c.v[key]++ 20 | c.mux.Unlock() 21 | } 22 | 23 | // Value returns the current value of the counter for the given key. 24 | func (c *SafeCounter) Value(key string) int { 25 | c.mux.Lock() 26 | // Lock so only one goroutine at a time can access the map c.v. 27 | defer c.mux.Unlock() 28 | return c.v[key] 29 | } 30 | 31 | func main() { 32 | //c := new(SafeCounter) // does not work, map will give nil pointer 33 | c := &SafeCounter{v: make(map[string]int)} // SafeCounter{v: make(map[string]int)} works too 34 | for i := 0; i < 1000; i++ { 35 | go c.Inc("somekey") 36 | } 37 | 38 | time.Sleep(time.Second) 39 | fmt.Println(c.Value("somekey")) 40 | } 41 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_pointer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | a := 2 7 | b := &a 8 | fmt.Println(a) // 2 9 | fmt.Println(*b) // 2 10 | 11 | *b = 3 12 | fmt.Println(a) // 3 13 | fmt.Println(*b) // 3 14 | 15 | a = 4 16 | fmt.Println(a) // 4 17 | fmt.Println(*b) // 4 18 | } 19 | 20 | /* 21 | Both a and *b refer to the same variable internally. Hence the changing the value of one reflects in another. 22 | Also, * and & can be used together as well. But they will cancel out each other. 23 | Hence these are all equivalent, 24 | a 25 | *&a 26 | b 27 | *&b 28 | &*b 29 | 30 | Note: *a is not a valid operation as a is not a pointer 31 | 32 | */ 33 | 34 | // pass the pointer and use the pointer 35 | func incrInt(d *int) { 36 | *d++ 37 | } 38 | 39 | func inorder(node *TreeNode, list * []int) { 40 | if node == nil { 41 | return 42 | } 43 | *list = append(*list,node.Val) 44 | } 45 | 46 | func more_examples() { 47 | c := new(Person) // returns pointer 48 | c.Name = "Catherine" 49 | fmt.Println(c.Name) // prints: Catherine 50 | d := c 51 | d.Name = "Daniel" 52 | fmt.Println(c.Name) // prints: Daniel 53 | // Adding an Asterix before a pointer dereferences the pointer. This does not work for data type variable such as 'a' above 54 | i := *d 55 | i.Name = "Ines" 56 | fmt.Println(c.Name) // prints: Daniel 57 | fmt.Println(d.Name) // prints: Daniel 58 | fmt.Println(i.Name) // prints: Ines 59 | } 60 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_select.go: -------------------------------------------------------------------------------- 1 | // Go program to illustrate the 2 | // concept of select statement 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "sync" 8 | "time" 9 | ) 10 | 11 | func portal1(channel1 chan string, wg *sync.WaitGroup) { 12 | channel1 <- "Welcome to channel 1" 13 | wg.Done() 14 | } 15 | 16 | func portal2(channel2 chan string, wg *sync.WaitGroup) { 17 | channel2 <- "Welcome to channel 2" 18 | wg.Done() 19 | } 20 | 21 | // main function 22 | func main() { 23 | var wg sync.WaitGroup 24 | wg.Add(2) 25 | // Creating channels 26 | // NOTE: make it buffered channel, so that when we cant read this channel, it will not end up leaking go routine 27 | R1 := make(chan string, 1) 28 | R2 := make(chan string, 1) 29 | 30 | // calling function 1 and 31 | // function 2 in goroutine 32 | go portal1(R1, &wg) 33 | go portal2(R2, &wg) 34 | 35 | // Go’s select lets you wait on multiple channel operations. 36 | // can have 'default:' case or timer inside. 37 | // NOTE: If a select statement has non-blocking case like default or timer, it can choose any one of those and here 38 | // in this case we may never hit the timer at all 39 | 40 | select { 41 | // case 1 for portal 1 42 | case op1 := <-R1: 43 | fmt.Println(op1) 44 | 45 | // case 2 for portal 2 46 | case op2 := <-R2: 47 | fmt.Println(op2) 48 | 49 | case <-time.After(time.Second): 50 | fmt.Printf("\nTimeout\n") 51 | } 52 | wg.Wait() 53 | // make sure that both are closed 54 | close(R1) 55 | close(R2) 56 | } 57 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_slices.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /* 6 | Everything in Go is passed by value, slices too. But a slice value is a header, 7 | describing a contiguous section of a backing array, and a slice value only contains 8 | a pointer to the array where the elements are actually stored. The slice value does 9 | not include its elements (unlike arrays). 10 | 11 | So when you pass a slice to a function, a copy will be made from this header, including 12 | the pointer, which will point to the same backing array. Modifying the elements of the 13 | slice implies modifying the elements of the backing array, and so all slices which share 14 | the same backing array will "observe" the change. 15 | 16 | type SliceHeader struct { 17 | Data uintptr 18 | Len int 19 | Cap int 20 | } 21 | 22 | */ 23 | 24 | /* 25 | The contents of a slice argument can be modified by a function, but its header cannot. 26 | The length stored in the slice variable is not modified by the call to the function, 27 | since the function is passed a copy of the slice header, not the original. Thus if we want 28 | to write a function that modifies the header, we must return it as a result parameter, just as we have done here. 29 | */ 30 | 31 | func updateSlice(mySlice []string) { 32 | mySlice[0] = "oneupdated" 33 | mySlice = append(mySlice, "three") // append did not work 34 | // mySlice[3] = "oneupdated" //index out of range panic 35 | myLocalSlice := mySlice 36 | myLocalSlice[1] = "twoupdated" // will not update the original slice, works with ptr 37 | } 38 | 39 | func updateSliceWithPtr(mySlice *[]string) { 40 | (*mySlice)[0] = "oneptr" 41 | (*mySlice) = append((*mySlice), "threePtr") // append worked 42 | } 43 | 44 | func main() { 45 | var mySlice = []string{"one", "two"} 46 | fmt.Println(mySlice) //[one two] 47 | updateSlice(mySlice) 48 | fmt.Println(mySlice) // [oneupdated two] 49 | updateSliceWithPtr(&mySlice) 50 | fmt.Println(mySlice) // [oneptr two threePtr] 51 | myMainLocalSlice := mySlice 52 | myMainLocalSlice[1] = "twoupdated" // will update the original slice value too 53 | fmt.Println(mySlice) // [oneptr twoupdated threePtr] 54 | } 55 | 56 | /* 57 | op: 58 | 59 | [one two] 60 | [oneupdated two] 61 | [oneptr two threePtr] 62 | [oneptr twoupdated threePtr] 63 | 64 | */ 65 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_string_concat.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strings" 5 | "fmt" 6 | ) 7 | 8 | func stringsBuilder() { 9 | // ZERO-VALUE: 10 | // 11 | // It's ready to use from the get-go. 12 | // You don't need to initialize it. 13 | var sb strings.Builder 14 | for i := 0; i < 1000; i++ { 15 | sb.WriteString("a") 16 | } 17 | fmt.Println(sb.String()) 18 | } 19 | 20 | func bytesBuffer(b *testing.B) { 21 | var buffer bytes.Buffer 22 | for n := 0; n < 1000; n++ { 23 | buffer.WriteString("x") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_unmarshal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | //unmarshal into interface without defining the struct 10 | birdJson := `{"birds":{"pigeon":"likes to perch","eagle":"bird of prey"},"animals":"none"}` 11 | var result map[string]interface{} 12 | json.Unmarshal([]byte(birdJson), &result) 13 | birds := result["birds"].(map[string]interface{}) 14 | for key, value := range birds { 15 | fmt.Println(key, value.(string)) 16 | } 17 | unmarsahlEx() 18 | } 19 | 20 | type Bird struct { 21 | Species string `json:"birdType"` 22 | Description string `json:"what it does"` 23 | } 24 | 25 | // unmarshal with the struct 26 | func unmarsahlEx() { 27 | birdJson := `{"birdType": "pigeon","what it does": "likes to perch on rocks"}` 28 | var bird Bird 29 | json.Unmarshal([]byte(birdJson), &bird) 30 | fmt.Printf("%+v\n", bird) 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Go_Samples/samples/simple_wg_routines.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | // good read: https://about.sourcegraph.com/blog/building-conc-better-structured-concurrency-for-go 8 | func runner1(wg *sync.WaitGroup) { 9 | defer wg.Done() // This decreases counter by 1 10 | fmt.Print("\nI am first runner") 11 | 12 | } 13 | 14 | func runner2(wg *sync.WaitGroup) { 15 | defer wg.Done() 16 | fmt.Print("\nI am second runner") 17 | } 18 | 19 | func main() { 20 | var wg sync.WaitGroup 21 | wg.Add(2) 22 | go runner1(&wg) 23 | go runner2(&wg) 24 | wg.Wait() 25 | } 26 | -------------------------------------------------------------------------------- /HackerEarth/Akash and the Assignment.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int m,n,i; 7 | int f,s,d; 8 | cin>>m; 9 | cin>>n; 10 | char a[100000]; 11 | for(i=0;i>a[i]; 14 | } 15 | 16 | for(i=0;i>f; 18 | cin>>s; 19 | cin>>d; 20 | int num=f-2+d; 21 | cout< 2 | 3 | int main() 4 | { 5 | unsigned int count,i,a,b,c,n,j; 6 | scanf("%d",&n); 7 | for(j=0;jb) 23 | break; 24 | count++; 25 | } 26 | printf("%u\n",count); 27 | } 28 | } -------------------------------------------------------------------------------- /HackerEarth/KGBD.py: -------------------------------------------------------------------------------- 1 | def kc_gcd(a, b): 2 | n1 = a 3 | n2 = b 4 | while (a > 0 and b > 0): 5 | a = a - b 6 | a, b = b, a 7 | while (n1 != n2): 8 | if (n1 > n2): 9 | n1 = n1 - n2 10 | else: 11 | n2 = n2 - n1 12 | return (n1 == a + b) 13 | 14 | 15 | n = int(input().strip()) 16 | while (n >= 1): 17 | count = 0 18 | data = int(input().strip()) 19 | for i in range(1, data + 1): 20 | for j in range(1, data + 1): 21 | if (kc_gcd(i, j)): 22 | count = count + 1 23 | n = n - 1 24 | print(count) 25 | -------------------------------------------------------------------------------- /HackerEarth/Mind Palaces.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int m,n,i,j; 7 | cin>>m; 8 | cin>>n; 9 | int mat[m][n]; 10 | for(i=0;i>mat[i][j]; 13 | } 14 | } 15 | 16 | int cas; 17 | cin>>cas; 18 | int k; 19 | for(k=0;k>ser; 23 | int flag=0; 24 | for(i=0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n,row,col; 7 | cin>>n; 8 | int i,j,k; 9 | int a[1000][1000]; 10 | 11 | for(int i=0;i>row; 13 | 14 | int sum=0; 15 | //input to array 16 | for(j=0;j<=row-1;j++){ 17 | for(k=0;k<=row-1;k++) 18 | { 19 | 20 | a[j][k]=abs(j-k); 21 | 22 | } 23 | } 24 | for(j=0;j 2 | 3 | int main() 4 | { 5 | long int m,n,dif; 6 | long int f,junk,s,i; 7 | scanf("%d",&m); 8 | scanf("%d",&n); 9 | scanf("%d%d",&f,&s); 10 | dif=s-f+1; 11 | for(i=0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | double n; 7 | double i=0; 8 | cin>>n; 9 | static double num1=0,num2=0; 10 | for(i=0;i>input; 13 | double j=0; 14 | double rowcount=0,count=0; 15 | while(input[j]!='\0'){ 16 | 17 | if(input[j]=='C'){ 18 | count=count+1; 19 | 20 | rowcount=rowcount+1; 21 | if(count>num1) num1=count; 22 | if(rowcount>num2) num2=rowcount; 23 | } 24 | else rowcount=0; 25 | j++; 26 | } 27 | } 28 | cout<= 10): 18 | newcount = newcount + 1 19 | 20 | print(newcount) 21 | -------------------------------------------------------------------------------- /HackerEarth/Will you be my Friend.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | 4 | 5 | class TestClass { 6 | public static void main(String args[] ) throws Exception { 7 | 8 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 | String basef = br.readLine(); 10 | int base1 = Integer.parseInt(basef); 11 | int totalf=0; 12 | int base2; 13 | String line = br.readLine(); 14 | int N = Integer.parseInt(line); 15 | //String bases = br.readLine(); 16 | String []bases=br.readLine().split(" "); 17 | for(int i=0;i= 0 and next % 10 == 0): 9 | count = count + 1 10 | next = next / 10 11 | print 12 | count 13 | -------------------------------------------------------------------------------- /HackerEarth/algorithms/PalindromeCount.go: -------------------------------------------------------------------------------- 1 | //https://www.hackerearth.com/practice/algorithms/dynamic-programming/2-dimensional/practice-problems/algorithm/palindrome-count-1/ 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func isPal(str string) bool { 9 | n := len(str) 10 | for i := 0; i < n/2; i++ { 11 | if string(str[i]) != string(str[n-1-i]){ 12 | return false 13 | } 14 | } 15 | return true 16 | } 17 | 18 | func countPalindromes(str string, n int) int { 19 | count := 0 20 | for i := 0; i < n-1; i++ { 21 | for j := i + 1; j < n; j++ { 22 | if string(str[i]) == string(str[j]) { 23 | if isPal(str[i : j+1]) { 24 | count++ 25 | } 26 | } 27 | } 28 | } 29 | return count 30 | } 31 | func main() { 32 | s := "dskjkd" 33 | n := len(s) 34 | c := countPalindromes(s, n) 35 | fmt.Print(n + c) 36 | } 37 | -------------------------------------------------------------------------------- /HackerEarth/algorithms/possibleSums.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func getPossSums(nums []int) int { 8 | count := 0 9 | uniqueNums := make(map[int]bool) 10 | uniqueNums[0] = true 11 | n := len(nums) 12 | for i := 0; i < n; i++ { 13 | if uniqueNums[nums[i]] == false { 14 | uniqueNums[nums[i]] = true 15 | count++ 16 | } 17 | for j := i + 1; j < n; j++ { 18 | if uniqueNums[nums[i]+nums[j]] == false { 19 | uniqueNums[nums[i]+nums[j]] = true 20 | count++ 21 | } 22 | } 23 | } 24 | 25 | fmt.Println(uniqueNums) 26 | return count + 1 27 | } 28 | 29 | func main() { 30 | nums := []int{1, 2, 3} 31 | sums := getPossSums(nums) 32 | fmt.Println(sums) 33 | } 34 | -------------------------------------------------------------------------------- /HackerEarth/algorithms/xorry.go: -------------------------------------------------------------------------------- 1 | //https://www.hackerearth.com/problem/algorithm/xorray 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | //donot call this function everytime, calculate at once for the maximum and use it every time 9 | func getXOR(digit int) int { 10 | var xor = make([]int,digit+1) 11 | xor[1] = 1 12 | 13 | for i := 2; i <= digit; i++ { 14 | var val = 1 15 | for j:= 2;j= 0; i-- { 13 | count = count + int(countString[i]-48)*dec 14 | dec = dec * 10 15 | } 16 | return count 17 | } 18 | 19 | func expandString(compStr string) map[string]int { 20 | var charCount = make(map[string]int) 21 | lastIdx := 0 22 | lastChar := string(compStr[0]) 23 | for i := 1; i < len(compStr); i++ { 24 | cnt := 0 25 | if string(compStr[i]) >= "a" && string(compStr[i]) <= "z" { 26 | cnt = getCharCount(compStr[lastIdx+1 : i]) 27 | charCount[lastChar] = charCount[lastChar] + cnt 28 | 29 | lastChar = string(compStr[i]) 30 | lastIdx = i 31 | } 32 | if i == len(compStr)-1 { 33 | cnt = getCharCount(compStr[lastIdx+1:]) 34 | charCount[lastChar] = charCount[lastChar] + cnt 35 | 36 | } 37 | } 38 | return charCount 39 | } 40 | 41 | func getChar(charCount [27]int, index []int) { 42 | tmpA := int('a') 43 | for _, idx := range index { 44 | //fmt.Printf("%d:",idx) 45 | flag := false 46 | for i := 1; i <= 26; i++ { 47 | if idx <= 0 { 48 | fmt.Println(string(tmpA + i - 2)) 49 | flag = true 50 | break 51 | } 52 | idx = idx - charCount[i] 53 | } 54 | if !flag { 55 | if idx <= 0 { 56 | fmt.Println("z") 57 | } else { 58 | fmt.Println("-1") 59 | } 60 | } 61 | } 62 | } 63 | 64 | func main() { 65 | charCount := expandString("a1b5n7b3a8z3") 66 | var charIdx [27]int 67 | for i := 1; i <= 26; i++ { 68 | tmp := int('a') 69 | charIdx[i] = charCount[string(tmp+i-1)] 70 | } 71 | 72 | //fmt.Printf("a count is: %v\n", charCount) 73 | indexes := []int{2, 3, 4, 40, 800, 21} 74 | getChar(charIdx, indexes) 75 | } 76 | -------------------------------------------------------------------------------- /HackerRank/30_days_of_code/10_binary_numbers.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | import sys 4 | 5 | 6 | n = int(raw_input().strip()) 7 | count=0 8 | max=0 9 | while(n>0): 10 | digit=n%2 11 | if(digit==1): 12 | count = count + 1 13 | if(count > max): 14 | max=count 15 | else: 16 | count=0 17 | n=n/2 18 | 19 | print max 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /HackerRank/30_days_of_code/11_2d_arrays.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | import sys 4 | 5 | 6 | arr = [] 7 | for arr_i in xrange(6): 8 | arr_temp = map(int,raw_input().strip().split(' ')) 9 | arr.append(arr_temp) 10 | maxn=-60 11 | for i in range(0,4): 12 | for j in range(0,4): 13 | inp= (arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]) 14 | if (inp >= maxn): 15 | maxn=inp 16 | 17 | print maxn 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /HackerRank/30_days_of_code/12_inheritance.py: -------------------------------------------------------------------------------- 1 | class Student(Person): 2 | def __init__(self, firstName, lastName, idNumber, scores): 3 | self.firstName = firstName 4 | self.lastName = lastName 5 | self.idNumber = idNumber 6 | self.scores=scores 7 | def calculate(self): 8 | sum = 0 9 | count = 0 10 | for i in scores: 11 | sum =sum +i 12 | count = count +1 13 | avg=sum/count 14 | if(avg<40): 15 | return 'T' 16 | elif(avg<55): 17 | return 'D' 18 | elif(avg<70): 19 | return 'P' 20 | elif(avg<80): 21 | return 'A' 22 | elif(avg<90): 23 | return 'E' 24 | return 'O' 25 | -------------------------------------------------------------------------------- /HackerRank/30_days_of_code/15_linked_list.py: -------------------------------------------------------------------------------- 1 | def insert(self,head,data): 2 | temp = Node(data) 3 | temp.next=None 4 | current = head 5 | if(head==None): 6 | current=temp 7 | else: 8 | while(head.next!=None): 9 | head=head.next 10 | head.next=temp 11 | return current 12 | 13 | -------------------------------------------------------------------------------- /HackerRank/30_days_of_code/18_queues_and_stacks.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # Write your code here 3 | stackstring = [] 4 | queuestring = [] 5 | def pushCharacter(self,ch): 6 | self.stackstring.extend(ch) 7 | 8 | def enqueueCharacter(self,ch): 9 | self.queuestring.extend(ch) 10 | 11 | def popCharacter(self): 12 | char = self.stackstring.pop() 13 | return char 14 | def dequeueCharacter(self): 15 | char = self.queuestring.pop(0) 16 | return char 17 | -------------------------------------------------------------------------------- /HackerRank/30_days_of_code/20_sorting.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | import sys 4 | 5 | def passhere(a): 6 | alen=len(a) 7 | count=0 8 | for i in range(alen): 9 | for j in range(alen-1): 10 | if(a[j]>a[j+1]): 11 | count = count + 1 12 | temp=a[j] 13 | a[j]=a[j+1] 14 | a[j+1]=temp 15 | print "Array is sorted in",count, "swaps." 16 | print "First Element:", a[0] 17 | print "Last Element:", a[len(a)-1] 18 | 19 | n = int(raw_input().strip()) 20 | a = map(int,raw_input().strip().split(' ')) 21 | passhere(a) 22 | -------------------------------------------------------------------------------- /HackerRank/30_days_of_code/29_bitwise_and.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | t = int(input().strip()) 7 | for a0 in range(t): 8 | maxnum=0 9 | n,k = input().strip().split(' ') 10 | n,k = [int(n),int(k)] 11 | print(k-1 if ((k-1) | k) <= n else k-2) 12 | 13 | 14 | -------------------------------------------------------------------------------- /HackerRank/30_days_of_code/9_recursion.py: -------------------------------------------------------------------------------- 1 | # Enter your code here. Read input from STDIN. Print output to STDOUT 2 | 3 | def factorial(n): 4 | if(n<=1): 5 | return 1 6 | else: 7 | num=n*factorial(n-1) 8 | return num 9 | 10 | n=int(raw_input()) 11 | factn=factorial(n) 12 | print factn 13 | 14 | -------------------------------------------------------------------------------- /HackerRank/DataStructure/Array/2D_Array.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | //code link: https://www.hackerrank.com/challenges/2d-array 4 | func main() { 5 | arr := [6][6]int{} 6 | var maxval int 7 | for i:=0;i<6;i++{ 8 | for j:=0;j<6;j++{ 9 | fmt.Scanf("%d",&arr[i][j]) 10 | } 11 | } 12 | maxval = -10000 13 | for i:=0;i<4;i++{ 14 | for j:=0;j<4;j++{ 15 | total := (arr[i][j])+(arr[i][j+1])+(arr[i][j+2])+(arr[i+1][j+1])+(arr[i+2][j])+(arr[i+2][j+1])+(arr[i+2][j+2]) 16 | if (total > maxval){ 17 | maxval = total 18 | } 19 | } 20 | } 21 | fmt.Println(maxval) 22 | } 23 | -------------------------------------------------------------------------------- /HackerRank/DataStructure/Array/Arrays_DS.go: -------------------------------------------------------------------------------- 1 | package main 2 | //code link: https://www.hackerrank.com/challenges/arrays-ds 3 | import ( 4 | "fmt" 5 | ) 6 | func main() { 7 | //Enter your code here. Read input from STDIN. Print output to STDOUT 8 | var size int 9 | fmt.Scanf("%d", &size) 10 | vals := make([]string,size) 11 | for j:= 0 ; j= k { 18 | sum := int32(0) 19 | for i := flwLen - 1; i >= flwLen-k; i-- { 20 | sum = sum + c[i] 21 | } 22 | cost = cost + (iterNum+1)*sum 23 | } 24 | iterNum++ 25 | flwLen = flwLen - k 26 | if flwLen < k { 27 | break 28 | } 29 | } 30 | for i := flwLen - 1; i >= 0; i-- { 31 | cost = cost + (iterNum+1)*c[i] 32 | } 33 | 34 | return cost 35 | } 36 | 37 | func main() { 38 | k := int32(2) 39 | c := []int32{2, 5, 6} 40 | res := getMinimumCost(k, c) 41 | fmt.Println(res) 42 | } 43 | -------------------------------------------------------------------------------- /HackerRank/interview-preparation-kit/arrays/minimum-swap-2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //not working 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func minimumSwaps(arr []int32) int32 { 9 | fmt.Println(arr) 10 | if len(arr) <= 1 { 11 | return 0 12 | } 13 | var swap int32 14 | 15 | for i:=0;i arr[i+1] { 17 | for j:=i+1;j 3 { 39 | res = 2 * (count - 3) 40 | } 41 | return res 42 | } 43 | 44 | func main() { 45 | nums := []int64{1, 2, 2, 4} 46 | r := int64(2) 47 | res := countTriplets(nums, r) 48 | fmt.Println(res) 49 | } 50 | -------------------------------------------------------------------------------- /HackerRank/interview-preparation-kit/dictAndmaps/sherlock-and-anagrams.go: -------------------------------------------------------------------------------- 1 | //https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=dictionaries-hashmaps 2 | 3 | //not working 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | ) 9 | 10 | // Complete the sherlockAndAnagrams function below. 11 | func sherlockAndAnagrams(s string) int32 { 12 | var ana int32 13 | var count int 14 | strMap := make(map[string]int) 15 | 16 | for i := range s { 17 | strMap[string(s[i])] = strMap[string(s[i])] + 1 18 | if strMap[string(s[i])] == 2 { 19 | strMap[string(s[i])] = 0 20 | count++ 21 | } 22 | } 23 | 24 | return ana 25 | } 26 | 27 | func main() { 28 | 29 | s := "abba" 30 | result := sherlockAndAnagrams(s) 31 | 32 | fmt.Printf("%d\n", result) 33 | 34 | } 35 | -------------------------------------------------------------------------------- /HackerRank/interview-preparation-kit/linkedLists/reverseDoublyLL.go: -------------------------------------------------------------------------------- 1 | //https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=linked-lists 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | type DoublyLinkedListNode struct { 9 | data int32 10 | next *DoublyLinkedListNode 11 | prev *DoublyLinkedListNode 12 | } 13 | 14 | type DoublyLinkedList struct { 15 | head *DoublyLinkedListNode 16 | tail *DoublyLinkedListNode 17 | } 18 | 19 | func (doublyLinkedList *DoublyLinkedList) insertNodeIntoDoublyLinkedList(nodeData int32) { 20 | node := &DoublyLinkedListNode{ 21 | next: nil, 22 | prev: nil, 23 | data: nodeData, 24 | } 25 | 26 | if doublyLinkedList.head == nil { 27 | doublyLinkedList.head = node 28 | } else { 29 | doublyLinkedList.tail.next = node 30 | node.prev = doublyLinkedList.tail 31 | } 32 | 33 | doublyLinkedList.tail = node 34 | } 35 | 36 | func printLinkedList(head *DoublyLinkedListNode) { 37 | node := head 38 | for { 39 | if node == nil { 40 | fmt.Println() 41 | return 42 | } 43 | fmt.Printf("%d->", node.data) 44 | node = node.next 45 | } 46 | } 47 | 48 | // Complete the reverse function below. 49 | 50 | /* 51 | * For your reference: 52 | * 53 | * DoublyLinkedListNode { 54 | * data int32 55 | * next *DoublyLinkedListNode 56 | * prev *DoublyLinkedListNode 57 | * } 58 | * 59 | */ 60 | func reverse(head *DoublyLinkedListNode) *DoublyLinkedListNode { 61 | var next *DoublyLinkedListNode 62 | cur := head 63 | for { 64 | if cur == nil { 65 | return cur 66 | } 67 | next = cur.next 68 | 69 | cur.next = cur.prev 70 | cur.prev = next 71 | 72 | if next == nil { 73 | return cur 74 | } 75 | cur = next 76 | } 77 | 78 | return cur 79 | } 80 | 81 | func main() { 82 | llist := DoublyLinkedList{} 83 | llist.insertNodeIntoDoublyLinkedList(1) 84 | llist.insertNodeIntoDoublyLinkedList(4) 85 | llist.insertNodeIntoDoublyLinkedList(5) 86 | printLinkedList(llist.head) 87 | llist1 := reverse(llist.head) 88 | printLinkedList(llist1) 89 | } 90 | -------------------------------------------------------------------------------- /HackerRank/interview-preparation-kit/stack/balancedBrackets.go: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/balanced-brackets/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=stacks-queues 2 | // 3/18 is failing 3 | package main 4 | 5 | import "fmt" 6 | 7 | type Stack []string 8 | 9 | func (s Stack) ISEmpty() bool { return len(s) == 0 } 10 | 11 | func (s *Stack) Push(v string) { 12 | (*s) = append((*s), v) 13 | } 14 | 15 | func (s *Stack) Pop() string { 16 | v := (*s)[len(*s)-1] 17 | (*s) = (*s)[:len(*s)-1] 18 | return v 19 | } 20 | 21 | // Complete the isBalanced function below. 22 | func isBalanced(s string) string { 23 | stack := Stack{} 24 | for _,val := range (s){ 25 | v := string(val) 26 | switch v { 27 | case "(","{","[": 28 | stack.Push(v) 29 | case "}": 30 | if stack.ISEmpty() { return "NO"} 31 | poppedVal := stack.Pop() 32 | if poppedVal != "{" { 33 | return "NO" 34 | } 35 | case "]": 36 | if stack.ISEmpty() { return "NO"} 37 | poppedVal := stack.Pop() 38 | if poppedVal != "[" { 39 | return "NO" 40 | } 41 | case ")": 42 | if stack.ISEmpty() { return "NO"} 43 | poppedVal := stack.Pop() 44 | if poppedVal != "(" { 45 | return "NO" 46 | } 47 | } 48 | } 49 | return "YES" 50 | } 51 | 52 | func main() { 53 | s := "}][}}(}][))]" 54 | fmt.Println(isBalanced(s)) 55 | } 56 | -------------------------------------------------------------------------------- /HackerRank/interview-preparation-kit/stack/stack.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type StackOld []int 8 | 9 | func (s StackOld) ISEmpty() bool { return len(s) == 0 } 10 | 11 | func (s *StackOld) Push(v int) { 12 | (*s) = append((*s), v) 13 | } 14 | 15 | func (s *StackOld) Pop() int { 16 | v := (*s)[len(*s)-1] 17 | (*s) = (*s)[:len(*s)-1] 18 | return v 19 | } 20 | 21 | func main() { 22 | s := StackOld{} 23 | fmt.Println(s.ISEmpty()) 24 | s.Push(4) 25 | s.Push(5) 26 | s.Push(6) 27 | fmt.Println("Before Stack", s) 28 | s.Pop() 29 | fmt.Println("After Stack", s) 30 | } 31 | -------------------------------------------------------------------------------- /HackerRank/other_programs/HandShake.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | unsigned int a,b,i,shake; 8 | scanf("%d",&a); 9 | for(i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | void insertionSort(int ar_size, int * ar) { 7 | int n=ar_size,i,j; 8 | int temp=ar[n-1]; 9 | for(i=n-1;i>=0;i--){ 10 | if(temp>ar[i-1]){ 11 | ar[i]=temp; 12 | break; 13 | }else ar[i]=ar[i-1]; 14 | 15 | for(j=0;j 2 | #include 3 | #include 4 | #include 5 | #include 6 | int main(void) { 7 | 8 | int ar_size; 9 | scanf("%d", &ar_size); 10 | int ar[ar_size], _ar_i; 11 | for(_ar_i = 0; _ar_i < ar_size; _ar_i++) { 12 | ar[_ar_i]=0; 13 | } 14 | for(_ar_i = 0; _ar_i < ar_size; _ar_i++) { 15 | scanf("%d", &ar[_ar_i]); 16 | } 17 | 18 | int n=ar_size,i,j; 19 | int temp=0,temp1; 20 | for(i=1;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | int lonelyinteger(int a_size, int* a) { 7 | int i,j,k,flag; 8 | for(i=0;i 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | int a,b,i; 8 | scanf("%d",&a); 9 | for(i=0;i 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | char in_string[4000]; 8 | int present[27],i; 9 | int cur_str; 10 | char cur_string; 11 | for(i=1;i<=26;i++) present[i]=0; 12 | gets(in_string); 13 | int in_len=strlen(in_string); 14 | for(i=0;ia[j]){ 50 | chang=chang+b[j]-a[j]; 51 | 52 | } 53 | } 54 | 55 | System.out.print(chang+"\n"); 56 | 57 | } 58 | 59 | 60 | 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /HackerRank/other_programs/angry_professor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | int n; 11 | cin>>n; 12 | int m,c; 13 | int t; 14 | while(n--){ 15 | cin>>m; 16 | cin>>c; 17 | while(m--){ 18 | cin>>t; 19 | if(t<=0) c--; 20 | } 21 | if(c<=0){ 22 | cout<<"NO"<<"\n"; 23 | }else cout<<"YES\n"; 24 | 25 | 26 | } 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /HackerRank/other_programs/chocolate_feast.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | int t,n,c,m,extra; 11 | cin>>t; 12 | while(t--){ 13 | cin>>n>>c>>m; 14 | int answer=0; 15 | int mid; 16 | mid=n/c; 17 | answer=answer+mid; 18 | 19 | while(mid>=m) 20 | { 21 | 22 | answer=answer+(mid/m); 23 | 24 | extra=mid%m; 25 | mid=mid/m; 26 | 27 | mid=mid+extra; 28 | 29 | } 30 | 31 | 32 | cout<int(two[len1-1])): 13 | count = count + 1 14 | elif(int(one[len1-1]) 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | int n,c,d,i; 8 | char str[10000]; 9 | char str1[10000]=""; 10 | int size; 11 | scanf("%d",&size); 12 | while(size--){ 13 | scanf("%s",str); 14 | n = strlen(str); 15 | // copy string 16 | for (c = n - 1, d = 0; c >= 0; c--, d++) 17 | str1[d] = str[c]; 18 | str1[d] = '\0'; 19 | int flag=1; 20 | for(i=1;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 11 | int n,i,flag; 12 | long double dig1,dig2,fibn,sum; 13 | cin>>n; 14 | for(i=0;i>fibn; 20 | while(sum<=fibn){ 21 | if(sum==fibn) { 22 | flag=1; 23 | } 24 | sum=dig1+dig2; 25 | dig1=dig2; 26 | dig2=sum; 27 | } 28 | 29 | if(flag==1) cout<<"IsFibo\n"; 30 | else cout<<"IsNotFibo\n"; 31 | } 32 | 33 | 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /HackerRank/other_programs/kangaroo.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | import sys 4 | 5 | 6 | x1,v1,x2,v2 = raw_input().strip().split(' ') 7 | x1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)] 8 | #print x1,v1,x2,v2 9 | if(x10): 27 | totalluck = totalluck - int(implist[0]) 28 | implist.pop(0) 29 | casecanfail = casecanfail-1 30 | for i in implist: 31 | totalluck = totalluck + int(i) 32 | print totalluck 33 | 34 | -------------------------------------------------------------------------------- /HackerRank/other_programs/make_it_anagram.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | 10 | int main() { 11 | char s1[10010],s2[10010]; 12 | cin>>s1>>s2; 13 | int a[26]={0}; 14 | for(int i=0;ib[j]) sum+=a[j]-b[j]; 39 | else sum+=b[j]-a[j]; 40 | } 41 | 42 | } 43 | 44 | System.out.println(sum); 45 | 46 | } 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /HackerRank/other_programs/maximizing_xor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | using namespace std; 19 | /* 20 | * Complete the function below. 21 | */ 22 | int maxXor(int l, int r) { 23 | int max=0; 24 | int i,j; 25 | for(i=l;i<=r;i++){ 26 | for(j=i;j<=r;j++){ 27 | if(max<=(i^j)) max=(i^j); 28 | } 29 | } 30 | 31 | return max; 32 | 33 | } 34 | 35 | int main() { 36 | int res; 37 | int _l; 38 | cin >> _l; 39 | 40 | int _r; 41 | cin >> _r; 42 | 43 | res = maxXor(_l, _r); 44 | cout << res; 45 | 46 | return 0; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /HackerRank/other_programs/palindrom_index.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.text.*; 4 | import java.math.*; 5 | import java.util.regex.*; 6 | 7 | public class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in=new Scanner(System.in); 11 | int loop,j,flag=1; 12 | String input; 13 | loop=in.nextInt(); 14 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | long long int a,b,j; 6 | int main() { 7 | scanf("%d"); 8 | while(scanf("%ld%ld",&a,&b)>0) 9 | printf("%d\n",(int)(floor(sqrt(b))-ceil(sqrt(a))+1)); 10 | return 0; 11 | } 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /HackerRank/other_programs/staircase.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | 9 | int main() { 10 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 11 | int n; 12 | cin>>n; 13 | for(int i=1;i<=n;i++){ 14 | for(int j=1;j<=n-i;j++){ 15 | cout<<" "; 16 | } 17 | for(int j=1;j<=i;j++){ 18 | cout<<"#"; 19 | } 20 | cout<<"\n"; 21 | } 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /HackerRank/other_programs/swap_case.py: -------------------------------------------------------------------------------- 1 | s=input(); 2 | for i in s: 3 | if(i.isupper()): 4 | print (i.lower(),end="") 5 | elif(i.islower()): 6 | print (i.upper(),end="") 7 | else : 8 | print (i,end="") 9 | -------------------------------------------------------------------------------- /HackerRank/other_programs/utopian_tree.c: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int height(int n) { 5 | return 0; 6 | } 7 | int main() { 8 | int T; 9 | cin >> T; 10 | while (T--) { 11 | int n; 12 | long int count=1; 13 | cin >> n; 14 | for(int i=1;i<=n;i++){ 15 | if(i%2!=0) count=count*2; 16 | else count++; 17 | } 18 | cout< lenB{ 22 | headA = headA.Next 23 | lenA-- 24 | } 25 | if lenB > lenA { 26 | headB = headB.Next 27 | lenB-- 28 | } 29 | } 30 | for { 31 | if headB == nil || headA == nil { 32 | return headA //should not happen, safe case 33 | } 34 | if headA == headB { 35 | return headA 36 | } 37 | headA = headA.Next 38 | headB = headB.Next 39 | } 40 | return headA 41 | 42 | } 43 | 44 | func getLen(head *ListNode) int { 45 | cnt := 0 46 | for { 47 | if head == nil { 48 | return cnt 49 | } 50 | head = head.Next 51 | cnt++ 52 | } 53 | return cnt 54 | } 55 | -------------------------------------------------------------------------------- /LeetCode/Easy/LinkedList/linked-list-cycle.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/linked-list-cycle 5 | Runtime: 11 ms, faster than 60.08% of Go online submissions for Linked List Cycle. 6 | Memory Usage: 4.3 MB, less than 88.57% of Go online submissions for Linked List Cycle. 7 | */ 8 | 9 | type ListNode struct { 10 | Val int 11 | Next *ListNode 12 | } 13 | 14 | func hasCycle(head *ListNode) bool { 15 | ptr1 := head 16 | ptr2 := head 17 | for { 18 | if ptr1 == nil || ptr2 == nil || ptr2.Next == nil { 19 | return false 20 | } 21 | ptr1 = ptr1.Next 22 | ptr2 = ptr2.Next.Next 23 | // need to check the node itself as the duplicate values are allowed 24 | if ptr1 == ptr2 { 25 | return true 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LeetCode/Easy/LinkedList/linked_list_remove_duplicates.go: -------------------------------------------------------------------------------- 1 | package main 2 | /* 3 | URL: https://leetcode.com/problems/remove-duplicates-from-sorted-list 4 | Runtime: 9 ms, faster than 19.51% of Go online submissions for Remove Duplicates from Sorted List. 5 | Memory Usage: 3.1 MB, less than 75.73% of Go online submissions for Remove Duplicates from Sorted List. 6 | */ 7 | 8 | type ListNode struct { 9 | Val int 10 | Next *ListNode 11 | } 12 | 13 | func deleteDuplicates(head *ListNode) *ListNode { 14 | currentNode := head 15 | for { 16 | if currentNode == nil || currentNode.Next == nil { 17 | return head 18 | } 19 | if currentNode.Val == currentNode.Next.Val { 20 | currentNode.Next = currentNode.Next.Next 21 | continue 22 | } 23 | currentNode = currentNode.Next 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LeetCode/Easy/LinkedList/linkedlist_reverse.go: -------------------------------------------------------------------------------- 1 | package main 2 | /* 3 | URL: https://leetcode.com/problems/reverse-linked-list 4 | Runtime: 6 ms, faster than 20.48% of Go online submissions for Reverse Linked List. 5 | Memory Usage: 2.6 MB, less than 93.28% of Go online submissions for Reverse Linked List. 6 | */ 7 | 8 | type ListNode struct { 9 | Val int 10 | Next *ListNode 11 | } 12 | 13 | func reverseList(head *ListNode) *ListNode { 14 | var prev, next *ListNode 15 | currentNode := head 16 | for { 17 | if currentNode == nil { 18 | return prev 19 | } 20 | next = currentNode.Next 21 | currentNode.Next = prev 22 | prev = currentNode 23 | currentNode = next 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LeetCode/Easy/LinkedList/middle_of_ll.go: -------------------------------------------------------------------------------- 1 | package main 2 | /* 3 | URL: https://leetcode.com/problems/middle-of-the-linked-list/submissions/ 4 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Middle of the Linked List. 5 | Memory Usage: 2 MB, less than 44.00% of Go online submissions for Middle of the Linked List. 6 | */ 7 | 8 | type ListNode struct { 9 | Val int 10 | Next *ListNode 11 | } 12 | 13 | func middleNode(head *ListNode) *ListNode { 14 | if head == nil { 15 | return nil 16 | } 17 | ptr := head 18 | ptr2 := head 19 | for { 20 | if ptr2.Next == nil { 21 | return ptr 22 | } 23 | if ptr2.Next.Next == nil { 24 | return ptr.Next 25 | } 26 | ptr2 = ptr2.Next.Next 27 | ptr = ptr.Next 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /LeetCode/Easy/LinkedList/palindrome-linked-list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/palindrome-linked-list 5 | Runtime: 224 ms, faster than 49.76% of Go online submissions for Palindrome Linked List. 6 | Memory Usage: 9.4 MB, less than 90.62% of Go online submissions for Palindrome Linked List. 7 | */ 8 | 9 | type ListNode struct { 10 | Val int 11 | Next *ListNode 12 | } 13 | 14 | func isPalindrome(head *ListNode) bool { 15 | if head == nil { 16 | return true 17 | } 18 | middle := getMiddle(head) 19 | reversedMiddle := reverseLinkedList(middle) 20 | for { 21 | if reversedMiddle == nil || head == nil { 22 | return true 23 | } 24 | if reversedMiddle.Val != head.Val { 25 | return false 26 | } 27 | reversedMiddle = reversedMiddle.Next 28 | head =head.Next 29 | } 30 | } 31 | 32 | func getMiddle(head *ListNode) *ListNode{ 33 | ptr := head 34 | ptr2 := head 35 | for { 36 | if ptr2.Next == nil { 37 | return ptr 38 | } 39 | if ptr2.Next.Next == nil { 40 | return ptr 41 | } 42 | ptr2 = ptr2.Next.Next 43 | ptr = ptr.Next 44 | } 45 | } 46 | 47 | func reverseLinkedList(head *ListNode) *ListNode { 48 | var prev, next *ListNode 49 | currentNode := head 50 | for { 51 | if currentNode == nil { 52 | return prev 53 | } 54 | next = currentNode.Next 55 | currentNode.Next = prev 56 | prev = currentNode 57 | currentNode = next 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /LeetCode/Easy/Stack_Queue/valid-parentheses.go: -------------------------------------------------------------------------------- 1 | /* 2 | Link: https://leetcode.com/problems/valid-parentheses 3 | 91/ 91 test cases passed 4 | Runtime: 0 ms 5 | Memory Usage: 2.2 MB 6 | */ 7 | 8 | package main 9 | 10 | func isValid(s string) bool { 11 | matchingString := map[string]string{ 12 | ")": "(", 13 | "}": "{", 14 | "]": "[", 15 | } 16 | var sliceStr []string 17 | for _, c := range s { 18 | switch string(c) { 19 | case "(", "{", "[": 20 | sliceStr = append(sliceStr, string(c)) 21 | case ")", "}", "]": 22 | if len(sliceStr) == 0 { 23 | return false 24 | } 25 | if sliceStr[len(sliceStr)-1] != matchingString[string(c)] { 26 | return false 27 | } 28 | sliceStr = sliceStr[:len(sliceStr)-1] 29 | } 30 | } 31 | if len(sliceStr) != 0 { 32 | return false 33 | } 34 | return true 35 | } 36 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/best-time-to-buy-and-sell-stock.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/best-time-to-buy-and-sell-stock 5 | Runtime: 278 ms, faster than 9.83% of Go online submissions for Best Time to Buy and Sell Stock. 6 | Memory Usage: 8.7 MB, less than 64.30% of Go online submissions for Best Time to Buy and Sell Stock. 7 | */ 8 | 9 | func maxProfit(prices []int) int { 10 | lPrices := len(prices) 11 | if lPrices <= 0{ 12 | return 0 13 | } 14 | maxToSell := prices[lPrices-1] 15 | maxProfit := 0 16 | 17 | for i:=lPrices-2;i>=0;i--{ 18 | if maxToSell-prices[i]>maxProfit{ 19 | maxProfit = maxToSell-prices[i] 20 | } 21 | if prices[i] > maxToSell{ 22 | maxToSell=prices[i] 23 | } 24 | } 25 | return maxProfit 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/contains_duplicate.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/contains-duplicate 5 | Status: Success 6 | Runtime: 96 ms, faster than 56.49% of Go online submissions for Contains Duplicate. 7 | Memory Usage: 9.1 MB, less than 48.28% of Go online submissions for Contains Duplicate. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func containsDuplicate(nums []int) bool { 14 | identity := make(map[int]struct{}, len(nums)) 15 | for _, num := range nums { 16 | if _, ok := identity[num]; ok { 17 | return true 18 | } 19 | identity[num] = struct{}{} 20 | } 21 | return false 22 | } 23 | 24 | func main() { 25 | fmt.Println("input: <>, output:", containsDuplicate([]int{1, 1, 2})) 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/decompress_encoded_list.go: -------------------------------------------------------------------------------- 1 | /* 2 | Link: https://leetcode.com/problems/decompress-run-length-encoded-list 3 | Runtime: 4 ms, faster than 93.56% of Go online submissions for Decompress Run-Length Encoded List. 4 | Memory Usage: 5.9 MB, less than 51.98% of Go online submissions for Decompress Run-Length Encoded List. 5 | */ 6 | package main 7 | 8 | func decompressRLElist(nums []int) []int { 9 | var val []int 10 | for i := 0; i < len(nums); i = i + 2 { 11 | for j := 0; j < nums[i]; j++ { 12 | val = append(val, nums[i+1]) 13 | } 14 | } 15 | return val 16 | } 17 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/divide-array-into-equal-pairs.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/divide-array-into-equal-pairs/ 5 | Status: Success 6 | Runtime: 23 ms, faster than 34.57% of Go online submissions for Divide Array Into Equal Pairs. 7 | Memory Usage: 5.8 MB, less than 40.74% of Go online submissions for Divide Array Into Equal Pairs. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func main() { 14 | fmt.Println("input: <>, output:", intersect([]int{1, 2, 2, 1}, []int{2, 2})) 15 | } 16 | 17 | func divideArray(nums []int) bool { 18 | numCount := make(map[int]int) 19 | for _, num := range nums { 20 | numCount[num]++ 21 | } 22 | for _, val := range numCount{ 23 | if val % 2 != 0 { 24 | return false 25 | } 26 | } 27 | return true 28 | } 29 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/intersect_of_2_arrays.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/intersection-of-two-arrays-ii/ 5 | Status: Success 6 | Runtime: 6 ms, faster than 33.88% of Go online submissions for Intersection of Two Arrays II. 7 | Memory Usage: 3 MB, less than 74.10% of Go online submissions for Intersection of Two Arrays II. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func main() { 14 | fmt.Println("input: <>, output:", intersect([]int{1, 2, 2, 1}, []int{2, 2})) 15 | } 16 | 17 | func intersect(nums1 []int, nums2 []int) []int { 18 | len1 := len(nums1) 19 | len2 := len(nums2) 20 | if len1 == 0 || len2 == 0 { 21 | return []int{} 22 | } 23 | if len1 < len2 { 24 | return process(nums1, nums2, len1, len2) 25 | } 26 | return process(nums2, nums1, len2, len1) 27 | } 28 | 29 | func process(mapArr, otherArr []int, mapLen, otherLen int) []int { 30 | numMap := make(map[int]int, mapLen) 31 | for i := 0; i < mapLen; i++ { 32 | numMap[mapArr[i]]++ 33 | } 34 | totalNum := 0 35 | for i := 0; i < otherLen; i++ { 36 | if numMap[otherArr[i]] > 0 { 37 | if totalNum < mapLen { 38 | mapArr[totalNum] = otherArr[i] 39 | } else { 40 | mapArr = append(mapArr, otherArr[i]) 41 | } 42 | numMap[otherArr[i]]-- 43 | totalNum++ 44 | } 45 | } 46 | if totalNum < mapLen { 47 | return mapArr[:totalNum] 48 | } 49 | return mapArr 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/kth-largest-element-in-a-stream.go: -------------------------------------------------------------------------------- 1 | /* 2 | Link: https://leetcode.com/problems/kth-largest-element-in-a-stream 3 | Status: Time Limit Exceeded 4 | */ 5 | package main 6 | 7 | 8 | type KthLargest struct { 9 | items []int 10 | index int 11 | streamLen int 12 | } 13 | 14 | func Constructor(k int, nums []int) KthLargest { 15 | streamLen := len(nums) 16 | if k > streamLen{ 17 | streamLen=k 18 | } 19 | return KthLargest{items:nums,index:k,streamLen:streamLen} 20 | } 21 | 22 | 23 | func (this *KthLargest) Add(val int) int { 24 | this.items = append(this.items,val) 25 | sort.Ints(this.items) // TODO: use binary search to keep the new value in right place. Sort is causing TLE 26 | if len(this.items)>this.streamLen{ 27 | this.items=this.items[1:] 28 | } 29 | if len(this.items)<=0{ 30 | return val 31 | } 32 | ind := (len(this.items)-this.index)%len(this.items) 33 | return this.items[ind] 34 | } 35 | 36 | 37 | /** 38 | * Your KthLargest object will be instantiated and called as such: 39 | * obj := Constructor(k, nums); 40 | * param_1 := obj.Add(val); 41 | */ 42 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/last-stone-weight.go: -------------------------------------------------------------------------------- 1 | /* 2 | Link: https://leetcode.com/problems/last-stone-weight 3 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Last Stone Weight. 4 | Memory Usage: 2 MB, less than 82.05% of Go online submissions for Last Stone Weight. 5 | */ 6 | package main 7 | 8 | func lastStoneWeight(stones []int) int { 9 | if len(stones) == 0{ 10 | return 0 11 | } 12 | for len(stones) > 1{ 13 | sort.Ints(stones) 14 | l := stones[len(stones)-1] 15 | l2 := stones[len(stones)-2] 16 | stones[len(stones)-2]=l-l2 17 | stones = stones[:len(stones)-1] 18 | } 19 | return stones[0] 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/longest-common-prefix.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/longest-common-prefix 5 | Status: Success 6 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Longest Common Prefix. 7 | Memory Usage: 2.4 MB, less than 100.00% of Go online submissions for Longest Common Prefix. 8 | */ 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | func longestCommonPrefix(strs []string) string { 15 | index := 0 16 | for { 17 | breakOut := false 18 | if index >= len(strs[0]) { 19 | break 20 | } 21 | currLetter := strs[0][index] //current digit needed to be checked 22 | for _, s := range strs { 23 | if index >= len(s) || s[index] != currLetter { 24 | breakOut = true 25 | break 26 | } 27 | } 28 | if breakOut { 29 | break 30 | } 31 | index++ 32 | } 33 | if index == 0 { 34 | return "" 35 | } 36 | return strs[0][0:index] 37 | } 38 | 39 | func main() { 40 | fmt.Println("input: <>, output:", longestCommonPrefix([]string{"car", "ca"})) 41 | } 42 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/maximum-subarray.go: -------------------------------------------------------------------------------- 1 | /* 2 | Link: https://leetcode.com/problems/maximum-subarray 3 | Runtime: 167 ms, faster than 15.48% of Go online submissions for Maximum Subarray. 4 | Memory Usage: 10 MB, less than 12.44% of Go online submissions for Maximum Subarray. 5 | */ 6 | package main 7 | 8 | func maxSubArray(nums []int) int { 9 | if len(nums) <=0 { 10 | return 0 11 | } 12 | max := nums[0] 13 | currMax := nums[0] 14 | for i:=1;i 0 { 16 | currMax = currMax+nums[i] 17 | }else{ 18 | currMax = nums[i] 19 | } 20 | if max < currMax { 21 | max = currMax 22 | } 23 | } 24 | return max 25 | } 26 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/maximum-units-on-a-truck.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/maximum-units-on-a-truck/ 5 | Status: Success 6 | Runtime: 32 ms, faster than 49.07% of Go online submissions for Maximum Units on a Truck. 7 | Memory Usage: 7 MB, less than 8.33% of Go online submissions for Maximum Units on a Truck. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func maximumUnits(boxTypes [][]int, truckSize int) int { 14 | var unitNums []int 15 | boxMap := make(map[int]int) 16 | for _, box := range boxTypes{ 17 | // first index is number of boxes 18 | // second index is size of thar unit 19 | if boxMap[box[1]] == 0 { 20 | // get the unique qty numbers 21 | unitNums = append(unitNums,box[1]) 22 | } 23 | // get the total number boxes available for the given qty 24 | boxMap[box[1]]+= box[0] 25 | } 26 | sort.Ints(unitNums) 27 | numsLen := len(unitNums) 28 | numsUnit := 0 29 | for i:=numsLen-1;i>=0;i--{ 30 | if truckSize <=0 { 31 | return numsUnit 32 | } 33 | if boxMap[unitNums[i]] < truckSize { 34 | numsUnit+=(boxMap[unitNums[i]]*unitNums[i]) 35 | truckSize-=boxMap[unitNums[i]] 36 | }else{ 37 | numsUnit+=(unitNums[i]*truckSize) 38 | truckSize-=boxMap[unitNums[i]] 39 | } 40 | } 41 | return numsUnit 42 | } 43 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/merge-sorted-array.go: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Link: https://leetcode.com/problems/merge-sorted-array 4 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Merge Sorted Array. 5 | Memory Usage: 2.2 MB, less than 84.71% of Go online submissions for Merge Sorted Array. 6 | */ 7 | 8 | func merge(nums1 []int, m int, nums2 []int, n int) { 9 | idxPtr := len(nums1)-1 10 | for m>0||n>0{ 11 | if n<=0||(m>0&&nums1[m-1]>nums2[n-1]){ 12 | nums1[idxPtr]=nums1[m-1] 13 | m-- 14 | idxPtr-- 15 | }else if m<=0||(n>0&&nums1[m-1]<=nums2[n-1]){ 16 | nums1[idxPtr]=nums2[n-1] 17 | n-- 18 | idxPtr-- 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/missing_number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/missing-number/submissions/ 5 | Status: Success 6 | Runtime: 20 ms, faster than 67.82% of Go online submissions for Missing Number. 7 | Memory Usage: 7.4 MB, less than 5.24% of Go online submissions for Missing Number. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | // for the given number from 0 to n, find the missing number in (n-1) array 14 | // ex: input: [0,1] output: 2. 0 to n is 0,1,2 and 0,1 is part of the array. 15 | func missingNumber(nums []int) int { 16 | xor := len(nums) 17 | for idx, num := range nums { 18 | xor = xor ^ num ^ idx 19 | } 20 | return xor 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/move-zeroes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/move-zeroes 5 | Status: Success 6 | Runtime: 20 ms, faster than 92.93% of Go online submissions for Move Zeroes. 7 | Memory Usage: 6.6 MB, less than 86.77% of Go online submissions for Move Zeroes. 8 | */ 9 | 10 | func moveZeroes(nums []int) { 11 | if len(nums) <=1{ 12 | return 13 | } 14 | cnt := 0 15 | for idx:=0;idx, output:", removeDuplicates([]int{1, 1, 2})) 30 | } 31 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/remove_duplicates_from_sorted_array.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 5 | Status: Success 6 | Runtime: 8 ms, faster than 88.29% of Go online submissions for Remove Duplicates from Sorted Array. 7 | Memory Usage: 4.3 MB, less than 100.00% of Go online submissions for Remove Duplicates from Sorted Array. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func main() { 14 | fmt.Println("input: <>, output:", removeDuplicates([]int{1, 1, 2})) 15 | } 16 | 17 | func removeDuplicates(nums []int) int { 18 | if len(nums) <= 1 { 19 | return len(nums) 20 | } 21 | cnt := 0 22 | for idx := 1; idx < len(nums); idx++ { 23 | if nums[cnt] == nums[idx] { 24 | continue 25 | } 26 | cnt++ 27 | nums[cnt] = nums[idx] 28 | } 29 | return cnt + 1 30 | } 31 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/remove_element.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/remove-element 5 | Status: Success 6 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Remove Element. 7 | Memory Usage: 2.1 MB, less than 86.73% of Go online submissions for Remove Element. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func removeElement(nums []int, val int) int { 14 | if len(nums) <0||(len(nums)==1 && nums[0]==val) { 15 | return 0 16 | } 17 | cnt := 0 18 | for idx := 0; idx < len(nums); idx++ { 19 | if val == nums[idx] { 20 | continue 21 | } 22 | nums[cnt] = nums[idx] 23 | cnt++ 24 | } 25 | return cnt 26 | } 27 | 28 | func main() { 29 | fmt.Println("input: <>, output:",removeElement([]int{3,2,2,3},3)) 30 | } 31 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/remove_one_element_to_make_array_increasing.go: -------------------------------------------------------------------------------- 1 | /* 2 | Link: https://leetcode.com/problems/valid-parentheses 3 | 91/ 91 test cases passed 4 | Runtime: 0 ms 5 | Memory Usage: 2.2 MB 6 | */ 7 | 8 | package main 9 | 10 | import "fmt" 11 | 12 | func canBeIncreasing(nums []int) bool { 13 | l := len(nums) 14 | if l <= 2 { 15 | return true 16 | } 17 | // lastDig := nums[0] 18 | // dupVal := 0 19 | // var numLess bool 20 | lastDig := nums[0] 21 | alreadyDec := false 22 | for i := 1; i < l; i++ { 23 | fmt.Printf("i %d\n", nums[i]) 24 | 25 | if nums[i] <= nums[i-1] { 26 | if alreadyDec { 27 | fmt.Printf("i %d, compare with %d\n", nums[i], lastDig) 28 | return false 29 | } 30 | alreadyDec = true 31 | // check whether the last digit after omiting the decreasing num is lesses than nums[i] 32 | if lastDig > nums[i] { 33 | fmt.Printf("false as dup, lastdig %d nums[i] %d\n", lastDig, nums[i]) 34 | return false 35 | } 36 | // lastDig = nums[i-1] 37 | // i-- 38 | continue 39 | } else { 40 | lastDig = nums[i-1] 41 | } 42 | } 43 | return true 44 | } 45 | 46 | func main() { 47 | // fmt.Println(canBeIncreasing([]int{1, 2, 10, 5, 7})) 48 | // fmt.Println(canBeIncreasing([]int{2, 3, 1, 2})) 49 | // fmt.Println(canBeIncreasing([]int{1, 1})) //true 50 | fmt.Println(canBeIncreasing([]int{100, 21, 100})) //true 51 | } 52 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/reverse_integer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/reverse-integer/ 5 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Reverse Integer. 6 | Memory Usage: 2.1 MB, less than 80.67% of Go online submissions for Reverse Integer. 7 | */ 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | 13 | func reverse(x int) int { 14 | MAX_INT := 2147483648-1 15 | isNeg := false 16 | if x < 0{ 17 | isNeg = true 18 | x = x* -1 19 | } 20 | newVal := 0 21 | for { 22 | if x <= 0 { 23 | break 24 | } 25 | newVal = (newVal*10)+((x %10)) 26 | if newVal >= MAX_INT { 27 | return 0 28 | } 29 | x = x/10 30 | } 31 | if isNeg{ 32 | return newVal * -1 33 | } 34 | return newVal 35 | } 36 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/running-sum-of-1d-array.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/intersection-of-two-arrays-ii/ 5 | Status: Success 6 | Runtime: 7 ms, faster than 13.10% of Go online submissions for Running Sum of 1d Array. 7 | Memory Usage: 2.7 MB, less than 85.71% of Go online submissions for Running Sum of 1d Array. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func runningSum(nums []int) []int { 14 | if len(nums) <=1{ 15 | return nums 16 | } 17 | for i:=1;i midIdx { 24 | break 25 | } 26 | if nums[midIdx] == target { 27 | return midIdx 28 | } 29 | if target > nums[midIdx] { 30 | if midIdx >= numLen { 31 | return numLen 32 | } 33 | pos = midIdx + 1 34 | minIdx = midIdx + 1 35 | } else { 36 | if midIdx <= 0 { 37 | return 0 38 | } 39 | pos = midIdx 40 | maxIdx = midIdx - 1 41 | } 42 | } 43 | return pos 44 | } 45 | 46 | func main() { 47 | fmt.Println("input: <>, output:", searchInsert([]int{1, 3, 5, 6, 45}, 2)) 48 | } 49 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/single_number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/single-number 5 | Status: Success 6 | Runtime: 14 ms, faster than 90.71% of Go online submissions for Single Number. 7 | Memory Usage: 6.3 MB, less than 73.26% of Go online submissions for Single Number. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func main() { 14 | fmt.Println("input: <>, output:", singleNumber([]int{2, 2, 1, 3, 1})) 15 | } 16 | 17 | func singleNumber(nums []int) int { 18 | sum := 0 19 | for _, num := range nums { 20 | sum = sum ^ num 21 | } 22 | return sum 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode/Easy/array/sort-array-by-parity.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/sort-array-by-parity 5 | Status: Success 6 | Runtime: 5 ms, faster than 88.56% of Go online submissions for Sort Array By Parity. 7 | Memory Usage: 5.3 MB, less than 12.94% of Go online submissions for Sort Array By Parit 8 | */ 9 | 10 | func sortArrayByParity(nums []int) []int { 11 | if len(nums) <=1{ 12 | return nums 13 | } 14 | cnt := 0 15 | var oddArray []int 16 | for idx:=0;idx charsLen { 23 | continue 24 | } 25 | // we cannot duplicate a map directly as the map is inmemeory and charIdx gets updated aswell 26 | // So create a new map again for the charIdx 27 | wordIdx := make(map[rune]int) 28 | for key, val := range charIdx { 29 | wordIdx[key] = val 30 | } 31 | // for each words loop thorugh the each chars and check the count of that char repetition 32 | completedWord := true 33 | for _, wordChar := range word { 34 | if _, ok := wordIdx[wordChar]; !ok { 35 | // if the char of word doesnot exist, break 36 | completedWord = false 37 | break 38 | } else { 39 | // if the char of the word is already exhausted, break 40 | if wordIdx[wordChar] <= 0 { 41 | completedWord = false 42 | break 43 | } 44 | wordIdx[wordChar] = wordIdx[wordChar] - 1 45 | } 46 | } 47 | if completedWord { 48 | totalCount = totalCount + len(word) 49 | } 50 | } 51 | // fmt.Println("charidx", charIdx) 52 | return totalCount 53 | } 54 | 55 | func main() { 56 | fmt.Println("input: <>, output:", countCharacters([]string{"hello", "world", "leetcode"}, "welldonehoneyr")) 57 | fmt.Println("input: <>, output:", countCharacters([]string{"qobxtxjzdngkrzamsxzdvbvkiwijokwdyndqllhqpaoxzwonriclsm", "fahtqqnuzhhhrcblquaosdfdcqoskxcsdnhtwvvvzsxkpjprytieieniafnltxmuzwkdnttofpibi", "xedhntgrqegfs", "wrssfvsbcehbahbvojnzgacbgveitirkjmmyiorwykynqddgydzgfvlvplfnyumgxturxraonpchd", "hpmdzhpgijirecxzkuyhptiytnuscu", "xljgysrjjukphjgzbpn", "gmwbirxt", "yhvpsvsnhfmbmcpihnqtodspbvexnpgcqrrughbakbufyjispkquvfppkaffypdpnvikjygdaarcigipfhuvzzzbgw", "gvvbgpjolobpbxcnhnzuqrsqgrkanwmnnkqynakkooailoafunopsrlijqhaqmszssxikftcfoqsw", "naktgxfyuvuoh", "muui", "ghzqskipqprrzeligdjyowypeerogxonvztsq", "onosezgutawtzteoagbftclsqpfsxtwetourxjxurdqevrir", 58 | "fcskqxwkzsldsjihahalnw", "lsstgzxjxabcbspjwelqmhtnurgfmdtpaihxnxad", "nwrwtwetgjwooevhxhkzlvsyghtkldioyjhkkniepktqs", "utohzbqvkqkq", "vdoqnhtidgicevprrrwlbtldtaxpsxdhxhgbwlkbeglkbhrujtafswjkozdmdpvwhsuskofmxxtprtpopacslinwozth", "zqlzxpemomnbzxlorvlkxt", "kubshvnldnkofitnnjere", "czxmqpowzzhdbhgtlqdokrzxowsvwyavfhcycctgdvrsfzmanrlktfaetnuayrqkvhcbxezfahkrxgaaztovrxuhnll", "rrcesnfbxglhjawldnnuiiepdsofbrsbjczlemusqwvenicxmtdmpwfrnizymfmqynvtkbrmablcugroshc", "thholqebekkysstqzlbbdapktxumygplqganucwnahmrihiraxdnvbiaqhykcti", "fagqnapzeeglbdzsbneosxmptmwopjcxztukhpjkqjmjbkpbzrfaqskctehyboeddmilkwlurcb", "wtjdykncubkduhxiwwusoxvzpnaxpnzdjmwddnonsmmvwmuaxghetgrwpoeqbprxgviwzagyqopfdakrqjgiy", "nsftehpgzstetbganbtozdopptseucdqkhzdmujnzjdvufqtikgeepttnrabb", "ozihktgnvljzhqwanxemtzxphzqvmoblvi", "iwdsrekqllbbyarzzmbqbvldvxctdeswiyahiwfoefhfsfwktdzaulnalewbusazjhcbtxjuck", "dylhds", "idnaddnzbodhjrpshhahnbbnrskruxszxeeyanumazvahktizectmmvjbhnhbrohsyqhrgq", "scyzsykrwzuozmbrbenfiqpxchtpmcxepjiglaeionsmbwrzeidupayusczcooudpcgkgspbuyzcdfymsejucb", "otpcfrhckxmnseayhwoyjjfkceaoznmmkikpdsuueyqmbsuelmhqnmdsjs", "xoghnhpypfiibqrpgtyux", "cxhpbcziptgandiwxtctdjpboiqwv", "gyjosuhwgbqpcdsdqadopdqozjxpzwxbqaffnxaddhgrxmunpidvpnijxnbawshcznkmprpgkhvzxmzbaftedgtfgjhaisdnva", "jlnxshfthqgzlnvjzztrnjswwsotpybxecyqhnfkbfwvmxpcs", "mtddspmqwbnoiajpexsuhxogarduzsoammqqelh", "sixkvxgnbalipwmkbcwpugpvolsvvlmaaeeobmoeogspbkbsskwjdqkite", "xhsutriuynfrldjbhexhxjgcfwcujvwsqfiaqwvjnkjkswdpaynelhryrzfeqjhajezmolk", "zfiredtxenzgtrkiamuoubetexzbnwkdtxbtihhtsfubnmryxq", "sot", "szgkkhuhkcnr", "firxkgvkzqlnallzwjispsizoawobemuhqrhpyvknasjzwctamfuonder", "vyei", "fidqszoicndwifns", "xkickycwzj", "gmybflbjunudxrwguzditaxmyadgdjeengut", "gvlwwnmrddhzwewugdtobauecealfhasyftgxkiqeluysxxmroukfziifpryvddggttojhcszeyjetbsldmorqnbuqreuxfw", "vbhuerxkcjlkamgruturkbrubbscmvzqruwvlrlyylcvuiothkhpznjzsfnyfoaqkziyjqzdreeygmtbdljwnaojexfgmjlup", "bxjvop", "aswdmctosieicucsjwxych", "lxbtlhnrfyaznrqgxrltmxkjmhdqjjgnvstxaygmuxznjfiiukm", "npncdabkmbgfhnedcmbfyjiplzwymgvsfrifvvjayobsygwolqbwkblqutakcshnlsqadtfiqmpauslvqd", "kuyemuuymacyvmahtagmcewkspverpjtjscccnrczchgkjzppdxcalxxcxrwnepk", "jxwouobfvzttz", "yucpsdhqvzboeezcqpxsepuuk", "iwbdmxdcbypnzqmgkrjhfivkrmnv", "lpqklgcwdvgbghfyoyejnpexrelywqfdtczflwetbxvzigtvisi", "dlasodatffcreungntdmezgfqklrabyymsnhdberufcrgpxgsziklznhdprbczhbxgtuslufycjronozdqumzlnidkvaydg", "oejzlmrrbdysqlezifcvgjnmvodfvmrnjmnfkejdbnnyljzjaxfecrfefdgarqbtwoijuktacywmsubtxtgzkbnstgrsrjpkdfe", "mlegvhxielwlfadlnqvnipcuizpdxgtvro", "vwgmwkbturocovaykdsjaftbtgmtwknnmhexfgcfchpwwgcgecfobbencotjizxbtdrijwfjxdsxanwfjyjamrxrdaiusgr", "xjmkcsekcorldyrjiavrhuhqtndujymc", "rmxwcaorznumwxgwnibnxwzvnxjhzwqzgmkgifnnnnzpgtsvprycjtdeirtpqbduursabbidzkfbexgthkoacagkb", "tkrsxhztwgvqxamjtexklnooaloydjhejlbasavskttwxiabarogvmfdfjttaxhgqljlbfnrvrwwbxkurhufiknoxfmemcv", "cojlyayladyrhofzetaddteqrjbyxtvyszgdorexqmgznqmuvemegbwki", "zktqnurtpttlcjgkmnprqeyeepqunfqqvjwuevwbvnaupyofwiqwhpyumyfwpjrruhleromrmpvczlkxqiuq", "gyxl", "qmhwlymfsjixvvjhkczylqcsnbjxliasetxciggtfl", "gizysqkqbyhzeagzsscvdigtcfiupyhqovaaioxfrphugxzrcjvwqwc", "hpgkulrmbaixnjiapmjiwhwsgromfqpxqkkiscjwpiicslwcijginxfiwqakeezeohhskxgvgdkezmqys", "vibswdyqaxjvqsffwmcismooheyhwzqvyzezluejztlgddshvwcryzcllaisxrygwqyyoiaivfvgtzicycyrkckv", "oyclwdejlifmocfjsbgmernsyitkfaahjxfnwnusrdypsziawlpsjgnavytdihpxcmugshnqbkyfts", "xwcbiporfbktpvqhznjuaxfcdykifuzwdsdhxirwwxinoffywgxscrtuwhvuwjejzqirsfijgguouapqpmfdnpsfm", "qffrjfkj", "rpynimubaxdgbrkdawgugnhobaowxdnzkiidworcsnejgqctftyksvbhiwkcnyffmsbxwptqn", "oeqdvldvfbklukstxwomapaauaozblhxudkdxihepqagndnlkvbqhluscvczhrsrhodnftoszhjdymuywdtjgzbmkrdf", "xviupppkeswkctwlqwyuhokbhqqjshmaeiouhununbhrkabacenkg", "habomjnlznqvckmowgelhnglfizogckplbymkdowfpicxydzgoskckraxpdysksvzezcpg", "zemawxwjeowraaqsqytsshtavnvoyiyollelxqabmjwhxtrdijiacbbjiiyzwkxboot", "jcnpsxnkbqdbh", "bftrbaurtzkftodotjguzjmwxrrmswxwclohotuanypmhtemmsaicwckowmcdmpnhcfzptekpgljfvwpqjgilxu", "bbaigjqxdmuchkkb", "effbptpwafzqbsebbjmvdcxdbmnlfqjklongafzkvaqmkehefedjxgxlbdhltihtgfqjjsdis", "lhuxgqpwcgpujfvvnlrxhgbiwxmxzhglyhkdkafafojtlkuxkmjwlxrd", "ussuyjqsxwsdhkjeipwycrkcxxjatoqhygzymgikqdnqiyyzlbcdlgtmneyickucbkpkza", "ykmsksjorovmdymlbgprvprnyxwppvwgmzfjsqouvgara", "wduqkbncayo", "qdfkyomjlhfozonwpdxllqdnvpohyijqmyymuclnydzmlqksntdfj", "ynzekkkljzrvnwclzcfgtvcmstxgadxpztofckypbgqgbnumnkeaqclaspzxjbygtkjznxeduhbksr", "aw", "jbremnahqoiqktpbkteefdkbrerrxmhqbbselpnfzapgmxidrhbixetaetjcroufa", "wtufuqgljvxzsurhviikdxyuythezjnvwrxqrykmotkhlphlyfljjsfugzwxxfqkc", "ytjuaagqnfxqwiopolnejmoxow", "oqoskpzkwxsffgeuuhdklidtmjobzayatyaqefgwgqbo", "qkhtpuhhkspffkpryvdjasbxhtfrmptpljszvtgvhfvqpxypxfdaphfqdmigzgfg", 59 | "goddugelwdvemxwureitzwqmbqeqtymrlrzahuxnpgufaagbpexwpoahvdnsyvgxw", "dfhxrctagxkuasofoejsalcerkbtsjwnbnoahsumzfyiiskhzzwyykeefszrzrbztbrzhxxgaajb", "tjsardsbhmhefysdqtbhzsxukbwdpioqaohloaancxdkkmofniojrvxj", "jzjozqfqiwyfadplibubtpcfxxfvjtbizxlmpaccjpihvnrtvfqtfiaztvfbednyemfmahbljdvykddawaujdksenm"}, 60 | "fcxpzkzkqeyeijquyfixvlzjpzomujrqzxeoynjiflnmdrpdkrm")) 61 | } 62 | -------------------------------------------------------------------------------- /LeetCode/Easy/strings/first_unique_char.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/contains-duplicate 5 | URL: https://leetcode.com/problems/first-unique-character-in-a-string 6 | Status: Success 7 | Runtime: 10 ms, faster than 83.10% of Go online submissions for First Unique Character in a String. 8 | Memory Usage: 6.4 MB, less than 19.25% of Go online submissions for First Unique Character in a String. 9 | */ 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | 15 | // mycode 16 | func firstUniqChar(s string) int { 17 | runes := []rune(s) 18 | strMap := make(map[string]int,len(s)) 19 | for _, r:= range runes{ 20 | strMap[string(r)]++ 21 | } 22 | for idx, r:= range runes{ 23 | if strMap[string(r)] <= 1{ 24 | return idx 25 | } 26 | } 27 | return -1 28 | } 29 | 30 | // best sol 31 | func firstUniqChar(s string) int { 32 | var counts [26]int 33 | for i := 0; i < len(s); i++ { 34 | counts[s[i] - 'a']++ 35 | } 36 | 37 | for i := 0; i < len(s); i++ { 38 | if counts[s[i] - 'a'] == 1 { 39 | return i 40 | } 41 | } 42 | 43 | return -1 44 | } 45 | -------------------------------------------------------------------------------- /LeetCode/Easy/strings/implement-strstr.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/implement-strstr/ 5 | Status: Success 6 | Runtime: 3 ms, faster than 54.86% of Go online submissions for Implement strStr(). 7 | Memory Usage: 2 MB, less than 78.94% of Go online submissions for Implement strStr(). 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func strStr(haystack string, needle string) int { 14 | if len(needle) == 0 { 15 | return -1 16 | } 17 | f := needle[0] 18 | hayLen := len(haystack) 19 | needleLen := len(needle) 20 | i := 0 21 | for { 22 | if i >= hayLen || hayLen-i < needleLen{ 23 | return -1 24 | } 25 | if haystack[i]==f{ 26 | // check all chars of needle 27 | hayIndex := i 28 | needleIdx :=0 29 | for j:= hayIndex;j= len(strs[0]) { 17 | break 18 | } 19 | currLetter := strs[0][index] //current digit needed to be checked 20 | for _, s := range strs { 21 | if index >= len(s) || s[index] != currLetter { 22 | breakOut = true 23 | break 24 | } 25 | } 26 | if breakOut { 27 | break 28 | } 29 | index++ 30 | } 31 | if index == 0 { 32 | return "" 33 | } 34 | return strs[0][0:index] 35 | } 36 | -------------------------------------------------------------------------------- /LeetCode/Easy/strings/palindrome.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/palindrome-number/ 5 | Status: Accepted 6 | Runtime: 8 ms, faster than 95.51% of Go online submissions for Palindrome Number. 7 | Memory Usage: 5.4 MB, less than 42.49% of Go online submissions for Palindrome Number. 8 | */ 9 | import ( 10 | "fmt" 11 | "strconv" 12 | ) 13 | 14 | func isPalindrome(x int) bool { 15 | t := strconv.Itoa(x) 16 | strLen := len(t) 17 | for i := 0; i < strLen/2; i++ { 18 | if t[i] != t[strLen-1-i] { 19 | return false 20 | } 21 | } 22 | return true 23 | } 24 | 25 | func main() { 26 | fmt.Println("op: ", isPalindrome(-121)) 27 | fmt.Println("op: ", isPalindrome(121)) 28 | } 29 | -------------------------------------------------------------------------------- /LeetCode/Easy/strings/ransom-note.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/ransom-note 5 | Status: Success 6 | Runtime: 7 ms, faster than 80.00% of Go online submissions for Ransom Note. 7 | Memory Usage: 3.9 MB, less than 84.13% of Go online submissions for Ransom Note. 8 | */ 9 | 10 | func canConstruct(ransomNote string, magazine string) bool { 11 | var letCnt [26]int 12 | for _, char := range magazine { 13 | letCnt[char-97]++ 14 | } 15 | for _, char := range ransomNote { 16 | letCnt[char-97]-- 17 | if letCnt[char-97] < 0 { 18 | return false 19 | } 20 | } 21 | return true 22 | } 23 | -------------------------------------------------------------------------------- /LeetCode/Easy/strings/reverse-words-in-a-string.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/reverse-words-in-a-string/ 5 | Status: Accepted 6 | Runtime: 3 ms, faster than 61.19% of Go online submissions for Reverse Words in a String. 7 | Memory Usage: 2.9 MB, less than 82.09% of Go online submissions for Reverse Words in a String. 8 | */ 9 | 10 | import ( 11 | "strings" 12 | ) 13 | 14 | func reverseWords(s string) string { 15 | if s == ""{ 16 | return "" 17 | } 18 | f := strings.Fields(s) 19 | for i:=0;i, output:", romanToInt("III")) 40 | } 41 | -------------------------------------------------------------------------------- /LeetCode/Easy/strings/string_reverse_a_string.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /* 6 | URL: https://leetcode.com/problems/reverse-string/ 7 | Status: Success 8 | Runtime: 28 ms, faster than 99.13% of Go online submissions for Reverse String. 9 | Memory Usage: 6.6 MB, less than 97.93% of Go online submissions for Reverse String. 10 | */ 11 | 12 | 13 | // strings are immutable and you cannot do str[i] 14 | func reverseString(s []byte) { 15 | strLen := len(s) 16 | for i:=0; i= endLen{ 15 | return true 16 | } 17 | 18 | if s[startLen]==s[endLen]{ 19 | startLen++ 20 | endLen-- 21 | }else{ 22 | if delChar{ 23 | return false 24 | } 25 | if s[startLen] == s[endLen-1] && s[startLen+1] == s[endLen]{ 26 | // make sure that the remaining string is palindorm, If yes, return true 27 | // increase the endLen index by 1 as golang will not include the last char if it is not included 28 | return isPalindrome(s[startLen:endLen]) || isPalindrome(s[startLen+1:endLen+1]) 29 | }else if s[startLen] == s[endLen-1]{ 30 | endLen-- 31 | delChar=true 32 | }else if s[startLen+1] == s[endLen]{ 33 | startLen++ 34 | delChar=true 35 | }else{ 36 | return false 37 | } 38 | 39 | } 40 | 41 | } 42 | 43 | return true 44 | } 45 | 46 | func isPalindrome(t string) bool { 47 | strLen := len(t) 48 | for i := 0; i < strLen/2; i++ { 49 | if t[i] != t[strLen-1-i] { 50 | return false 51 | } 52 | } 53 | return true 54 | } 55 | -------------------------------------------------------------------------------- /LeetCode/Easy/trees/binary-tree-inorder-traversal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/binary-tree-inorder-traversal 5 | Status: Success 6 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Binary Tree Inorder Traversal. 7 | Memory Usage: 1.9 MB, less than 91.64% of Go online submissions for Binary Tree Inorder Traversal. 8 | */ 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | /** 15 | * Definition for a binary tree node. 16 | * type TreeNode struct { 17 | * Val int 18 | * Left *TreeNode 19 | * Right *TreeNode 20 | * } 21 | */ 22 | func inorderTraversal(root *TreeNode) []int { 23 | var list = new([]int) 24 | inorder(root,list) 25 | return *list 26 | } 27 | 28 | func inorder(node *TreeNode, list * []int) { 29 | if node == nil { 30 | return 31 | } 32 | inorder(node.Left, list) 33 | *list = append(*list,node.Val) 34 | inorder(node.Right, list) 35 | } 36 | 37 | -------------------------------------------------------------------------------- /LeetCode/Easy/trees/invert-binary-tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/invert-binary-tree/submissions/ 5 | Status: Success 6 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Invert Binary Tree. 7 | Memory Usage: 2.1 MB, less than 72.10% of Go online submissions for Invert Binary Tree. 8 | */ 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | func invertTree(root *TreeNode) *TreeNode { 19 | invert(root) 20 | return root 21 | } 22 | 23 | func invert(node *TreeNode) { 24 | if node == nil { 25 | return 26 | } 27 | node.Right, node.Left = node.Right, node.Left 28 | invert(node.Left) 29 | invert(node.Right) 30 | } 31 | -------------------------------------------------------------------------------- /LeetCode/Easy/trees/minimum-depth-of-binary-tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/minimum-depth-of-binary-tree 5 | Status: Success 6 | Runtime: 287 ms, faster than 50.76% of Go online submissions for Minimum Depth of Binary Tree. 7 | Memory Usage: 26.3 MB, less than 12.64% of Go online submissions for Minimum Depth of Binary Tree. 8 | */ 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | 19 | func minDepth(root *TreeNode) int { 20 | if root == nil { 21 | return 0 22 | } 23 | var ( 24 | treeLevel int 25 | q []*TreeNode 26 | ) 27 | q = append(q,root) 28 | for len(q) >0 { 29 | parentNodes := len(q) // total number of parent nodes of current level 30 | for parentNodes > 0 && len(q) >0{ 31 | currNode := q[0] 32 | q = q[1:] // remove the current node from the queue 33 | if currNode.Left == nil && currNode.Right == nil { 34 | return treeLevel+1 35 | } 36 | if currNode.Left != nil{ 37 | q = append(q,currNode.Left) 38 | } 39 | if currNode.Right != nil{ 40 | q = append(q,currNode.Right) 41 | 42 | } 43 | parentNodes-- // remove the parent node count 44 | } 45 | treeLevel++ // increase the level by 1 46 | } 47 | return treeLevel 48 | } 49 | -------------------------------------------------------------------------------- /LeetCode/Easy/trees/path-sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/path-sum 5 | Status: Success 6 | Runtime: 4 ms, faster than 87.02% of Go online submissions for Path Sum. 7 | Memory Usage: 4.6 MB, less than 94.84% of Go online submissions for Path Sum. 8 | */ 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | 19 | func hasPathSum(root *TreeNode, targetSum int) bool { 20 | if root == nil { 21 | return false 22 | } 23 | if root.Val == targetSum && root.Left == nil && root.Right == nil { 24 | return true 25 | } 26 | targetSum = targetSum - root.Val 27 | return hasPathSum(root.Left,targetSum)||hasPathSum(root.Right,targetSum) 28 | } 29 | -------------------------------------------------------------------------------- /LeetCode/Easy/trees/same-tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/same-tree 5 | Status: Success 6 | Runtime: 4 ms, faster than 12.40% of Go online submissions for Same Tree. 7 | Memory Usage: 2.1 MB, less than 69.36% of Go online submissions for Same Tree. 8 | */ 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | func isSameTree(p *TreeNode, q *TreeNode) bool { 19 | if p == nil && q == nil { 20 | return true 21 | } 22 | if p==nil || q==nil || p.Val!=q.Val{ 23 | return false 24 | } 25 | 26 | return isSameTree(p.Left,q.Left)&&isSameTree(p.Right,q.Right) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /LeetCode/Easy/trees/search-in-a-binary-search-tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/search-in-a-binary-search-tree 5 | Status: Success 6 | Runtime: 22 ms, faster than 74.25% of Go online submissions for Search in a Binary Search Tree. 7 | Memory Usage: 7 MB, less than 95.81% of Go online submissions for Search in a Binary Search Tree. 8 | */ 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | 19 | func searchBST(root *TreeNode, val int) *TreeNode { 20 | 21 | if root == nil { 22 | return nil 23 | } 24 | if root.Val == val{ 25 | return root 26 | } 27 | lTree := searchBST(root.Left, val) 28 | if lTree != nil { 29 | return lTree 30 | } 31 | rTree := searchBST(root.Right, val) 32 | if rTree != nil { 33 | return rTree 34 | } 35 | return nil 36 | } 37 | -------------------------------------------------------------------------------- /LeetCode/Easy/trees/symmetric-tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/symmetric-tree 5 | Status: Success 6 | Runtime: 6 ms, faster than 27.31% of Go online submissions for Symmetric Tree. 7 | Memory Usage: 2.9 MB, less than 87.86% of Go online submissions for Symmetric Tree. 8 | */ 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * type TreeNode struct { 13 | * Val int 14 | * Left *TreeNode 15 | * Right *TreeNode 16 | * } 17 | */ 18 | 19 | func isSymmetric(root *TreeNode) bool { 20 | if root == nil { 21 | return true 22 | } 23 | return symmetryCheck(root.Left, root.Right) 24 | } 25 | 26 | func symmetryCheck(node1, node2 *TreeNode) bool{ 27 | if node1 == nil && node2 == nil{ 28 | return true 29 | } 30 | if node1 == nil || node2 == nil { 31 | return false 32 | } 33 | if node1.Val != node2.Val{ 34 | return false 35 | } 36 | 37 | 38 | return symmetryCheck(node1.Left, node2.Right)&&symmetryCheck(node1.Right, node2.Left) 39 | } 40 | -------------------------------------------------------------------------------- /LeetCode/Medium/Array/array_rotate.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/rotate-array 5 | Status: Success 6 | Runtime: 4790 ms, faster than 5.01% of Go online submissions for Rotate Array. 7 | Memory Usage: 8.1 MB, less than 71.33% of Go online submissions for Rotate Array. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func rotate(nums []int, k int) { 14 | if len(nums) <= 1 { 15 | return 16 | } 17 | numLen := len(nums) 18 | // rotate two number at a time, we can take also take some definite number of slices such as gcd and move those at a time 19 | // instead of moving only 2 numbers at a time 20 | for j := 0; j < k; j++ { 21 | temp := nums[numLen-1] 22 | for i := 1; i < numLen; { 23 | nums[numLen-i] = nums[numLen-1-i] 24 | if numLen-2-i >= 0 { 25 | nums[numLen-i-1] = nums[numLen-2-i] 26 | } 27 | i = i + 2 28 | } 29 | nums[0] = temp 30 | } 31 | 32 | } 33 | 34 | func main() { 35 | fmt.Println("input: <>, output:") 36 | rotate([]int{1, 2, 3, 4, 5, 6, 7}, 3) 37 | } 38 | -------------------------------------------------------------------------------- /LeetCode/Medium/Array/maximum-erasure-value.go: -------------------------------------------------------------------------------- 1 | 2 | package main 3 | 4 | /* 5 | URL: https://leetcode.com/problems/maximum-erasure-value/ 6 | Status: Success 7 | Runtime: 1149 ms, faster than 8.00% of Go online submissions for Maximum Erasure Value. 8 | Memory Usage: 9.3 MB, less than 56.00% of Go online submissions for Maximum Erasure Value. 9 | */ 10 | 11 | import ( 12 | "fmt" 13 | ) 14 | 15 | 16 | // modified the https://leetcode.com/problems/longest-substring-without-repeating-characters,so varibale name might not make sense 17 | func maximumUniqueSubarray(nums []int) int { 18 | if len(nums) == 1 { 19 | return nums[0] 20 | } 21 | longestSubStr := 0 22 | startSubStrIndex := 0 23 | endSubStrIndex := 0 24 | charIndex := make(map[int]int) 25 | for idx, char := range nums { 26 | // a duplicate character found. 27 | if charOldIndex, ok := charIndex[char]; ok { 28 | if charOldIndex < startSubStrIndex { 29 | // if the duplicate char found exist before the start index, nothing to do and continue the computation 30 | } else { 31 | sum := getSumBetweenIndex(nums, startSubStrIndex, endSubStrIndex) 32 | if longestSubStr < sum { 33 | longestSubStr = sum 34 | } 35 | startSubStrIndex = charOldIndex + 1 36 | } 37 | } 38 | // keep incrementing the end index of the substring 39 | endSubStrIndex++ 40 | charIndex[char] = idx 41 | } 42 | 43 | lastSum := getSumBetweenIndex(nums, startSubStrIndex, endSubStrIndex) 44 | if longestSubStr < lastSum { 45 | longestSubStr = lastSum 46 | } 47 | return longestSubStr 48 | } 49 | 50 | func getSumBetweenIndex(nums []int, start, end int) int{ 51 | sum := 0 52 | for i:=start;i0{ 29 | if _,ok:=cntMap[cntVal];ok{ 30 | delCnt++ 31 | cntVal-- 32 | }else{ 33 | cntMap[cntVal]=struct{}{} 34 | break 35 | } 36 | } 37 | } 38 | return delCnt 39 | } 40 | -------------------------------------------------------------------------------- /LeetCode/Medium/Array/two-sum-ii-input-array-is-sorted.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 5 | Status: Success 6 | Runtime: 22 ms, faster than 27.24% of Go online submissions for Two Sum II - Input Array Is Sorted. 7 | Memory Usage: 5.5 MB, less than 50.03% of Go online submissions for Two Sum II - Input Array Is 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | 14 | func twoSum(numbers []int, target int) []int { 15 | i := 0 16 | j:= len(numbers)-1 17 | for { 18 | if i >= j { 19 | return []int{} 20 | } 21 | sum := numbers[i]+numbers[j] 22 | if sum == target { 23 | return []int{i+1,j+1} 24 | } 25 | if sum < target { 26 | i++ 27 | }else{ 28 | j-- 29 | } 30 | } 31 | return []int{} 32 | } 33 | -------------------------------------------------------------------------------- /LeetCode/Medium/LinkedList/linked_list_add_two_numbers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/add-two-numbers/ 5 | Status: Passed 6 | Runtime: 8 ms, faster than 93.28% of Go online submissions for Add Two Numbers. 7 | Memory Usage: 5.1 MB, less than 22.07% of Go online submissions for Add Two Numbers. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | type ListNode struct { 14 | Val int 15 | Next *ListNode 16 | } 17 | 18 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { 19 | listSum := make([]int, 0) 20 | reminder := 0 21 | tmp := l1 22 | for { 23 | if l1 == nil && l2 == nil && reminder == 0 { 24 | break 25 | } 26 | sum := reminder 27 | if l1 != nil { 28 | sum += l1.Val 29 | } 30 | if l2 != nil { 31 | sum += l2.Val 32 | } 33 | 34 | if sum >= 10 { 35 | listSum = append(listSum, sum%10) 36 | reminder = int(sum / 10) 37 | } else { 38 | reminder = 0 39 | listSum = append(listSum, sum) 40 | } 41 | 42 | if l1 != nil && l1.Next != nil { 43 | l1 = l1.Next 44 | } else { 45 | l1 = nil 46 | } 47 | if l2 != nil && l2.Next != nil { 48 | l2 = l2.Next 49 | } else { 50 | l2 = nil 51 | } 52 | } 53 | l1 = tmp 54 | lenSum := len(listSum) 55 | 56 | for key, val := range listSum { 57 | l1.Val = val 58 | if key == lenSum-1 { 59 | break 60 | } 61 | if l1.Next == nil { 62 | l1.Next = &ListNode{} 63 | } 64 | l1 = l1.Next 65 | } 66 | 67 | return tmp 68 | } 69 | 70 | func main() { 71 | l13 := &ListNode{3, nil} 72 | l12 := &ListNode{4, l13} 73 | l11 := &ListNode{2, l12} 74 | 75 | l23 := &ListNode{4, nil} 76 | l22 := &ListNode{6, l23} 77 | l21 := &ListNode{5, l22} 78 | 79 | list := addTwoNumbers(l11, l21) 80 | 81 | fmt.Println("list", list) 82 | } 83 | -------------------------------------------------------------------------------- /LeetCode/Medium/LinkedList/linked_list_remove_duplicate.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: 5 | Status: 6 | Runtime: <> ms, faster than <> of Go online submissions for Add Two Numbers. 7 | Memory Usage: <> MB, less than <> of Go online submissions for Add Two Numbers. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | type ListNode struct { 14 | Val int 15 | Next *ListNode 16 | } 17 | 18 | func deleteDuplicates(head *ListNode) *ListNode { 19 | node := head 20 | var prevNode *ListNode 21 | lastNonDupNodeVal := head.Val 22 | head = nil 23 | for { 24 | if node == nil || node.Next == nil { 25 | // this is needed to handle if the last node itself is duplicated 26 | if node != nil && node.Val == lastNonDupNodeVal { 27 | if prevNode != nil { 28 | prevNode.Next = nil 29 | } 30 | } 31 | if head == nil && node != nil && node.Val != lastNonDupNodeVal { 32 | return node 33 | } 34 | return head 35 | } 36 | 37 | // both node has the same value 38 | if node.Next.Val == node.Val { 39 | node = node.Next 40 | continue 41 | } 42 | 43 | } 44 | } 45 | 46 | func main() { 47 | // -1 > 1 > 3 > 3 48 | n4 := ListNode{Val: 3} // 4th node 49 | n3 := ListNode{Val: 3, Next: &n4} // 3rd node 50 | n2 := ListNode{Val: 1, Next: &n3} // 2nd node 51 | n1 := ListNode{Val: -1, Next: &n2} // 1st node 52 | 53 | resNode := deleteDuplicates(&n1) 54 | for { 55 | if resNode == nil { 56 | fmt.Println("Nil node") 57 | return 58 | } 59 | fmt.Println("Node value", resNode.Val) 60 | if resNode.Next == nil { 61 | return 62 | } 63 | resNode = resNode.Next 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /LeetCode/Medium/LinkedList/linked_list_swap_nodes_in_pairs.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/swap-nodes-in-pairs 5 | Status: Success 6 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Swap Nodes in Pairs. 7 | Memory Usage: 2.1 MB, less than 20.58% of Go online submissions for Swap Nodes in Pairs. 8 | */ 9 | 10 | type ListNode struct { 11 | Val int 12 | Next *ListNode 13 | } 14 | 15 | func swapPairs(head *ListNode) *ListNode { 16 | if head == nil { 17 | return nil 18 | } 19 | curr := head 20 | var prev, next *ListNode 21 | if head.Next != nil { 22 | head = head.Next 23 | } 24 | for { 25 | if curr == nil || curr.Next == nil { 26 | break 27 | } 28 | next = curr.Next 29 | if prev != nil { 30 | prev.Next = next 31 | } 32 | curr.Next = next.Next 33 | next.Next = curr 34 | prev = curr 35 | curr = curr.Next 36 | } 37 | return head 38 | } 39 | -------------------------------------------------------------------------------- /LeetCode/Medium/LinkedList/swapping-nodes-in-a-linked-list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/submissions/ 5 | Status: Accepted 6 | Runtime: 183 ms, faster than 83.33% of Go online submissions for Swapping Nodes in a Linked List. 7 | Memory Usage: 10.4 MB, less than 34.37% of Go online submissions for Swapping Nodes in a Linked List. 8 | */ 9 | 10 | 11 | 12 | func swapNodes(head *ListNode, k int) *ListNode { 13 | if head == nil { 14 | return nil 15 | } 16 | // handle if it is head 17 | var firstNode, lastNode *ListNode 18 | ptr := head 19 | ptr2 := head 20 | nodeLen :=0 21 | for { 22 | nodeLen++ 23 | if nodeLen == k{ 24 | firstNode = ptr 25 | } 26 | if ptr2.Next == nil { 27 | nodeLen = (2*nodeLen)-1 28 | break 29 | } 30 | if ptr2.Next.Next == nil { 31 | nodeLen= (2*nodeLen) // extra len as it has one more node 32 | break 33 | } 34 | ptr2 = ptr2.Next.Next 35 | ptr = ptr.Next 36 | } 37 | lastNodeIndex := nodeLen - k + 1 38 | ptr = head 39 | idxCnt := 0 40 | for firstNode== nil || lastNode == nil{ 41 | if ptr == nil { 42 | // some error, return as it is 43 | return head 44 | } 45 | idxCnt++ 46 | if idxCnt == k { 47 | firstNode = ptr 48 | } 49 | if idxCnt == lastNodeIndex { 50 | lastNode = ptr 51 | } 52 | ptr = ptr.Next 53 | } 54 | firstNode.Val,lastNode.Val = lastNode.Val,firstNode.Val 55 | return head 56 | } 57 | -------------------------------------------------------------------------------- /LeetCode/Medium/Trees/binary-tree-level-order-traversal.go: -------------------------------------------------------------------------------- 1 | /* 2 | URL: https://leetcode.com/problems/binary-tree-level-order-traversal 3 | Status: Success 4 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Binary Tree Level Order Traversal. 5 | Memory Usage: 2.8 MB, less than 51.13% of Go online submissions for Binary Tree Level Order Traversal. 6 | */ 7 | 8 | /** 9 | * Definition for a Node. 10 | * type Node struct { 11 | * Val int 12 | * Left *Node 13 | * Right *Node 14 | * Next *Node 15 | * } 16 | */ 17 | 18 | func levelOrder(root *TreeNode) [][]int { 19 | var ( 20 | q []*TreeNode 21 | tree = [][]int{} 22 | levelTree []int 23 | ) 24 | if root == nil { 25 | return [][]int{} 26 | } 27 | currNode := root 28 | q = append(q, root) 29 | for len(q) > 0 { 30 | parentNodes := len(q) // total number of parent nodes of current level 31 | levelTree=nil 32 | for parentNodes > 0 && len(q) > 0 { 33 | currNode = q[0] 34 | q = q[1:] // remove the current node from the queue 35 | 36 | if currNode.Left != nil { 37 | q = append(q, currNode.Left) 38 | } 39 | if currNode.Right != nil { 40 | q = append(q, currNode.Right) 41 | } 42 | parentNodes-- // remove the parent node count 43 | levelTree=append(levelTree,currNode.Val) 44 | } 45 | tree = append(tree,levelTree) 46 | } 47 | return tree 48 | } 49 | -------------------------------------------------------------------------------- /LeetCode/Medium/Trees/binary-tree-right-side-view.go: -------------------------------------------------------------------------------- 1 | /* 2 | URL: https://leetcode.com/problems/binary-tree-right-side-view/ 3 | Status: Success 4 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Binary Tree Right Side View. 5 | Memory Usage: 2.3 MB, less than 79.45% of Go online submissions for Binary Tree Right Side View. 6 | */ 7 | 8 | /** 9 | * Definition for a Node. 10 | * type Node struct { 11 | * Val int 12 | * Left *Node 13 | * Right *Node 14 | * Next *Node 15 | * } 16 | */ 17 | 18 | func rightSideView(root *TreeNode) []int { 19 | var ( 20 | tree []int 21 | q []*TreeNode 22 | ) 23 | if root == nil { 24 | return []int{} 25 | } 26 | currNode := root 27 | q = append(q, root) 28 | for len(q) > 0 { 29 | parentNodes := len(q) // total number of parent nodes of current level 30 | for parentNodes > 0 && len(q) > 0 { 31 | currNode = q[0] 32 | q = q[1:] // remove the current node from the queue 33 | 34 | if currNode.Left != nil { 35 | q = append(q, currNode.Left) 36 | } 37 | if currNode.Right != nil { 38 | q = append(q, currNode.Right) 39 | } 40 | parentNodes-- // remove the parent node count 41 | } 42 | tree = append(tree, currNode.Val) 43 | } 44 | return tree 45 | } 46 | -------------------------------------------------------------------------------- /LeetCode/Medium/Trees/populating-next-right-pointers-in-each-node.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/populating-next-right-pointers-in-each-node/submissions/ 5 | Status: Success 6 | Runtime: 16 ms, faster than 10.63% of Go online submissions for Populating Next Right Pointers in Each Node. 7 | Memory Usage: 6.8 MB, less than 49.21% of Go online submissions for Populating Next Right Pointers in Each Node. 8 | */ 9 | 10 | /** 11 | * Definition for a Node. 12 | * type Node struct { 13 | * Val int 14 | * Left *Node 15 | * Right *Node 16 | * Next *Node 17 | * } 18 | */ 19 | 20 | func connect(root *Node) *Node { 21 | if root == nil { 22 | return root 23 | } 24 | var ( 25 | q []*Node 26 | ) 27 | q = append(q, root) 28 | for len(q) > 0 { 29 | parentNodes := len(q) // total number of parent nodes of current level 30 | var prevNode *Node 31 | prevNode = nil 32 | for parentNodes > 0 && len(q) > 0 { 33 | currNode := q[0] 34 | q = q[1:] // remove the current node from the queue 35 | if prevNode != nil { 36 | prevNode.Next = currNode 37 | } 38 | if currNode.Left != nil { 39 | q = append(q, currNode.Left) 40 | } 41 | if currNode.Right != nil { 42 | q = append(q, currNode.Right) 43 | } 44 | prevNode = currNode 45 | parentNodes-- // remove the parent node count 46 | } 47 | } 48 | return root 49 | } 50 | 51 | // Best Answer 52 | func connectBest(root *Node) *Node { 53 | if root == nil { 54 | return root 55 | } 56 | connectNode(root.Left, root.Right) 57 | return root 58 | } 59 | func connectNode(left *Node, right *Node) { 60 | if left == nil { 61 | return 62 | } 63 | left.Next = right 64 | connectNode(left.Left, left.Right) 65 | connectNode(right.Left, right.Right) 66 | connectNode(left.Right, right.Left) 67 | } 68 | -------------------------------------------------------------------------------- /LeetCode/Medium/hashmap/hashmap_3Sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/3sum 5 | Status: Success. 318 / 318 test cases passed. 6 | Runtime: 1084 ms, faster than 13.20% of Go online submissions for 3Sum. 7 | Memory Usage: 9.7 MB, less than 13.30% of Go online submissions for 3Sum. 8 | */ 9 | 10 | import ( 11 | "fmt" 12 | "time" 13 | ) 14 | 15 | type numMapStruct struct { 16 | exist bool 17 | index int 18 | } 19 | 20 | func threeSum(nums []int) [][]int { 21 | var threeSums [][]int 22 | 23 | numMap := make(map[int]numMapStruct) 24 | numLen := len(nums) 25 | for index, val := range nums { 26 | // create a map of each numbers given in an array. Store the index aswell and a bool to indicate 27 | //that the number exist in the struct instead of checking it using checker (ok checker) 28 | numMap[val] = numMapStruct{ 29 | exist: true, 30 | index: index, 31 | } 32 | } 33 | // loop from first digit to the last 2nd digit 34 | for i := 0; i < numLen-2; i++ { 35 | for j := i + 1; j < numLen-1; j++ { 36 | // if the 3rd digit which is needed to form a 3 sum found to be i or j, continue with the next number 37 | if numMap[(nums[i]+nums[j])*-1].index == i || numMap[(nums[i]+nums[j])*-1].index == j { 38 | continue 39 | } 40 | if numMap[(nums[i]+nums[j])*-1].exist { 41 | // got 3 sum numbers. Sort the numbers so that we dont end up having duplicate 3 sums 42 | threeSums = sortThreeSums(threeSums, ((nums[i] + nums[j]) * -1), nums[i], nums[j]) 43 | } 44 | } 45 | } 46 | 47 | return threeSums 48 | } 49 | 50 | func sortThreeSums(threeSums [][]int, i, j, k int) [][]int { 51 | var thisNums []int 52 | if i >= j && i >= k { 53 | //i is greater 54 | if j >= k { 55 | thisNums = []int{k, j, i} 56 | } else { 57 | thisNums = []int{j, k, i} 58 | } 59 | 60 | } else if j >= i && j >= k { 61 | //j is greater 62 | if i >= k { 63 | thisNums = []int{k, i, j} 64 | } else { 65 | thisNums = []int{i, k, j} 66 | } 67 | 68 | } else { 69 | //k is greater 70 | if i >= j { 71 | thisNums = []int{j, i, k} 72 | } else { 73 | thisNums = []int{i, j, k} 74 | } 75 | } 76 | for _, sums := range threeSums { 77 | if thisNums[0] == sums[0] && thisNums[1] == sums[1] && thisNums[2] == sums[2] { 78 | return threeSums 79 | } 80 | } 81 | return append(threeSums, thisNums) 82 | } 83 | 84 | func main() { 85 | sTime := time.Now() 86 | fmt.Println("op:", threeSum([]int{-1, 0, 1, 2, -1, -4})) 87 | fmt.Println("\n op:", threeSum([]int{1, 2, -2, -1})) 88 | fmt.Println("\n op:", threeSum([]int{3, -2, 1, 0})) 89 | elapsed := time.Since(sTime) 90 | fmt.Println("time taken:", elapsed) 91 | } 92 | -------------------------------------------------------------------------------- /LeetCode/Medium/hashmap/hashmap_find_replace_pattern.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/find-and-replace-pattern/ 5 | Status: Passed 6 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Find and Replace Pattern. 7 | Memory Usage: 2.5 MB, less than 22.58% of Go online submissions for Find and Replace Pattern. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func findAndReplacePattern(words []string, pattern string) []string { 14 | matchedWords := []string{} 15 | patternLen := len(pattern) 16 | //check pattern len also 17 | if patternLen < 1 || patternLen > 50 { 18 | return matchedWords 19 | } 20 | 21 | //check pattern 22 | letterPositionMap := make(map[byte][]int) 23 | for i := 0; i < patternLen; i++ { 24 | letterPositionMap[pattern[i]] = append(letterPositionMap[pattern[i]], i) 25 | } 26 | 27 | //check each words 28 | for _, word := range words { 29 | //check each words 30 | if len(word) != patternLen || len(word) < 1 || len(word) > 50 { 31 | continue 32 | } 33 | sameWord := true 34 | wordMap := make(map[byte][]int) 35 | //get each letters count of the word 36 | for i := 0; i < patternLen; i++ { 37 | wordMap[word[i]] = append(wordMap[word[i]], i) 38 | } 39 | //for each letter and its position in the given pattern run a loop 40 | //compare pattern positions against the word position, if the first position seems to be same, check all postions of that letter 41 | for _, pVal := range letterPositionMap { 42 | if !sameWord { 43 | break 44 | } 45 | for _, wVal := range wordMap { 46 | if pVal[0] == wVal[0] { 47 | if len(pVal) != len(wVal) { 48 | sameWord = false 49 | break 50 | } 51 | for key := range pVal { 52 | if pVal[key] != wVal[key] { 53 | sameWord = false 54 | } 55 | } 56 | } 57 | } 58 | } 59 | if sameWord { 60 | matchedWords = append(matchedWords, word) 61 | } 62 | } 63 | return matchedWords 64 | } 65 | 66 | func main() { 67 | fmt.Println("output: ", findAndReplacePattern([]string{"abc", "deq", "mee", "aqq", "dkd", "ccc"}, "abb")) 68 | } 69 | -------------------------------------------------------------------------------- /LeetCode/Medium/recursive_dp/recursive_subsets.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/subsets 5 | Status: Accepted 6 | Runtime: 0 ms, faster than 100.00% of Go online submissions for Subsets. 7 | Memory Usage: 2.6 MB, less than 19.72% of Go online submissions for Subsets. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | func subsets(nums []int) [][]int { 14 | var output []int 15 | var sets [][]int 16 | getSubsets(nums, output, 0, &sets) 17 | return sets 18 | } 19 | 20 | func getSubsets(nums, output []int, index int, sets *[][]int) { 21 | if index >= len(nums) { 22 | // fmt.Printf("nums %#v, output %#v, index %d, sets %#v\n",nums,output,index, sets) 23 | // need a local output as the output gets updated in golang and mess up the list if not used 24 | var localOutput []int 25 | for _, val := range output { 26 | localOutput = append(localOutput, val) 27 | } 28 | // fmt.Printf("localOutput %#v\n",localOutput) 29 | *sets = append(*sets, localOutput) 30 | return 31 | } 32 | // exclude 33 | getSubsets(nums, output, index+1, sets) 34 | 35 | // include 36 | output = append(output, nums[index]) 37 | getSubsets(nums, output, index+1, sets) 38 | 39 | } 40 | 41 | func main() { 42 | fmt.Println("input: {1,2,3}, output:", subsets([]int{1, 2, 3})) 43 | } 44 | -------------------------------------------------------------------------------- /LeetCode/Medium/strings/string_manp_longest_substring_without_repeating_chars.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: https://leetcode.com/problems/longest-substring-without-repeating-characters 5 | Status: Success. 987 / 987 test cases passed. 6 | Runtime: 4 ms, faster than 90.16% of Go online submissions for Longest Substring Without Repeating Characters. 7 | Memory Usage: 3.2 MB, less than 42.88% of Go online submissions for Longest Substring Without Repeating Characters. 8 | */ 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | // check each characters and if a character is repeated, set the start index to 'current repeated index + 1' so that 14 | // a new sub-string count can be formed. Calculate longest substring count whenever you see the repeated character. 15 | func lengthOfLongestSubstring(s string) int { 16 | if len(s) <= 1 { 17 | return len(s) 18 | } 19 | longestSubStr := 1 20 | startSubStrIndex := 0 21 | endSubStrIndex := 0 22 | charIndex := make(map[int32]int) 23 | for idx, char := range s { 24 | // a duplicate character found. 25 | if charOldIndex, ok := charIndex[char]; ok { 26 | if charOldIndex < startSubStrIndex { 27 | // if the duplicate char found exist before the start index, nothing to do and continue the computation 28 | } else { 29 | currentSubStrLen := endSubStrIndex - startSubStrIndex 30 | if currentSubStrLen > longestSubStr { 31 | longestSubStr = currentSubStrLen 32 | } 33 | startSubStrIndex = charOldIndex + 1 34 | } 35 | } 36 | // keep incrementing the end index of the substring 37 | endSubStrIndex++ 38 | charIndex[char] = idx 39 | } 40 | currentSubStrLen := endSubStrIndex - startSubStrIndex 41 | if currentSubStrLen > longestSubStr { 42 | longestSubStr = currentSubStrLen 43 | } 44 | return longestSubStr 45 | } 46 | 47 | func main() { 48 | fmt.Println("input: zabcabcbb, output:", lengthOfLongestSubstring("zabcabcbb")) 49 | fmt.Println("input: abcabcbb, output:", lengthOfLongestSubstring("abcabcbb")) 50 | fmt.Println("input: ab, output:", lengthOfLongestSubstring("ab")) 51 | fmt.Println("input: abbac, output:", lengthOfLongestSubstring("abbac")) 52 | } 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solved Programs 2 | 3 | Some solved programs from LeetCode, CodeChef, HackerRank, HackerEarth 4 | 5 | My profile links: 6 | 7 | LeetCode : https://leetcode.com/bharathshetty4/ 8 | 9 | CodeChef : https://www.codechef.com/users/bharathshetty4 10 | 11 | HackerRank : https://www.hackerrank.com/shettybharath4 12 | 13 | HackerEarth : https://www.hackerearth.com/@bharath14 14 | -------------------------------------------------------------------------------- /go_sample.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | URL: 5 | Status: 6 | Runtime: <> ms, faster than <> of Go online submissions for Add Two Numbers. 7 | Memory Usage: <> MB, less than <> of Go online submissions for Add Two Numbers. 8 | */ 9 | // import ( 10 | // "fmt" 11 | // ) 12 | 13 | // func main() { 14 | // fmt.Println("input: <>, output:") 15 | // } 16 | --------------------------------------------------------------------------------