Showing posts with label graph. Show all posts
Showing posts with label graph. Show all posts

Friday, September 23, 2016

Evaluate Division

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].
The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.
According to the example above:
equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. 
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

Analysis:

This is to find if two elements are connected. A typical graph practice.
After a path is found out, the answer to query is multiply of edges:
a/b=1,b/c=2,c/d=3, then a/d = a/b*b/c*c/d=6.0


class Edge{
    String from,to;
    double weight;
public Edge(String a,String b, double w){
    from = a;
    to = b;
    weight = w;
}
public String toString(){
    return from+"->"+to+":"+weight;
}
public int hashCode(){
    return toString().hashCode();
}    
public boolean equals(Object b){
    if(b instanceof Edge && toString().equals(b.toString())){
        return true;
    }
    return false;
}
}
class EdgeWeightedGraph{
    Map<String,Set<Edge>> adj = new HashMap<String,Set<Edge>>();
    
    public void addEdge(String a,String b, double weight){
        Edge one = new Edge(a,b,weight);
        Edge two = new Edge(b,a,1.0/weight);
        if(adj.containsKey(a)){
            adj.get(a).add(one);
        }else{
            Set<Edge> s = new HashSet<Edge>();
            s.add(one);
            adj.put(a,s);
        }
        if(adj.containsKey(b)){
            adj.get(b).add(two);
        }else{
            Set<Edge> s = new HashSet<Edge>();
            s.add(two);
            adj.put(b,s);
        }
    }
    public boolean contains(String a){
        return adj.containsKey(a);
    }
    public List<Edge> getPath(String a, String b){
        Set<Edge> visited = new HashSet<Edge>();
        List<Edge> path = new ArrayList<Edge>();
        path = dfsGetPath(a,b,path,visited);
        return path;
    }
    private List<Edge> dfsGetPath(String start,String end,List<Edge> path,Set<Edge> visited){
        if(start.equals(end)){
            //List<Edge> result = new ArrayList<Edge>();
            //result.addAll(path);
            return path;
        }
        if(adj.get(start)!=null){
            for(Edge e:adj.get(start)){
                if(visited.add(e)){
                    path.add(e);
                    List<Edge> r = dfsGetPath(e.to,end,path,visited);
                    if(r.size()>0){
                        return r;
                        //stop further processing
                    }
                    path.remove(e);//next loop starting from same path path
                }
            }
        }
        return new ArrayList<Edge>();
    }
}
public class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        //prepare
        double[] result = new double[queries.length];
        EdgeWeightedGraph g = new EdgeWeightedGraph();
        for(int i=0;i<values.length;i++){
            g.addEdge(equations[i][0],equations[i][1],values[i]);
        }
        for(int i=0;i<queries.length;i++){
            if(queries[i][0].equals(queries[i][1])&&g.contains(queries[i][0])){
                result[i]=1.0;
                continue;
            }
            List<Edge> r = g.getPath(queries[i][0],queries[i][1]);
            if(r.size()==0){
                result[i]=-1.0;
            }else{
                result[i]=1;
                for(Edge e:r){
                    result[i]*=e.weight;
                }
            }
        }
        return result;
    }
}

Wednesday, September 21, 2016

Frog Jump

A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.
If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.
Note:
  • The number of stones is ≥ 2 and is < 1,100.
  • Each stone's position will be a non-negative integer < 231.
  • The first stone's position is always 0.
Example 1:
[0,1,3,5,6,8,12,17]

There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.

Return true. The frog can jump to the last stone by jumping 
1 unit to the 2nd stone, then 2 units to the 3rd stone, then 
2 units to the 4th stone, then 3 units to the 6th stone, 
4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:


[0,1,2,3,4,8,9,11]

Return false. There is no way to jump to the last stone as 
the gap between the 5th and 6th stone is too large.
Analysis
With possible movements defined as constrains/rules, and target is to find if something is reachable, a natural thought would be finding if there's a path between two nodes in a graph. So adjacency list is a good candidate data structure to use. Controversy to traditional use of adjacency list, which is built up to represent a graph before traverse it, this algorithm built it up on the fly and used it as a memoization mechanism to avoid duplicate computations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
    public boolean canCross(int[] stones) {
        Objects.requireNonNull(stones);
   if(stones.length==1)return true;//one stone means the one to the other side
   if(stones.length==2) return (stones[1]==1?true:false);
   //this is an adjacency list. and our target is to figure out 
   //if there's a path to a node following certain restrictions
   //Controversy to traditional use of adjacency list, this list is built up on the fly
        Map<Integer, Set<Integer>> validMovements = new HashMap<Integer, Set<Integer>>();
        for(int i:stones){
         validMovements.put(i, new HashSet<Integer>());
        }
        validMovements.get(0).add(1);
        return dfs(validMovements,1,1,stones[stones.length-1]);
  }
  private boolean dfs(Map<Integer, Set<Integer>> validPositions, int curPosition, int lastJumpUnits, int endPosition){
   boolean reachable = false;
   for(int i=-1;i<=1;i++){
    int nextPosition = curPosition + lastJumpUnits+i;
    if(nextPosition==endPosition){
     return true;
    }
    //lastJumpUnits+i=0, not jumping, will make infinite loop so to avoid it
    if(lastJumpUnits+i>0 && validPositions.containsKey(nextPosition) 
      && !validPositions.get(nextPosition).contains(lastJumpUnits+i)){
     //we go here only when nextPosition is valid and nextPosition's movement has not been done
     //validPositions.get(nextPosition).add(lastJumpUnits+i);
     reachable = dfs(validPositions,nextPosition,lastJumpUnits+i,endPosition);
     if(reachable)break;
    }
   }
   validPositions.get(curPosition).add(lastJumpUnits);
   return reachable;
  }
}

Wednesday, June 08, 2016

Reconstruct Itinerary

Reconstruct Itinerary

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
  1. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
  2. All airports are represented by three capital letters (IATA code).
  3. You may assume all tickets may form at least one valid itinerary.
Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package array;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

public class ResonstructIternenary {
 public List<String> findItinerary(String[][] tickets) {
  // construct adjacency list, make its adjacency list sorted
  // make sure it is really a list and not set. use set when it does not allow
  // duplication 
  //sorted list in java can be priority queue
  Map<String, PriorityQueue<String>> adl = new HashMap<String, PriorityQueue<String>>();
  for (String[] ft : tickets) {
   PriorityQueue<String> to = adl.get(ft[0]);
   if (to == null)
    to = new PriorityQueue<String>();// so every from node has a
             // queue even it is empty
   to.add(ft[1]);
   adl.put(ft[0], to);
  }
  //to hold the path
  LinkedList<String> itinerary = new LinkedList<String>();

  dfs(adl, "JFK", itinerary);
  return itinerary;
 }

 /**
  * depth first traversal following the minimum ordered destinations 
  * remove the destination from adjacency list so that it won't be visited twice 
  * when no further destination to go further, put the destination to the path
  *  
  * @param adl
  * @param string
  * @param itinerary
  */
 private void dfs(Map<String, PriorityQueue<String>> adl, String from,
   LinkedList<String> itinerary) {
  while (adl.keySet().contains(from) && adl.get(from).size() > 0) {
   dfs(adl, adl.get(from).poll(), itinerary);
  }
  // it will reach to here after dfs is done, which means reaching to
  // deepest leaves from current node
  // the stack of nested calls keeps the order of node visiting. reflect
  // it by adding to from of list
  itinerary.addFirst(from);
 }

 public static void main(String[] args) {
  ResonstructIternenary o = new ResonstructIternenary();
  String[][] tickets = { { "JFK", "SFO" }, { "JFK", "ATL" },
    { "SFO", "JFK" } };
  List<String> itinerary = o.findItinerary(tickets);
  System.out.println(itinerary);
 }
}