Daksh Gautam's Blog

30 Days of Go

October 10, 2023

The page keeps track of 30 days of Golang practice using Leetcode.

(10th Oct 2023) Problem #1 - Valid Parenthesis

  • Here is the problem link on leetcode.
  • Below you can find the source code implemented in Go
import (
    "fmt"
)
func isValid(s string) bool {
    parMap: = createParanthesisMap()
    var output[] string

    for _,
    ch: = range s {
        var singleCh string = string(ch)
        if singleCh == "{" || singleCh == "(" || singleCh == "[" {
            output = append(output, singleCh)
        } else {
            if len(output) == 0 {
                return false
            } else {
                var value string = parMap[singleCh]
                var lastEl string = output[len(output) - 1]

                if value == lastEl {
                    output = output[: len(output) - 1]
                } else {
                    return false
                }
            }
        }

    }
        if len(output) != 0 {
        return false
    }
    return true
}
func createParanthesisMap() map[string] string {
    var parMap map[string] string
    parMap = make(map[string] string)
    parMap["("] = ")"
    parMap["{"] = "}"
    parMap["["] = "]"
    parMap[")"] = "("
    parMap["}"] = "{"
    parMap["]"] = "["

    return parMap
}

(13th Oct 2023) Problem #2 - Longest Common Prefix

  • Here is the problem link on leetcode.
  • This was a great problem for me, learned a lot. Although the algorithm is pretty simple but implementation requires lots of concepts which include

    • how pointers work & what happens when we call a function with parameters ? How the parameters are copied to the function arguments ?
    • Does Golang follow copy by value or copy by reference ?

      • Everything in Go is copy by value and what you copy depends; Sometimes you copy the actual data (primitives) and sometimes you copy the pointers to the actual data. (non-primitives).
    • Understanding about Primitive vs Non-primitive data types.

      • Primitive data types are copied by value. This includes - Strings, Ints, Floats, Booleans, Arrays & Structs
      • Non-Primitive data types are also copied by value. The value they copy is the pointer to the actual data. This includes - Slices, Maps & Functions
  • I actually learned about pointers by experimenting with Golang script. Here is the link to the playground use this to play around with the script. Also providing the link to the gist in case playground link stops working.
  • Golang does not contain anything like array of character, something like this char[] which is obviously present in Java. Use alphabets []rune to create character array.
  • Here is the successfully submitted code.
import (
    "fmt"
)
type Node struct {
    // there is no char array in Golang you can use rune as char array. 
    // In Go rune type is not a character type, it is just another name for int32.

    charArr []rune
}
func longestCommonPrefix(strs []string) string {
    var nodeList []Node



    for _, v := range strs {
        // this is how you can add an element to the list. 
        // this how you can create an object during runtime
        nodeList = append(nodeList, Node {
            charArr: []rune(v),
        })
    }


    var minLength int = len(nodeList[0].charArr)

    for i := 0; i < len(nodeList); i++ {
        var node Node = nodeList[i]
        minLength = minFn(minLength, len(node.charArr)) 
    }



    var result string;
    // here you use semicolumns like other langs like
    // Java 
    for i := 0; i < minLength; i++ {
        if ifAllCharsAreSame(nodeList) == true {
            result += string(nodeList[0].charArr[0])
            removeFirstCharacterFromAllElements(nodeList)
        }
    }

    return result
}



func ifAllCharsAreSame(nodeList []Node) bool {
    var lastChar string
    for _, node := range nodeList {
        // rune is not a char. It is of int32 type. 
        var currChar string = string(node.charArr[0])
        if len(lastChar) == 0 {
            lastChar = string(currChar)
        } else {
            if lastChar == currChar {
                continue
            } else {
                return false
            }
        }
    }

    return true
}


// when you don't have return type of the function
func removeFirstCharacterFromAllElements(nodeList []Node) {
    for i := 0; i < len(nodeList); i++ {
        var nodePtr *Node = &nodeList[i]
        (*nodePtr).charArr = (*nodePtr).charArr[1:]
    }
}



// Golang does not have min function, hence you have to write your
// own min function. 
func minFn(x, y int) int {
    if (x > y) {
        return y
    }
    return x
}

Learnings (WIP)

  1. Use for _,val := range s like the foreach loop. Convert val to string in order to make character comparision.
  2. Semicolons are not used throughout the code except in for i=0; i < 123; i++ { } constructs.
  3. Golang copies everything by value.
  4. If you pass primitive data types to the function, actual data is copied. This holds true for Strings, Ints, Floats, Booleans, Arrays & Structs
  5. If you pass primitive data types to the function, pointer to the actual data is copied. This holds true for Slices, Maps & Functions

© 2023, Love you Papa, Mummy & Amma. ❤️