Friday, January 2, 2015

Count bounded slices using minimum queue data structure

Brought up by a friend Peng Li (http://allenlipeng47.com/PersonalPage/index/view/99/nkey), I have been thinking about this google interview problem for a while. Here is the problem statement:

Consider the array 3 5 7 6 3. 

Return the pair of indices that forms the slice where the difference between the maximum and minimum in the slice <= 2. 

Output: 
(0,0) (1,1) (2,2) (3,3) (4,4) (5,5) 
(0,1) (1,2) (1,3) (2,3) 

Obviously the brute force is to look up all possible sublists (O(n^2) and find min and max of each (O(n)) and check then print out result. The output result step will always take O(n), let's forget about that and focus on the sublists finding step. So this is O(n^3). 

Further optimizing is to use sliding or crawling window in stead of blindly checking all possible sublists , since we can shrink window once the sublist is not qualified, and expand the window after qualified sublist if found. That is O(n^2). 

So can we find min/max in each sliding window in O(1) time? If we can, that will further reduce the time complexity to O(n).

There is an incredible post on careercup.com about the solution. http://www.careercup.com/question?id=5090693043191808. All credits should go to the author in the discussion thread. 

Let's focus on find the minimum. Actually the problem essentially comes down to a data structure called minimum queue, which can find minimum value in the FIFO queue in O(1) time at any given time. To implement this kind of queue, we will use another data structure called minimum stack, which can find minimum value in the LIFO order in O(1) time. Combining a queue implementation with two stacks, we have our minimum queue implementation! 

The take-home message of this problem is all of complicated coding problems are built on top of fundamentals like data structure (list, stack, queue, tree, hash) or search algorithms (binary search).   There are thousands of hard coding problems, but there are only dozens or few hundreds of data structures and algorithms. 

public static List<Pair> countSlices(int[] numbers, int k){  
    if(numbers==null)
        return null;
    List<Pair> list = new ArrayList<Pair>();  
                    //p0, p1 defines the sliding windows
    int p0=0, p1=0, len = numbers.length;
    MQueue q = new MQueue();
    q.enqueue(numbers[p1]);
    while(p0<len && p1<len && p0<=p1){     
     int min = q.min();
     int max = q.max();
     if(max-min<=k){
     for(int p=p1; p>=p0; p--){
                list.add(new Pair(p1, p));
            }  
     p1++;//expand sliding window
     if(p1<len) q.enqueue(numbers[p1]);
     }else{
     p0++;//shrink sliding window
     q.dequeue();
     }
    }
    return list;
}

static class Pair{
int i; int j;
Pair(int i1, int j1){i = i1; j = j1;}
@Override
public String toString(){
return "("+i+"-"+j+")";
}
}

//a stack node which contains min and max of all underlying elements
static class MNode {
Integer i, min, max;
MNode(int i, int max, int min){this.i = i;this.max=max; this.min=min;}
}
//a stack(LIFO) can track min and max of all elements in amortized O(1) time
static class MStack {
Stack<MNode> s = new Stack<MNode>();
public boolean isEmpty(){
return s.isEmpty();
}
public int min(){
if(s.isEmpty())
return Integer.MAX_VALUE;
return s.peek().min;
}
public int max(){
if(s.isEmpty())
return Integer.MIN_VALUE;
return s.peek().max;
}
public void push(int i){
int max=Math.max(i, max());
int min=Math.min(i, min());
s.push(new MNode(i, max, min));
}
public int pop(){
return s.pop().i;
}
}
//a queue(FIFO) can track min and max of all elements in amortized O(1) time 
static class MQueue{
MStack s_new = new MStack(), s_old = new MStack();
public void enqueue(int i){
s_new.push(i);
}
public int dequeue(){
if(s_old.isEmpty()){
while(!s_new.isEmpty()){
s_old.push(s_new.pop());
}
}
return s_old.pop();
}
public boolean isEmpty(){
return s_new.isEmpty() && s_old.isEmpty();
}
public int min(){
return Math.min(s_new.min(), s_old.min());
}
public int max(){
return Math.max(s_new.max(), s_old.max());
}
}



Wednesday, December 24, 2014

Count Luck - Maze

Most of the maze question are related to DFS graph search, can be solved by recursive way.

This one is from HackerRank

https://www.hackerrank.com/challenges/count-luck/copy-from/10625563


Problem Statement from hackerrank
Hermione Granger is lost in the Forbidden Forest while collecting some herbs for her magical potion. The forest is magical and has only 1 exit point which magically transports her back to the Hogwarts School of Wizardy and Witch Craft.
Forest can be considered as a grid of NxM size. Each cell in the forest is either empty (represented by '.') or has a tree (represented by 'X'). Hermione can move through empty cell, but not through cells with tree on it. She can only travel LEFT, RIGHT, UP, DOWN. Her position in the forest is indicated by the marker 'M' and the location of the exit point is indicated by '*'. Top-left corner is indexed (0, 0).
.X.X......X
.X*.X.XXX.X
.XX.X.XM...
......XXXX.
In the above forest, Hermione is located at index (2, 7) and exit is at (1, 2). Each cell is indexed according to Matrix Convention
She starts her commute back to the exit and every time she encounters more than one option to move, she waves her wand and the correct path is illuminated and she proceeds in that way. It is guaranteed that there is only one path to each reachable cell from the starting cell. Can you tell us if she waved her wand exactly K times or not? Ron will be impressed if she is able to do so.
The key here is to find the ONLY path from M to *, then trace it back, and count the point where Hermione has multiple choices. 
public class Solution {
    public static class Node{
        int r;int c; Node pre;
        public Node(int r, int c){this.r = r; this.c = c;}
    }
    public static void visit(char[][] maz, int startR, int startC, boolean[][] seen,  Node pre, Node tail){
        if(startR<0 || startC<0 || startR>=maz.length || startC>=maz[0].length || seen[startR][startC])
            return;
        if(maz[startR][startC]=='X')
            return;
        if(maz[startR][startC]=='*'){
            tail.pre = pre;
            return;       
        }
        seen[startR][startC] = true;
        Node n = new Node(startR, startC);
        n.pre = pre;
        visit(maz, startR-1, startC, seen,  n, tail);
        visit(maz, startR+1, startC, seen,  n, tail);
        visit(maz, startR, startC-1, seen,  n, tail);
        visit(maz, startR, startC+1, seen,  n, tail);
    }
    
    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        try(Scanner conin = new Scanner(System.in)){
            int t = conin.nextInt();
            while(t-->0){
                int row = conin.nextInt();
                int col = conin.nextInt();
                int startR=0, startC=0;
                int endR=0, endC=0;
                char[][] maz = new char[row][col];
                for(int r=0; r<row; r++){
                    String str = conin.next();
                    int index = str.indexOf("M");
                    if(index>=0){
                        startR=r;startC=index;
                    }
                    index = str.indexOf("*");
                    if(index>=0){
                        endR=r;endC=index;
                    }
                    maz[r] = str.toCharArray();
                }
                int k=conin.nextInt();
                boolean[][] seen = new boolean[row][col];
                Node tail = new Node(endR, endC);
                Node head = null;
                visit(maz, startR, startC, seen, head, tail);                 
                int counter = 0;
                Node n = tail.pre;
                while(n!=null){
                    //System.out.println(n.r + "-" + n.c);
                    int option = 0;
                    if(n.r-1>=0 && n.r-1<row && maz[n.r-1][n.c]=='.')
                        option++;
                    if(n.r+1>=0 && n.r+1<row && maz[n.r+1][n.c]=='.')
                        option++;
                    if(n.c-1>=0 && n.c-1<col && maz[n.r][n.c-1]=='.')
                        option++;
                    if(n.c+1>=0 && n.c+1<col && maz[n.r][n.c+1]=='.')
                        option++;
                    if(option>2 || (n == tail.pre&&option>1) || (n.r==startR&&n.c==startC&&option>1) || (n.pre!=null && n.pre.r==startR&&n.pre.c==startC&&option>1))
                        counter++;
                    n = n.pre;                    
                }
                
                System.out.println(counter==k?"Impressed":"Oops!");
            }
        }
    }
}



Tuesday, December 23, 2014

Star

This one is from hacker rank.

https://www.hackerrank.com/challenges/stars


Problem Statement from the hacker rank
Little John has drawn N stars on his paper where each star has a weight vi. He draws a straight line that divides the paper into two parts such that each part has a subset of stars in them. Let the weight of each part be the summation of weights of the stars in the part. He wants to draw the line such that the difference in the sum of weights between the two parts is as small as possible while maximizing the smaller part's weight.
Your task is to compute the weight of smaller part corresponding to this line where no stars are allowed to be on the line and line can be of any slope.
Input Format
The first line of the input contains an integer N.
Each of next N lines contains three integers xi and yi specifying the positions of ith star and vi.
No three points lie on a line.
The key here is the formular to find if point is on left or right side of a line:
position = sign( (Bx-Ax)*(Y-Ay) - (By-Ay)*(X-Ax) )
0 on the line, and positive on one side, negative on the other side.

this is O(n^3) solution
public class Solution {
    public static class Point{
        long x; long y; long w;
        Point(long x, long y, long w){this.x = x; this.y = y; this.w = w;}
        long onLine(Point p1, Point p2){
            return (p1.x - p2.x)*(this.y-p1.y)-(p1.y-p2.y)*(this.x-p1.x);
        }
    }

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        try(Scanner conin = new Scanner(System.in)){
            int num = conin.nextInt();
            Point[] points = new Point[num];
            for(int i=0; i<num; i++){
                points[i] = new Point(conin.nextLong(), conin.nextLong(), conin.nextLong());
            }
            long maxSum = 0;
            for(int i=0; i<num; i++){
                for(int j=i+1; j<num; j++){
                    long leftSum = 0;
                    long rightSum = 0;
                    for(int k=0; k<num; k++){
                        if(!(k==i || k==j)){
                            long left = points[k].onLine(points[i], points[j]);
                            if(left>0)
                                leftSum += points[k].w;
                            else
                                rightSum += points[k].w;
                        }                        
                    }
                    
                    long[] sums = new long[]{leftSum, rightSum, points[i].w, points[j].w};
                    Arrays.sort(sums);
                    long sum = Math.min(sums[0]+sums[3], sums[1]+sums[2]);
                    maxSum = Math.max(maxSum, sum);
                    
                    //sum = Math.min(sums[0], sums[1]+sums[2]+sums[3]);
                    //maxSum = Math.max(maxSum, sum);
                    
                    sum = Math.min(sums[0]+sums[1], sums[2]+sums[3]);
                    maxSum = Math.max(maxSum, sum);
                    
                    sum = Math.min(sums[0]+sums[1]+sums[2], sums[3]);
                    maxSum = Math.max(maxSum, sum);
                    
                }
            }
            System.out.println(maxSum);
        }
    }
}

Wednesday, November 26, 2014

Maximum number of edges removed so the each connected component of the forest should contain an even number of vertices.

Tomorrow is Thanksgiving day, to prepare myself for the holiday, I spent one hour to solve this graph problem found online. This is fun!

The problem source: https://www.hackerrank.com/challenges/even-tree

You are given a tree (a simple connected graph with no cycles). You have to remove as many edges from the tree as possible to obtain a forest with the condition that : Each connected component of the forest should contain an even number of vertices.
To accomplish this, you will remove some edges from the tree. Find out the maximum number of removed edges.
Approach: Greedy algorithm.

Iterate through all of the edges of the initial graph, then calculate the number of vertices of each subtree rooted at the two vertices of examined edge. If both numbers are even, then remove the edge. 
Here are the method and classes:
static List<EdgeG> edges = new ArrayList<EdgeG>();

public static class EdgeG{
NodeG one;
NodeG two;
public EdgeG(NodeG o, NodeG t){
this.one = o;
this.two = t;
}
}


public static int removeEdge(){
int counter = 0;
for(EdgeG e : edges){
if(e.one.size(e.two)%2==0 && e.two.size(e.one)%2==0){
//remove edge
counter++;
e.one.removeEdge(e.two);
e.two.removeEdge(e.one);
}
}
return counter;
}
To calculate the numbers of vertices for each subtree rooted at the two vertices of the examined edge, we can use Depth First Search. Here is the code

public static class NodeG{
int num;
List<NodeG> neighbors;
public NodeG(int n){
num = n;
neighbors = new ArrayList<NodeG>();
}

public int size(NodeG from){
NodeG n = this;
int counter = 0;
Set<NodeG> seen = new HashSet<NodeG>();
Stack<NodeG> s = new Stack<NodeG>();
s.add(n);
counter++;
while(!s.isEmpty()){
NodeG current = s.pop();
seen.add(current);
for(NodeG c : current.neighbors){
if(c!=from && !seen.contains(c)){
s.add(c);
counter++;
}
}
}
return counter;
}
}

Wednesday, September 17, 2014

Find the first element occurs twice in a number array

The most effective solution is to use hash to keep track of the element counts, while using DLL list to keep track of the potential candidates seen so far, meanwhile the value of the hash table is a pointer to each node in the DLL, so we can quickly remove one node from the DLL.

Data structure: aggregated data structure using hash table O(1) lookup and DLL O(1) deletion and access to the head.

/*
* http://www.geeksforgeeks.org/microsoft-interview-set-37-sde-1/
* Given numbers a1…an find the minimum index, whose element occurs 
* twice in the array. Do it in one pass of the array ( or less that O(n) if possible?)
*/
public static int findFirstNoRepeatNumber(int[] numbers){
Map<Integer, Node> store = new HashMap<Integer, Node>();
Node head = null;
Node tail = null;
for(int i : numbers){
if(store.containsKey(i)){
Node found = store.get(i);
found.times = found.times + 1;
if(found.times==2){
//add it to DLL when repeat twice
if(head==null){
head = found;
tail = found;
}else{
found.pre = tail;
tail.next = found;
tail = found;
}
}
if(found.times>2){
//remove found from DLL
if(!(found.pre==null && found.next==null)){
if(found.pre==null){
head = found.next;
}else if(found.next ==null){
tail = found.pre;
}else{
found.pre.next = found.next;
found.next.pre = found.pre;
}
found.pre = null;
found.next = null;
}
}
}else{
//create node and add to map for first time
Node newNode = new Node();
newNode.index = i;
newNode.times = 1;
store.put(i, newNode);
}
}
return head.index;
}