Friday, December 6, 2019

GoLang: Map Values retrieved as Reference or by Value ?

GoLang Map Value : By Value or Reference ?

Map data structure in GoLang is to map keys to values.

Value Retrieval

If we have a map say objects with keys as string, then we retrieve a value for any key as
objects["key"]

is Value a reference or new value?

Having come from Java background, my idea was the value retrieved from map was going to be by reference. This was not true. Value retrieved from map by above fashion actually returns new object.

So if the value in the map is some struct, then any updated on the extracted value is not reflected.

Example

In this example,
  1. we retrieve a value from a map
  2. We update the value
  3. retrieve the same value from map again
Here we can see the update is not reflected into the map. RUN THE CODE

package main

import (
  "fmt"
)

type Person struct {
  Name string
  Address string
}

func main() {
  persons := map[string]Person {
    "ginny" : Person {
      Name : "ginny",
      Address: "Hogwart",
    },
  }
  
  person := persons["ginny"]
  fmt.Println(person) // will print ginny and Hogwart as expected
  
  person.Address = "Three Brooms"
  fmt.Println(person) // will print ginny and Three Brooms as expected. But this is not updated into Map
  
  person = persons["ginny"]
  fmt.Println(person) // will print ginny and Hogwart not the updated values
}

What to do for reflecting the update into map?

If you want the update in value to be reflected into the map, then the mapping in map should be pointer.
persons := map[string]*Person
This is same example as above. Only we are using pointer values in the map. Here we are able to see that the update is reflected into the map. RUN THE CODE

package main

import (
  "fmt"
)

type Person struct {
  Name string
  Address string
}

func main() {
  persons := map[string]*Person {
    "ginny" : &Person {
      Name : "ginny",
      Address: "Hogwart",
    },
  }
  
  person := persons["ginny"]
  fmt.Println(*person) // will print ginny and Hogwart as expected
  
  person.Address = "Three Brooms"
  fmt.Println(*person) // will print ginny and Three Brooms as expected. But this is not updated into Map
  
  person = persons["ginny"]
  fmt.Println(*person) // will print ginny and Three Brooms as expected
}

Similar Other Cases

  1. Method Receiver : If a method updates the receiver, then receiver should be pointer in order to reflect the updates. RUN Example
  2. Slice : When objects from slices are retrieved and updated, update is not reflected in slice itself. Pointer should be used to reflect the update. RUN Example







Wednesday, July 24, 2019

Daily Coding Problem #292: Teams without Enemies

A teacher must divide a class of students into two teams to play dodgeball. Unfortunately, not all the kids get along, and several refuse to be put on the same team as that of their enemies.

Given an adjacency list of students and their enemies, write an algorithm that finds a satisfactory pair of teams, or returns False if none exists.
  For example, given the following enemy graph you should return the teams {0, 1, 4, 5} and {2, 3}.

  students = {
    0: [3],
    1: [2],
    2: [1, 4],
    3: [0, 4, 5],
    4: [2, 3],
    5: [3]
  }
  
  On the other hand, given the input below, you should return False.

  students = {
    0: [3],
    1: [2],
    2: [1, 3, 4],
    3: [0, 2, 4, 5],
    4: [2, 3],
    5: [3]
  }
      

Solution

The Solution is straight forward. We maintain Two Lists representing two teams. At the same time we also maintain Two Sets representing the enemies of the teams.

We iterate through all the members one by one. We insert the member into eligible list and update the enemies set as well. If we can successfully insert all the members, then we have our solution. If we are unbale to insert all memebers, then the two teams cannot be formed.

WARNING!!

The solution is not as straight forward as it sounds.
It may be possible that the team member inserted previously into any of the list might cause conflict and hence result might not be possible.
  For following example, if we iterate in the order 0, 1, 2, 3, 4, 5 we will enounter 4 is enemies in both the team.

  students = {
    0: [3],
    1: [5],
    2: [4],
    3: [0, 4, 5],
    4: [2, 3],
    5: [3]
  }

  But it has valid team division and that is: {0, 4, 5} and {1, 2, 3}.
      
So for some of the inputs, we might need to iterate in different permutation. For this reason, we need Back Tracking

Implementation

Following is implementation with back tracking.







Monday, July 8, 2019

LeetCode #632: Minimum Range

$\mathtt{Solution REFERENCE}$ @ LeetCode #632

Smallest Range : Problem Definition

This is a LeetCode Problem. You can find it HERE

Given $k$ lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each the lists.

The range $[a,b]$ is smaller than the range $[c,d]$ if $b-a < d -c$ OR $a < c\ if\ b-a == d-c$

Solution

Brute Force Solution

The straight forward solution would be to consider every possible set that includes at least one element from each of the list and find the minimum range out of those all sets.

The problem is, there are exponential number of possible sets to be considered. If we consider sets with one element from each list, then we already have $k^n$ sets. So this is not practical.

Efficient Solution

If we have a list, then to minimize the range, we either need to increase the minimum value or decrease the maxmimum value in the set.

We start by considering a set of $k$ elements which will have one item from each of the given list. At each step we keep track of $MAX$ and $Min-Range$ and it can be done in constant time $O(1)$. Now at each step, we remove the minimum element from set. To maintain constraint of having at least one element from each list, to compensate the removal of minimum element, we insert the next element from the list to which the minimum element we just removed belongs.

After each step we update $MAX$ and $Min-Range$ if necessary.

Once one of the list exhausts, we can safely return the $Min-Range$ as our result because we cannot have other lists which includes at least one element from each list.

Time and Space Complexity

Talking about Time Complexity, at the worst we will need to go through all the elements in all the $k$ lists which is O(nk) assuming each list has $n$ elements. Remember that we are removing the minimum element from the set and then push new element to it. So we must be able to identify the minimum element each time. If we iterate through all elements in the set to find the minimum, it will take $O(k)$ time. Therefore the overall time complexity will be $O(nk^2)$.

We can make this better by using $Min-Heap$. Instead of using set to store $k$ elements, we use $min-heap$ where we can find minimum element in $O(1)$ time, remove and add element in $O(logk)$ time. So the overall time complexity will be $O(nklogk)$.

The Space complexity will be $O(k)$ to store $k$ elements at each step.

Min Heap

It is not enough to store only the elements from the input lists.

When we remove an element from the heap, we should be able to identify to which list this element belongs to and at which index because after its removal we need to add next item from the same list. For this reason, items pushed into the heap should have information:
  1. actual element from lists
  2. list to which the element belongs (index)
  3. index where this element lies in the list (index)
This implies we could use array of 3 elements as an item of the heap: $[<item>, <index\ of\ list>, <index\ within\ the\ list>]$

Implementation








GoLang: Initialization before the execution of init()

Problem Definition

I have this goLang package which reads a JSON config file and sets up a map. I didn't want to call a separate method to load the file and set up the map. I wanted this to happen in the beginning automatically.
So I created init() method which loads the file and initializes the map with required configuration.

Problem

I fell into problem when I wrote unit test.

For the test I wanted to load with mocked content, not the actual file content. I actually didn't want to load the file at all.

So I created a variable fileReader as an instance of ioutil.ReadFile() method. It allows me to inject mocked file reader as dependency and execute whatever I want.

But as I said earlier, I had implemented init() method to read the file. This init() executed in the beginning before I was able to inject my mocked file reader.

Solution

Clearly the solution was to find a way to inject the dependency before the init() method executes. Fortunately I found a way to do that. Its using the following:
        // executes becore init() method so that fileReader can be injected
        var _ = func() (_ struct{}) {
          fileReader = mockedFileReader
          return
        }()
      

Code Illustration

Packakge Implementation

Test Implementation








Monday, June 17, 2019

Daily Coding Problem #332: Relationship between SUM, XOR and AND of Two Numbers

Problem Definition

Given integers $M$ and $N$, write a program that counts how many positive integer pairs $(a, b)$ satisfy the following conditions:
  1. $a + b = M$
  2. $a\ XOR\ b = N$

Solution

$\mathtt{Solution\ REFERENCE}$ @ StackOverflow

Implementation

Complexity

This implementation iterates through all the bits in $XOR$ and $AND$. If $N$ be the number of bits, then the time complexity is $\cal{O(N)}$.






Friday, May 17, 2019

PowerMockito: Mocking Private and Public Static Methods

Assume following class with private and public static methods and we want to write junit test which access those methods. We are mocking these static methods.

Mock Private Static Method

For mocking private static method we need to use

Mock Public Static Method

When mocking public static method we could use either of following:
OR
Here is the implementation

BE CAREFUL NOT USE FOLLOWING WITH PUBLIC STATIC METHOD

This will give ERROR
  org.mockito.exceptions.misusing.UnfinishedStubbingException: 
  Unfinished stubbing detected here:
  -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)

  E.g. thenReturn() may be missing.
  Examples of correct stubbing:
      when(mock.isOk()).thenReturn(true);
      when(mock.isOk()).thenThrow(exception);
      doThrow(exception).when(mock).someVoidMethod();
  Hints:
   1. missing thenReturn()
   2. you are trying to stub a final method, you naughty developer!
   3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed      
      







DeRegistration of a service removed health checks on other services?

$\mathtt{REFERENCE}$ @ GitHub Issue

Problem

I had been tyring to integrate Consul and Fabio.

I was able to run both these servers. Also I was able to register services to consul. That was reflected in Fabio as well. I was able to access the registered services through Fabio.

The problem I stuck into was when I tried to Deregister a service from consul, it did deregister but all the Checks from all other services were also gone. Because of the Fabio stopped accessing other services as well.

Solution

Well I really didn't find what was going on with Consul or Fabio.

All I did to fix this issue was Update the Consul version.

I had been using Consul Linux version 1.4.3.

I updated the consul to 1.5.0 and BOOM!! it fixed the issue.






Wednesday, May 8, 2019

Daily Coding Problem #294: Smallest Weight Strictly Ascending Then Descending Path

Problem Definition

This problem was asked by Square.

A competitive runner would like to create a route that starts and ends at his house, with the condition that the route goes entirely uphill at first, and then entirely downhill.

Given a dictionary of places of the form {location: elevation}, and a dictionary mapping paths between some of these locations to their corresponding distances, find the length of the shortest route satisfying the condition above. Assume the runner's home is location 0.

For example, suppose you are given the following input:

  elevations = {0: 5, 1: 25, 2: 15, 3: 20, 4: 10}
  paths = {
      (0, 1): 10,
      (0, 2): 8,
      (0, 3): 15,
      (1, 3): 12,
      (2, 4): 10,
      (3, 4): 5,
      (3, 0): 17,
      (4, 0): 10
  }
  


In this case, the shortest valid path would be 0 -> 2 -> 4 -> 0, with a distance of 28.

Solution using BackTracking

To solve this problem we need to go through all possible valid paths and determine the minimum weight path.

It can be solved easily with Back Tracking using recursive method.

Solution Overview

  • Start from the starting node which is 0.
  • For each of the path that can be explored from current node, travel along that path if it is valid i.e. Elevation must be valid since we must travel strictly uphill and then downhill only. Anytime we encounter invalid node, we back track and follow different path. Also if node which has already been visited in given path is encountered we should back track since it will give cycle.
  • If we can safely reach final destination node which is 0 again, we store the path summation in a list (OR update miniumum weight)
  • After we have found a path, we need to back track again since there may be many possible paths and we need to find the optimal path.

Java Implementation

Following is implementation in Java. This prints lightest weight and the path. (GoLang version solution, below prints all valid paths with their weights.)

GoLang Implementation

Following is implementation in GoLang. This solution actually prints all valid paths with their path weight. It can be easily modified to return the minimum weight path.

Complexity

This solves the problem by traversing every possible paths. So the theoretical time complexity is $O(2^n)$.

However since the question has restriction that the path has to strictly ascend and then descend, we are returning path as invalid as soon as we encounter invalid path. Because of this restriction, in practice the time complexity will be $O(n).$

Alternative Solution with Memoization

In the previous solution, we start from first node 0 and keep on exploring all possible paths all the way to destination. During the exploration we keep updating track of path sum for all paths and update the best path.

In this solution, we compute the best path and best path weight that can be attained from given node. We cache this result and use it later when we encounter the same node in other path.

This solution does not require to pass currentPath, currentPathSum, bestPath and bestWeight to findPathHelper()

Computation is done from the end. Idea is lightest tail path will be part of the solution path.
Following in implementation.

Complexity

The time complexity will be $O(n).$






Friday, May 3, 2019

Daily Coding Problem #291: Minimum Number of Boats to save population

Problem Definition

An imminent hurricane threatens the coastal town of Codeville. If at most two people can fit in a rescue boat, and the maximum weight limit for a given boat is k, determine how many boats will be needed to save everyone.

For example, given a population with weights [100, 200, 150, 80] and a boat limit of 200, the smallest number of boats required will be 3.

Solution

To be able to determine the smallest number of boats, we need to maximize the number of pairing. To maximize the number of pairing, for given weight we must pair with the maximum value possible. If we pair we smaller weight we may not get the minimum number.

For example, given a population with weights [30, 150, 170, 50] and a boat limit of 200. Here if we pair 30 with 50, then 150 and 170 are left alone hence resulting into the result 3. However, it is possible to pair 30 with 170 and 50 with 150 satisfying the constraint. This pairing will give the result 2.

Therefore, for each weight, we must pair it with the maximum weight possible. We might be tempted to use following solution:
  1. For each weight, iterate through rest of the weights to find the maximum weight with which it can be paired. Make sure to avoid already used weight.
This solution will work, but it will have time complexity $O(n^2)$

Solution Using Sorting

Following is implementation is using sorting. This method is still $O(n^2)$. It takes $O(n)$ time find pair. I am trying to figure out if the pair could be found in $O(logn)$ time instead so that the overall time complexity will be $O(nlogn)$

Implementation

Complexity

Sorting can be done in $O(n logn)$ time.
Finding a pair will take $O(n)$ time.

$\therefore$ The Time Complexity of this method will be $\cal{O(n^2)}$.






Thursday, May 2, 2019

Kruskal's MST Algorithm Using Union-Find Data Structure

$\mathtt{REFERENCE}$ @ Source Class Notes

Kruskal's Algorithm

  1. Like Prim's Algorithm, it is also a greedy algorithm.
  2. While Prim's Algorithm starts from single node and keep growing to reach a final tree, this algorithm starts with $|V|$ trees and keep on combining to finally reach the MST.

Main Features

  1. It starts with a forest of size $n = |V|$ trees.
  2. At each step, it combines two trees to obtain a bigger tree and reduces the number of tress in the forest by 1.
  3. When the forest has a single tree, it is a Minimum Spanning Tree (MST).
Use Union-Find data structure to make it faster.

Formal Sketch of Kruskal's MST Algorithm

  1. $A = \phi$ // A is an empty forest
  2. Sort the edges in the graph in increasing order of the weight.
  3. for each edge $(u,v) \in G.E$ in increasing order of weight {
    1. if $u$ and $v$ are not already connected (find by using Union-Find) {
      1. $A = A \cup \{(u,v)\}$
      2. UNION(u,v) // Union-Find operation
      }
    }
  4. return A

Implementation

Following is the implementation of above explanation.

Complexity

  • Sorting takes $O(|E|log|E|)$ times
  • Union-Find operations can be done in $O(log|V|)$ time if properly implemented
$\therefore$ The Time Complexity of this method will be $O(|E|log|E|)$ time.

for dense graph, $|E| \approx |V|^2 \Rightarrow$ SLOW
for sparse graph, $|E| \approx |V| \Rightarrow$ FAST






Wednesday, April 17, 2019

Look And Say or Count And Say Sequence

$\mathtt{REFERENCE}$ @ LeetCode

This is a LeetCode Problem. You can find it HERE

Problem Definition

This problem is actually generation of $look-and-say\ sequence$. DESCRIPTION
The count-and-say sequence is the sequence of integers with the first five terms as following:

 1.     1
 2.     11
 3.     21
 4.     1211
 5.     111221
 
 1 is read off as "one 1" or 11.
 11 is read off as "two 1s" or 21.
 21 is read off as "one 2, then one 1" or 1211.

Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.
  

Solution

Then $nth$ sequence is generated using $(n-1)th$ sequence. So the obvious solution would to go on generating sequences starting from $n=1$ for which the $sequence = 1$.

Algorithm to generate a sequence from previous sequence is simple.
  1. Traverse through previous sequence character by character.
    1. Maintian the count of repeated character.
    2. When a new character is encountered, append to result the $count$ and the $character$.
  2. Return result.
We will have to repeat this algorithm until the required sequence is generated.

P.S. When I was tyring to solve this problem, I was looking for more efficient solution. More specifially I was looking for a pattern so that I could directly generate the $nth$ sequence without computing the intermediate sequences. As it turns out, there is no such solution. So the process described above is the actual solution to this problem.

Implementation

Following is the implementation in $GoLang$.

Important thing to keep in mind during the implementation is the generation of intermediate strings. Be careful to generate intermediate and final sequence in $\cal{O(n)}$ time.

Complexity

Method countAndSay() runs for $\cal{O(n)}$ time $n$ being the $nth$ sequence number.

Method compute() which computes current sequence using previous sequence, runs for $\cal{O(m)}$ time where $m$ is number of characters in previous sequence.

Assuming $m=n$, The Time Complexity of this solution will be $\cal{O(n^2)}$.






Tuesday, April 16, 2019

String in GoLang

$\mathtt{REFERENCE}$ @ Blog.GoLang.Org

  • The BLOG explains how slices work in Go
  • This post is more or less summary of Go string
  • Efficient use of string requires understanding not only how they work, but also
    1. the difference between a byte, a character and a rune
    2. the difference between Unicode and UTF-8
    3. the difference between a string and a string literal
    4. and other even more subtle distinctions
"When I index a Go string at position n, why don't I get the nth character?" As you'll see, this question leads us to many details about how text works in the modern world."
An excellent introduction to some of these issues, independent of Go, is Joel Spolsky's famous blog post, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).

What is string?

  1. In Go, a string is in effect a read-only slice of bytes.
  2. It's important to state right up front that a string holds arbitrary bytes. It not required to hold Unicode text, UTF-8 text or any other predefined format. As far as the content of a string is concerned, it is exactly equivalent to a slice of bytes

Code Points, Characters and Runes

  1. As mentioned above, a string holds bytes.
  2. The idea of $Character$ is a little hard to define. The Unicode standard uses the term $Code Point$ to refer to the item represented by a single value. The code point U+2318, with the hexadecimal value 2318, represents the symbol ⌘. The concept of $Character$ in computing is ambiguous or at least confusing.
  3. $Code Point$ is a bit of a mouthful, so Go introduces a shorter term for the concept: $rune$. It means exactly the same as $Code Point$ with one interesting addition. The Go language defines the word rune as an alias for the type int32, so programs can be clear when an integer value represents a code point. Moreover, what you might think of as a character constant is called a rune constant in Go. The type and value of the expression '⌘' is rune with integer value 0x2318.

Range Loops

  1. With a regular $for$ loop, we get bytes of the string
  2. A $for\ range$ loop, by contrast, decodes one UTF-8-encoded $rune$ on each iteration. Each time around the loop is the starting position of the current rune, measured in bytes and the $Code\ Point$ is its value.







Thursday, April 11, 2019

Print given String in ZigZag Fashion

Problem Definition

Given a string and a number of lines $k$, print the string in zigzag form.

In zigzag, characters are printed out diagonally from top left to bottom right until reaching the $kth$ line, then back up to top right, and so on.
For example, given the sentence "thisisazigzag" and k = 4, you should print:
t     a     g
 h   s z   a
  i i   i z
   s     g

Solution

The solution to this problem would be to construct $k$ lines and print them.

Key Problem

Construction of each of the line is the key part of this problem. Each line would consist necessary characters from the $input\ string$ separated by required number of $spaces$. To construct each line we need to identify characters belonging to the line and number of spaces to be inserted after/before each of the characters.

Basic Algorithm

To construct each line,
  1. Insert necessary number of spaces in the beginning of the line
  2. Identify next character that belongs to this line and append to it
  3. Append necessary number of spaces
  4. Go to step 2, if there are more characters that belong to this line, otherwise print the line and move on to next line

Identify Size of spaces and Next Belonging Character

Assuming $0\ index$ based line numbers.
  1. For $ith\ line$, number of spaces that starts the line $=\ i$
  2. Index (say $index$) of first character that belong to $ith\ line = i$
  3. Number of spaces that follows after a character depends upon whether we are moving $up\ or\ down$. For simplicity we can assume that at character on first line $i = 0$, we are always moving $down$, while for the last line $i = k-1$, we are always moving $up$. For other lines we will be alternatively moving $up$ and $down$ starting from moving down because initially we are moving down.
              If we are moving up,
                 gapSize = 2 * i - 1
    
              Else if we are moving down,
                 j = k - i - 1
                 gapSize = 2 * j - 1
            
  4. Index of next character will be $index = index + gapSize + 1$

Implementation

Following is the implementation as described above.

Complexity

Ignoring the time complexity to construct string of empty spaces, the time complexity of this implementation is $O(n)$ because we go through each of the characters in the input string only once.