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;
}

Wednesday, July 30, 2014

longest repeated substring using simplest suffix tree


public class SuffixTree {
STNode root;
class STNode {
int data ;
STNode[] edges;
STNode(int d){
data = d;
}
STNode(){
}
}
//assume small cases: a-z
STNode addString(String s, int data){
if(root==null)
root = new STNode(-1);
STNode current = root;
int index = 0;
while(index<s.length()){
if(current.edges==null)
current.edges = new STNode[26];
int pos = s.charAt(index) - 'a';
if(current.edges[pos]==null)
current.edges[pos] = new STNode();
current = current.edges[pos];
index++;
}
current.data = data; //leaf store the position
return root;
}
public void addAllSubString(String s){
for(int i=0;i<s.length();i++){
this.addString(s.substring(i), i);
}
}

public String findLongestRepeatSub(String s){
this.addAllSubString(s);
Deque<STNode> sk = new ArrayDeque<STNode>();
sk.add(root);
int maxL = 0;
int currentL = 0;
STNode target = root;
while(!sk.isEmpty()){
Deque<STNode> temp = new ArrayDeque<STNode>();

while(!sk.isEmpty()){
STNode n = sk.remove();
currentL++;
int counter=0;
if(n.edges!=null){
for(STNode nd : n.edges){
if(nd!=null){
sk.add(nd);
counter++;
}
}
}

if(counter>1 || counter==1 && n.data>0){
if(currentL>maxL){
maxL = currentL;
target = n;
}
}
}
sk = temp;
}
int cn = 0;
//go down to the leaf if not on leaf yet.
while(target.data<=0){
if(target.edges!=null){
for(STNode nd : target.edges){
if(nd!=null){
target = nd;
cn++;
}
}
}
}
if(cn!=0)
return s.substring(target.data, s.length()-cn+1);
else
return s.substring(target.data, s.length());
}
}