Tuesday, September 15, 2015

Leetcode: Alien Dictionary

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
For example,
Given the following words in dictionary,
[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]
The correct order is: "wertf".
Note:
  1. You may assume all letters are in lowercase.
  2. If the order is invalid, return an empty string.
  3. There may be multiple valid order of letters, return any one of them is fine.
Understand the problem:
The problem can be solved by a topological sorting. First we construct the graph based on the ordering relationship. Then do a topological sorting, which return the correct order. 

Code (Java):
public class Solution {
    public String alienOrder(String[] words) {
        // Step 1: build the graph
        Map<Character, Set<Character>> graph = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            String curr = words[i];
            for (int j = 0; j < curr.length(); j++) {
                if (!graph.containsKey(curr.charAt(j))) {
                    graph.put(curr.charAt(j), new HashSet<Character>());
                }
            }
            
            if (i > 0) {
                connectGraph(graph, words[i - 1], curr);
            }
        }
        
        // Step 2: toplogical sorting
        StringBuffer sb = new StringBuffer();
        Map<Character, Integer> visited = new HashMap<Character, Integer>();
        
        Iterator it = graph.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            char vertexId = (char) pair.getKey();
            if (toplogicalSort(vertexId, graph, sb, visited) == false) {
                return "";
            }
        }
        
        return sb.toString();
    }
    
    private void connectGraph(Map<Character, Set<Character>> graph, String prev, String curr) {
        if (prev == null || curr == null) {
            return;
        }
        
        int len = Math.min(prev.length(), curr.length());
        
        for (int i = 0; i < len; i++) {
            char p = prev.charAt(i);
            char q = curr.charAt(i);
            if (p != q) {
                if (!graph.get(p).contains(q)) {
                    graph.get(p).add(q);
                }
                break;
            }
        }
    }
    
    private boolean toplogicalSort(char vertexId, Map<Character, Set<Character>> graph, StringBuffer sb, 
                                   Map<Character, Integer> visited) {
        if (visited.containsKey(vertexId)) {
            // visited
            if (visited.get(vertexId) == -1) {
                return false;
            }
            
            // already in the list
            if (visited.get(vertexId) == 1) {
                return true;
            }
        } else {
            // mark as visited
            visited.put(vertexId, -1);
        }
        
        Set<Character> neighbors = graph.get(vertexId);
        for (char neighbor : neighbors) {
            if (toplogicalSort(neighbor, graph, sb, visited) == false) {
                return false;
            }
        }
        
        sb.insert(0, vertexId);
        visited.put(vertexId, 1);
        
        return true;
    }
}

Update on 4/22/19: Topological sort using BFS
public class Solution {
    /**
     * @param words: a list of words
     * @return: a string which is correct order
     */
    public String alienOrder(String[] words) {
        // Write your code here
        if (words == null || words.length == 0) {
            return "";
        }
        
        // step 1: construct the graph
        //
        Map<Character, List<Character>> adjList = new HashMap<>();
        constructGraph(words, adjList);
        
        int numNodes = adjList.size();
        
        StringBuilder ans = new StringBuilder();
        
        // toplogical sorting
        //
        Map<Character, Integer> indegreeMap = new HashMap<>();
        for (Character node : adjList.keySet()) {
            indegreeMap.put(node, 0);
        }
        
        for (Character node : adjList.keySet()) {
            for (Character neighbor : adjList.get(node)) {
                int indegree = indegreeMap.get(neighbor);
                indegree += 1;
                indegreeMap.put(neighbor, indegree);
            }
        }
        
        Queue<Character> queue = new PriorityQueue<>();
        for (Character node : indegreeMap.keySet()) {
            if (indegreeMap.get(node) == 0) {
                queue.offer(node);
            }
        }
        
        while (!queue.isEmpty()) {
            char curNode = queue.poll();
            ans.append(curNode);
            
            for (char neighbor : adjList.get(curNode)) {
                int indegree = indegreeMap.get(neighbor);
                indegree -= 1;
                indegreeMap.put(neighbor, indegree);
                if (indegree == 0) {
                    queue.offer(neighbor);
                }
            }
        }
        
        if (ans.length() < numNodes) {
            return "";
        }
        
        return ans.toString();
    }
    
    private void constructGraph(String[] words, Map<Character, List<Character>> adjList) {
        // construct nodes
        //
        for (String word : words) {
            for (Character c : word.toCharArray()) {
                adjList.put(c, new ArrayList<>());
            }
        }
        
        // construct edges
        //
        for (int i = 1; i < words.length; i++) {
            String prev = words[i - 1];
            String curr = words[i];
            
            for (int j = 0; j < prev.length() && j < curr.length(); j++) {
                if (prev.charAt(j) != curr.charAt(j)) {
                    adjList.get(prev.charAt(j)).add(curr.charAt(j));
                    break;
                }
            }
        }
    }
}




Monday, August 31, 2015

Leetcode: Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
Hints:
  1. This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.


Understand the problem:
This problem is equivalent to finding the topological order in a directed graph. According to wiki, the topological  sorting is defined as " In the field of computer science, a topological sort (sometimes abbreviated toposort[1]) or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex vu comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). Any DAG has at least one topological ordering, and algorithms are known for constructing a topological ordering of any DAG in linear time."

Code (Java):
public class Solution {
    private int label;
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        if (numCourses <= 0) {
            return new int[0];
        }
        this.label = numCourses - 1;
        
        int[] result = new int[numCourses];
        
        // No prerequisites
        if (prerequisites == null || prerequisites.length == 0) {
            for (int i = 0; i < numCourses; i++) {
                result[i] = i;
            }
            
            return result;
        }
        
        // Convert the edge list to adj. list
        Map<Integer, List<Integer>> adjList = new HashMap<>();
        for (int[] edge : prerequisites) {
            if (adjList.containsKey(edge[1])) {
                List<Integer> neighbors = adjList.get(edge[1]);
                neighbors.add(edge[0]);
                adjList.put(edge[1], neighbors);
            } else {
                List<Integer> neighbors = new ArrayList<Integer>();
                neighbors.add(edge[0]);
                adjList.put(edge[1], neighbors);
            }
        }
        
        int[] visited = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            if (toplogicalSorting(i, visited, adjList, result) == false) {
                return new int[0];
            }
        }
        
        return result;
    }
    
    private boolean toplogicalSorting(int vertexId, int[] visited, 
            Map<Integer, List<Integer>> adjList,
                                   int[] result) {
        // Has been visited
        if (visited[vertexId] == -1) {
            return false;
        }
        
        // Has been added into the list
        if (visited[vertexId] == 1) {
            return true;
        }
        
        visited[vertexId] = -1;
        
        List<Integer> neighbors = adjList.get(vertexId);
        if (neighbors != null) {
            for (int neighbor : neighbors) {
                if (toplogicalSorting(neighbor, visited, 
                    adjList, result) == false) {
                    return false;
                }
            }
        }
        
        result[label--] = vertexId;
        visited[vertexId] = 1;
        
        return true;
                                       
    }
}

Update on 4/22/19: Topological sort using BFS
public class Solution {
    /*
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: the course order
     */
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        // write your code here
        int[] ans = new int[numCourses];
        int ansIdx = numCourses - 1;
        
        if (prerequisites == null || prerequisites.length == 0) {
            for (int i = 0; i < numCourses; i++) {
                ans[i] = i;
            }
            
            return ans;
        }
        
        Map<Integer, List<Integer>> adjList = new HashMap<>();
        Map<Integer, Integer> nodeToIndegreeMap = new HashMap<>();
        
        for (int i = 0; i < numCourses; i++) {
            adjList.put(i, new ArrayList<>());
            nodeToIndegreeMap.put(i, 0);
        }
        
        for (int[] prerequisite : prerequisites) {
            List<Integer> neighbors = adjList.get(prerequisite[0]);
            neighbors.add(prerequisite[1]);
            
            int indegree = nodeToIndegreeMap.get(prerequisite[1]);
            indegree += 1;
            nodeToIndegreeMap.put(prerequisite[1], indegree);
        }
        
        // get all nodes with 0 indegree
        //
        Queue<Integer> queue = new LinkedList<>();
        for (Integer node : nodeToIndegreeMap.keySet()) {
            if (nodeToIndegreeMap.get(node) == 0) {
                queue.offer(node);
            }
        }
        
        while (!queue.isEmpty()) {
            int curNode = queue.poll();
            ans[ansIdx--] = curNode;
            
            for (int neighbor : adjList.get(curNode)) {
                int indegree = nodeToIndegreeMap.get(neighbor);
                indegree -= 1;
                nodeToIndegreeMap.put(neighbor, indegree);
                
                if (indegree == 0) {
                    queue.offer(neighbor);
                }
            }
        }
        
        if (ansIdx > 0) {
            return new int[0];
        }
        
        return ans;
    }
}