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.






Monday, November 19, 2018

Leetcode 189: Rotate Array to the Right by K Times

$\mathtt{REFERENCE}$ @ LeetCode

Problem Definition

You are given an array and integer $k$ (>= 0). The problem is to rotate the input array to the right by $k$ times. Details can be found at LeetCode.

Example

Input: [1,2,3,4,5,6,7] and k = 3

Output: [5,6,7,1,2,3,4]

Solution 1 : Using Auxiliary Array of Size Same as Input Array.

In this method we go on saving the elements to the new rotated location in the auxiliary array. Finally when all elements are rotated to their proper indices, all elements are copied back to the original array in the same order as they appear after rotation.

Complexity

This method takes $\cal{O(n)}$ Time and $\cal{O(n)}$ Space.

Implementation

Solution 2 : Using Auxiliary array of size k

In the first solution we have used auxiliary array of size same as input to store rotated elements. If we look carefully, we can move in place those elements which can be pushed to right from left. Only those rightmost $k$ elements which can not be moved right cannot be moved in place because they have potential to replace the elements which have not been moved.

So it is sufficient to save only the right most $k$ elements in the auxiliary space. This will reduce the space requirement from ${O(n)}$ to ${O(k)}$.

In this method we use auxiliary array of size $k$ only. Rotation of the first $(N - k)$ elements will be done in place. Rotation of the last $k$ elements is stored in the auxiliary array. Once all elements are done, elements from the auxiliary array are copied in the front of input array.

Complexity

This method takes $\cal{O(n)}$ Time and $\cal{O(k)}$ Space.

Implementation

Solution 3 : Using Reversal Algorithm

The solutions we discussed above uses auxiliary array of some size to solve the problem. Hence they have certain extra space requirement.

Here we are going to discuss a solution that does not use any extra space. So this is a constant space solution.

Here we divide the input array into two parts
  1. First $(N - k)$ elements
  2. and Last $k$ elements
Now,
  1. Reverse the first part of the array.
  2. Reverse the second part.
  3. Reverse the whole array. Result will the required rotation of the array by $k$ times to the right.

Complexity

In this method we have managed to reduce the space complexity from O(n) to a constant space. This method still takes $\cal{O(n)}$ Time but $\cal{O(1)}$ Space.

Implementation