Thursday, June 14, 2018

Pushing Your Local Copy of JAR into the Local Maven Repository

$\mathtt{REFERENCE}$ @ Reference

If you understand the layout of the Maven repository, you can copy the jar directly into where it is meant to go. Maven will find this file next time it is run.

If you are not confident about the layout of the Maven repository, then you can adapt the following command to load in your jar file, all on one line.

     mvn install:install-file
          -Dfile=<path-to-file>
          -DgroupId=<group-id>
          -DartifactId=<artifact-id>
          -Dversion=<version>
          -Dpackaging=<packaging>
          -DgeneratePom=true
 
  Where: <path-to-file>  the path to the file to load
            <group-id>      the group that the file should be registered under
            <artifact-id>   the artifact name for the file
            <version>       the version of the file
            <packaging>     the packaging of the file e.g. jar
  

Example

If you have a jar file example.jar, then following command

     mvn install:install-file
          -Dfile=path/to/example.jar
          -DgroupId=com.hogwart
          -DartifactId=sample
          -Dversion=1.0.0
          -Dpackaging=jar
          -DgeneratePom=true

  
will generate following directory structure in the local maven repository:

~/.m2/repository/com/hogwart/sample/1.0.0/sample-1.0.0.jar






Monday, June 11, 2018

7 Steps to solve a Dynamic Programming Problem

$\mathtt{REFERENCE}$ @ Medium

$\mathtt{REFERENCE}$ @ Refdash

I loved the way the article has explained on how to proceed with Dynamic Programming. I am listing some key points from the article (for my own reference).

7 Steps to solve a Dynamic Programming Problem

  1. How to recognize a DP problem
  2. Identify Problem variables
  3. Clearly Express the reccurrence relation
  4. Identify the base cases
  5. Decide if you want to implement it iteratively or recursively
  6. Add memoization
  7. Determine time complexity

Step 1: How to recognize a Dynamic Programming problem

Recognizing a Dynamic Programming problem is often the most difficult step in solving it. Can the problem solution be expressed as a function of solutions to similar smaller problems?
First, let’s make it clear that DP is essentially just an optimization technique. DP is a method for solving problems by breaking it down into a collection of simpler subproblems, solving each of those subproblems just once, and storing their solutions. The next time the same subproblem occurs, instead of recomputing its solution, one simply looks up the previously computed solution. This saves computation time at the expense of a (hopefully) modest expenditure in storage space.

Recognizing that a problem can be solved using DP is the first and often the most difficult step in solving it. What you want to ask yourself is whether your problem solution can be expressed as a function of solutions to similar smaller problems.

Step 2: Identify problem variables

After identifying some recursive structure between our subproblems, we need to express the problem in terms of the function parameters and see which of those parameters are changing.

A way to determine the number of changing parameters is to list examples of several subproblems and compare the parameters. Counting the number of changing parameters is valuable to determine the number of subproblems we have to solve, but it is also important in its own right in helping us strengthen the understanding of the reccurrence relation from step 1.

Step 3: Clearly express the recurrence relation

Once you figure out that the recurrence relation exists and you specify the problems in terms of parameters, this should come as a natural step. How do problems relate to each other? In other words, let’s assume that you have computed the subproblems. How would you compute the main problem?

Step 4: Identify Base Cases

A base case is a subproblem that doesn’t depend on any other subproblem. In order to find such subproblems, you typically want to try a few examples, see how your problem simplifies into smaller subproblems, and at what point it cannot be simplified further.

The reason a problem cannot be simplified further is that one of the parameters would become a value that is not possible given constraints of a problem.

Step 5: Decide if you want to implement it iteratively or recursively

Step 6: Add memoization

Step 7: Determine Time complexity


Implementation for Problem Discussed in the Reference Page








Friday, June 8, 2018

Longest Substring without Repeating Characters

$\mathtt{REFERENCE}$ @ This is a LeetCode Problem.

Problem Description

Given a string. We need to find the sub string of unique characters with longest length.

Examples

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Solution 1: Brute Force Solution

An obvious solution would be to consider all the substrings and return the maximum length. The implementation is also obvious. From each position of the string, we compute the substring with unique characters. Finally we return the length of maximum size substring.

Complexity

We are computing substring and each of the location. To compute a substring at a location, we might need to traverse the whole string. So the time complexity of this approach will be $O(n^2)$. The space complexity is $O(1)$.

Solution 2: Efficient Solution

This problem can be solved efficiently using two pointers.
  1. Set two pointers start = 0 and cursor = 0.
  2. Keep increasing cursor until we encounter unique characters.
  3. When a duplicate character is encountered
    1. Compute length of the substring of unique characters based upon start and cursor value and update max length.
    2. Move the pointer start towards right until the repeated character is encountered.
  4. Repeat steps 2 and 3 until the end.


Implementation

Complexity

By this method, we access each of the characters in the string twice - once by the pointer cursor and other by the pointer start. Hence, the time complexity of this approach is $O(n)$. The space complexity remains O(1). To mark the visited characters we have used a fixed size array.






Find Two Missing Numbers in the given Array

$\mathtt{PRE-REQUISITE}$ @ One Missing Number in an Array

Task Description

Given an array of integers which contains numbers from [1,n] except two numbers. We need to find those two missing numbers.

Example

Sample Input 1:
input_array = [1, 2, 7, 9, 3, 6, 4]
Sample Output 1:
missing numbers = 5, 8
Sample Input 2:
input_array = [2, 7, 9, 3, 6, 4, 5, 8]
Sample Output 2:
missing numbers = 1, 10

Naive Solution, Hashing Solution and Sorting Solution

If the size of input array is $n$, then we are looking for the numbers $[1,\ N]]$ inclusive where $N = n + 2$.

Similar to the Single Missing Number Problem, the Naive solution, Hashing solution and Sorting solution can be implemented in the similar fashion with similar Time and Space Complexity. The changes to be made are minor. Can you try it?

Solution 2: Using Sum of Numbers and XOR Together

Sum of numbers method and XOR of numbers method can not be applied alone to compute the two missing numbers. However, we can combine those two methods to get our result.

Principle - Part 1 (Compute Pivot)

If $x$ and $y$ be the two missing numbers, then it can be guaranteed that the two numbers will lie on the either side of a $Pivot$ number because we are talking about Unique Numbers from $1$ to $N$, and $x$ and $y$ are also Unique.
We can safely choose the $Pivot$ number to be $Pivot = (x+y)/2$.

$x+y$ can be computed by the Sum of Numbers technique we applied in Single Missing Number Problem to compute single missing number. The same method here will give us the sum of two missing numbers. After we have the sum, we can compute $Pivot = sum / 2$

Principle - Part 2 (Compute Missing Numbers)

After we have chosen the $Pivot$ number we can compute the missing number on the either sides by using XOR technique.

The missing number in the lower half can be computed by computing XOR of
  1. all numbers from $1$ to $Pivot$, and
  2. all numbers $\le Pivot$ in the input array
The final result will be the missing number in Lower Half.

Similarly, the missing number in the uppoer half can be computed by computing XOR of
  1. all numbers from $Pivot + 1$ to $N$, and
  2. all numbers $\gt Pivot$ in the input array
The final result will be the missing number in Upper Half.

Implementation

Following the implementation of above principle:







Find a missing number in given array containing numbers 1 to n

Task Description

Given an array of integers which contains numbers from [1,n] inclusive except One number. We need to find that missing numbers.

Example

Sample Input 1:
input_array = [1, 2, 7, 9, 3, 6, 4, 8]
Sample Output 1:
missing number = 5
Sample Input 2:
input_array = [1, 2, 7, 9, 3, 6, 4, 5, 8]
Sample Output 2:
missing number = 10

Solution 1: Naive Solution

If the size of the input array is $n$, then we are looking for the numbers in the range $[1,\ N]$ inclusive where $N\ =\ n\ +\ 1$.

The naive solution will be to run a loop from $1$ to $N$ and for each number, we look into the given array to check if it exist or not. Whenever we encounter a number that does not exist in the input array, we have our solution.

Implementation

Complexity

In this solution, for each number from $1$ to $N$, we check if it exists in the given input array which takes $O(n)$ time and we are repeating this for $N$ number of times. $\therefore$ The time complexity of this solution is $O(n^2)$.

This solution doesn't require any extra data structure. So the space complexity is $O(1)$.

Solution 2: Hashing the numbers

In the above solution, we see that checking if a number exist in the input array takes $O(n)$ time. If we are able to improve this lookup time, then we could have better time complexity.

To improve the lookup time, we can store the input numbers into a HashMap. In this case, we know that we are going to check for the numbers $1$ to $N$. So we could also use a Boolean Array of size N to store whether a number exist in the array or not.

Implementation

Complexity

After hashing we can verify if the number exists in the input array in constant O(1) time and we do this for all numbers in the array. $\therefore$ The time complexity of this solution is $O(n)$.

However, we have introduced extra space for hashing whose size is equal to the number items in the input array. So the space complexity is also $O(n)$.

Solution 3: By Sorting Input Array

We can also solve this problem by sorting the input array. Once sorted, we can identify the missing number simply by traversing the sorted array.

Implementation

Complexity

Sorting takes $O(nlogn)$ time and traversing the sorted array takes $O(n)$ time. $\therefore$ The time complexity of this solution is $O(nlogn)$.

This solution doesn't require any extra data structure. So the space complexity is $O(1)$.

Solution 4: Using Sum of Numbers

We know that if the size of the input array is $n$, then we are looking for the numbers in the range $[1,\ n+1]$.

Sum of this range $S_N=\ \frac {N \times (1 + N)}{2}$

Now, if $S$ be the sum of all numbers in the input array and $x$ is a missing number in the array, then $S_N - S = x$. We can use this to easily identify the missing number.

Implementation

Complexity

We need to traverse through the input array only once to sum all the numbers. $\therefore$ The time complexity is $O(n)$.

This solution doesn't require any extra data structure. So the space complexity is $O(1)$.

Solution 4: Using XOR of Numbers

We know that if the size of the input array is $n$, then we are looking for the numbers in the range $[1,\ n+1]$.

Also,
  1. if we XOR a number to itself, then the result is $0$. i.e. $x\ ^\ x = 0$.
  2. if we XOR a number to $0$, the the result is the number itself.
So, if we compute XOR of all the numbers from $1$ to $N$ and also all the numbers in the input array, we are XORing all the numbers twice except the missing number. Hence, the result is going to be the missing number.

Implementation

Complexity

We need to traverse through the input array only once to XOR all the numbers. $\therefore$ The time complexity is $O(n)$.

This solution doesn't require any extra data structure. So the space complexity is $O(1)$.






Thursday, June 7, 2018

Mocking Non-Static Private Method Using PowerMockito

$\mathtt{RELATED\ TOPICS}$ @ Mocking Static Private method Mockito does not support the mocking of Private Methods. However, we can use PowerMockito that extends Mockito. Private methods may be mocked by following ways:

Test Class Setup

Test class should be anotated with @RunWith(PowerMockRunner.class) and @PrepareForTest({ClassWithPrivateMethod.class}).

When a class is annotated with @RunWith or extends a class annotated with @RunWith, JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit [REF].

@PrepareForTest tells PowerMockito to prepare listed classes for testing. Classes needed to be defined using this annotation are typically those that needs to be byte-code manipulated. This includes final classes, classes with final, private, static or native methods that should be mocked and also classes that should be return a mock object upon instantiation.

Mocking Private Method

A Private Method can be mocked in following way:

  ClassWithPrivateMethod instance = new ClassWithPrivateMethod();
  ClassWithPrivateMethod spy = PowerMockito.spy(instance);  // IMPORTANT its NOT Mockito.spy()

  PowerMockito.doReturn().when(spy, "PRIVATE_METHOD_NAME", );
  

Example

Consider a following utility class.

  public class StockDetails {

    //------------------------------------------------------------------------

    /**
     * Returns details of Stock corresponding to stockNumber
     * @param stockNumber stock number whose detail is to be found
     * @return array of strings representing stock detail
     *           array[0] = stockNumber
     *           array[1] = Stock Description
     *           array[2] = price
     *         null if stock detail is not found
     */
    public String[] getStockDetails(String stockNumber) {
      try {
        String stockDetail = requestStockDetails(stockNumber);

        String[] components = stockDetail.split("---");
        if (components[0].equals("SUCCESS")) {
          return new String[]{stockNumber, components[1], components[2]};
        }
      } catch (Exception e) {}
      return null;
    } // getStockDetails

    //------------------------------------------------------------------------

    /**
     * Retrieves the stock details from the stock information
     * server
     *
     * @param stockNumber
     * @return stock detail in json format
     */
    private String requestStockDetails(String stockNumber) {
      String stockDetail = "";

      //
      // logic for making HTTP request or any other request
      // made to the server to retrieve the stock detail
      //

      return stockDetail;
    } // requestStockDetails

    //------------------------------------------------------------------------

  } // StockDetails

  
Here I am going to write JUnit method to verify the method getStockDetails() which depends upon the private method requestStockDetails().

This private method makes an HTTP request to retrieve some results. We don't want the real HTTP request made for the unit test. So, we will need to mock this private method. Following is the implementation of the JUnit test which mocks the private method.

    import junit.framework.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;

    /**
     * @author Sabbir Manandhar
     * @version 1.0
     */
    @RunWith(PowerMockRunner.class)
    @PrepareForTest({StockDetails.class})
    public class StockDetailsTest {

      @Test
      public void testGetStockDetails() throws Exception {
        String stockNumber = "LKSJf289447OIOIJ";
    
        StockDetails stockDetails = new StockDetails();
        StockDetails spy = PowerMockito.spy(stockDetails); // Make SURE you use PowerMockito.spy()

        PowerMockito.doReturn("SUCCESS---This is the most active stock last week---2500.00")
                .when(spy, "requestStockDetails", stockNumber);

        String[] details = spy.getStockDetails(stockNumber); // This will execute actual method getStockDetails() in stockDetails instance,
                                                             // but requestStockDetails() inside this method will be mocked result
        Assert.assertEquals(stockNumber, details[0]);
        Assert.assertEquals("This is the most active stock last week", details[1]);
        Assert.assertEquals("2500.00", details[2]);
      }
    } // StockDetailsTest

  

Warning - Using Mockito.spy() instead of PowerMockito.spy()

Its important that you use PowerMockito.spy() while creating spy object for the actual stockDetails instance in the test method.

If you use Mockito.spy() method, then you are going to get an Exception.

   java.lang.NullPointerException
      at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:67)
       at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.prepareForStubbing(PowerMockitoStubberImpl.java:124)
       at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:92)
       at com.hogwart.StockDetailsTest.testGetStockDetails(StockDetailsTest.java:34)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
       at java.lang.reflect.Method.invoke(Method.java:498)
       at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
       at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
       at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
       at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
       at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
       at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
       at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
       at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
       at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
       at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
       at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
       at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
       at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
       at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
       at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
       at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)








Sunday, June 3, 2018

Maximum Size Square Sub Matrix with All 1's

$\mathtt{REFERENCE :}$HERE.

Problem Definition

Given a 2D $m \times n$ binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Example
  Input 

  1 0 0 1 1 0 0
  1 1 1 0 0 0 0
  1 1 1 1 1 1 0
  0 0 1 1 1 1 1
  1 1 1 1 1 1 1
  1 1 1 1 1 1 1

  Output
  16

Solution 1: Naive Solution

The naive solution will be to find maximum size square from each of the cell considering them as the TOP-LEFT corner of the square and finally return the maximum size.


  • Iterate through each of the cell in the given matrix
    • Consider each cell as the TOP-LEFT corner of a square. Then we go on to explore the maximum size square that it can form. The question is how do we explore?
      • If the current cell has value 0, then we don't need to explore at all. Size of square it can form is 0.
      • Else if the value is 1, then we go to the diagonally LEFT-DOWN cell. If this cell has value 1, then we check if all the cells in the column (in the left of it) and row (above it) are 1 or not (Boundary being the row and column value of current cell being considered). If all cells are not 1s, we have found the maximum square and return. But if all cells have value 1, we go on to next diagonal LEFT-DOWN cell and repeat the process.
  • Finally return the maximum size found.

Implementation

Complexity

We repeat the exploration process for each cell. There are $mn$ number of cells in the given matrix and the exploration of each cell can take $O(mn)$ time.$\therefore$ Total time complexity of this method $O((mn)^2)$.

As for space, it does not use any extra data structure. So its space complexity is $O(1)$

Solution 2: Dynamic Programming Solution

If the currently considered cell has a value 1, the minimum size of the square it can form is 1. To find the maximum size, we need to look into its neighbor cells at RIGHT, DOWN and RIGHT-DOWN (Assuming currently considered cell is the TOP-LEFT corner of the square)

If all the three neighbors are square of size 1, then the current cell will form square of size 2.


If any one of the three neighbors is square of size 0, then the currently considered cell can form square of size 1 only.


What will be the maximum size square if the neighbors are the square of size greater than 1.



In the example above:
  1. Right Neighbor forms square of size 3
  2. Right-Down Neighbor forms square of size 4
  3. Down Neighbor forms square of size 2
From the figure, it is obvious that the square formed by current cell is 3.

Can we compute this value from the neighbor values? YES!! The value can be computed from neighbors as follows:
size of square that current cell can form = 1 + Minimum(size of neighbors)

Base Case



Since the bottom Row and right most column don't have cells to form square, number in them, either 0 or 1 is the maximum size of the square they can form.

Implementation

Since we will be using each of the cell as the TOP-LEFT corner of the square they can form, we can start the computation from the RIGHT BOTTOM because their value will not depend upon the values above them or left to them. We can then move towards left or up.

For this implementation we will need to maintain Auxiliary Matrix of the same size as the input matrix to hold the sizes of the square that each cell can form.

Complexity

With this method, we will be traversing through each of the cells only once. For the computation of current cell, we need to access at max three other cell values. So, the Time Complexity of this method is $O(mn)$.

As for space, we are using extra matrix of same size as an input. Thus the space complexity is also $O(mn)$.

Solution 3: Better Dynamic Programming Solution, O(n) Extra Space

In the previous implementation, we can see that we are using the Auxiliary Matrix to access only 3 of previous values to compute value for current cell. Hence, we don't need the whole matrix all the time. It is sufficient to store the result of one row at a time.For every row, when we traverse from right to left, the Auxiliary Array is also updated from right to left.
if size[] be the auxiliary array,

For any cell matrix[r][c],

size[c+1] represents Right Neighbor
size[c] represents Down Neighbor, and
prev (previous value of size[c]) represents Diagonal Neighbor