Arrays & Slices Flashcards
Append slice in 2D slice without replacing
ans = append(ans, append([]int{}, subset…))
Create 2D slice
var ans [][]int
ans = make([][]int, 0)
then each internal slice needs to be initialized as separate memory to avoid overriding.
Pass new empty slice to a function call
functionCall(A, 0, make([]int, 0))
or
functionCall(A, 0, []int{}) // seems more expensive here?
Passing slice by reference to function
slices are already pass by reference. Slices are passed by value, but their value is just a length and a pointer to an array
Create slice using make
ans := make([]int, len(array))
b := make([]int, 0, 5) // len(b)=0, cap(b)=5
initialize a map
dups := make(map[int]bool)
m := map[int]string{}
level order traversal iterative
func LevelOrder(root *BinaryTree) {
queue := []*BinaryTree{}
queue = append(queue, root)
res := []int{}
for level := 0; len(queue) > 0; level++ {
size := len(queue)
for i := 0; i < size; i++ { curr := queue[0] queue = queue[1:] res = append(res, curr.Value) if curr.Left != nil { queue = append(queue, curr.Left) } if curr.Right != nil { queue = append(queue, curr.Right) } } } }
Queues using slices
queue := make([]int, 0)
// Push to the queue
queue = append(queue, 1)
// Top (just get next element, don’t remove it)
x = queue[0]
// Discard top element
queue = queue[1:]
// Is empty ?
if len(queue) == 0 {
fmt.Println(“Queue is empty !”)
}
Stack using slices
type Stack []string
func (s *Stack) Push(str string) {
s = append(s, str)
}
func (s Stack) Pop() (string, bool) {
if len(s) == 0 { // is empty
return “”, false
} else {
index := len(s) - 1 // Get the index of the top most element.
element := (s)[index]
s = (s)[:index] // Remove it from the stack by slicing it off.
return element, true
}
}
Min and Max Values of Integers
math.MinInt, math.MaxInt
math.MinInt64, math.MaxInt64
math.Inf(1)
Absolute Value
func Abs(y float64) float64
math.Abs(-3)
Max and Min library functions
import “math”
func Max(a, b float64) float64
func Min(x, y float64) float64
Standard input sorting
import “sort”
str := []string{“c”, “a”, “b”}
sort.Strings(str)
ints := []int{7, 2, 4}
sort.Ints(ints)
Sort a string characters
word := “1BCagM9”
s := []rune(word)
sort.Slice(s, func(i int, j int) bool { return s[i] < s[j] })
fmt.Println(string(s))
Output: 19BCMag
TC: O(NlogN) , golang uses optimized version of quicksort
Check if input is already sorted
import “sort”
ints := []int{1,2,3}
check := sort.IntsAreSorted(ints)
fmt.Println(“Sorted: “, check)
Output:
Sorted: true