LeetCode 863 - All Nodes Distance K in Binary Tree


https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/
We are given a binary tree (with root node root), a target node, and an integer value K.
Return a list of the values of all nodes that have a distance K from the target node.  The answer can be returned in any order.

    Example 1:
    Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
    
    Output: [7,4,1]
    
    Explanation: 
    The nodes that are a distance 2 from the target node (with value 5)
    have values 7, 4, and 1.
    
    
    
    Note that the inputs "root" and "target" are actually TreeNodes.
    The descriptions of the inputs above are just serializations of these objects.
    
    X. https://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/
    There are two types of nodes to be considered.
    1) Nodes in the subtree rooted with target node. For example if the target node is 8 and k is 2, then such nodes are 10 and 14.
    2) Other nodes, may be an ancestor of target, or a node in some other subtree. For target node 8 and k is 2, the node 22 comes in this category.
    Finding the first type of nodes is easy to implement. Just traverse subtrees rooted with the target node and decrement k in recursive call. When the k becomes 0, print the node currently being traversed (See this for more details). Here we call the function as printkdistanceNodeDown().
    How to find nodes of second type? For the output nodes not lying in the subtree with the target node as the root, we must go through all ancestors. For every ancestor, we find its distance from target node, let the distance be d, now we go to other subtree (if target was found in left subtree, then we go to right subtree and vice versa) of the ancestor and find all nodes at k-d distance from the ancestor.
        Node root;
        /* Recursive function to print all the nodes at distance k in
           tree (or subtree) rooted with given root. */
       
        void printkdistanceNodeDown(Node node, int k) 
        {
            // Base Case
            if (node == null || k < 0)
                return;
       
            // If we reach a k distant node, print it
            if (k == 0
            {
                System.out.print(node.data);
                System.out.println("");
                return;
            }
       
            // Recur for left and right subtrees
            printkdistanceNodeDown(node.left, k - 1);
            printkdistanceNodeDown(node.right, k - 1);
        }
       
        // Prints all nodes at distance k from a given target node.
        // The k distant nodes may be upward or downward.This function
        // Returns distance of root from target node, it returns -1
        // if target node is not present in tree rooted with root.
        int printkdistanceNode(Node node, Node target, int k) 
        {
            // Base Case 1: If tree is empty, return -1
            if (node == null)
                return -1;
       
            // If target is same as root.  Use the downward function
            // to print all nodes at distance k in subtree rooted with
            // target or root
            if (node == target) 
            {
                printkdistanceNodeDown(node, k);
                return 0;
            }
       
            // Recur for left subtree
            int dl = printkdistanceNode(node.left, target, k);
       
            // Check if target node was found in left subtree
            if (dl != -1
            {
                   
                // If root is at distance k from target, print root
                // Note that dl is Distance of root's left child from 
                // target
                if (dl + 1 == k) 
                {
                    System.out.print(node.data);
                    System.out.println("");
                }
                   
                // Else go to right subtree and print all k-dl-2 distant nodes
                // Note that the right child is 2 edges away from left child
                else
                    printkdistanceNodeDown(node.right, k - dl - 2);
       
                // Add 1 to the distance and return value for parent calls
                return 1 + dl;
            }
       
            // MIRROR OF ABOVE CODE FOR RIGHT SUBTREE
            // Note that we reach here only when node was not found in left 
            // subtree
            int dr = printkdistanceNode(node.right, target, k);
            if (dr != -1
            {
                if (dr + 1 == k) 
                {
                    System.out.print(node.data);
                    System.out.println("");
                
                else 
                    printkdistanceNodeDown(node.left, k - dr - 2);
                return 1 + dr;
            }
       
            // If target was neither present in left nor in right subtree
            return -1;
        }
    Time Complexity: At first look the time complexity looks more than O(n), but if we take a closer look, we can observe that no node is traversed more than twice. Therefore the time complexity is O(n).
      List<Integer> ans;
      TreeNode target;
      int K;

      public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        ans = new LinkedList();
        this.target = target;
        this.K = K;
        dfs(root);
        return ans;
      }

      // Return vertex distance from node to target if exists, else -1
      // Vertex distance: the number of vertices on the path from node to target
      public int dfs(TreeNode node) {
        if (node == null)
          return -1;
        else if (node == target) {
          subtree_add(node, 0);
          return 1;
        } else {
          int L = dfs(node.left), R = dfs(node.right);
          if (L != -1) {
            if (L == K)
              ans.add(node.val);
            subtree_add(node.right, L + 1);
            return L + 1;
          } else if (R != -1) {
            if (R == K)
              ans.add(node.val);
            subtree_add(node.left, R + 1);
            return R + 1;
          } else {
            return -1;
          }
        }
      }

      // Add all nodes 'K - dist' from the node to answer.
      public void subtree_add(TreeNode node, int dist) {
        if (node == null)
          return;
        if (dist == K)
          ans.add(node.val);
        else {
          subtree_add(node.left, dist + 1);
          subtree_add(node.right, dist + 1);
        }

      }
    X. Graph BFS
    https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/143752/JAVA-Graph-%2B-BFS
    https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/143729/Python-DFS-and-BFS
    A recursive dfs funciton connect help to build up a map conn.
    The key of map is node's val and the value of map is node's connected nodes' vals.
    Then we do N times bfs search loop to find all nodes of distance K
    //Method 1: use HashMap
    //1. build a undirected graph using treenodes as vertices, and the parent-child relation as edges
    //2. do BFS with source vertice (target) to find all vertices with distance K to it.
    class Solution {
        Map<TreeNode, List<TreeNode>> map = new HashMap();
    //here can also use Map<TreeNode, TreeNode> to only store the child - parent mapping, since parent-child mapping is inherent in the tree structure
        
        public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
             List<Integer> res = new ArrayList<Integer> ();
            if (root == null || K < 0) return res;
            buildMap(root, null); 
            if (!map.containsKey(target)) return res;
            Set<TreeNode> visited = new HashSet<TreeNode>();
            Queue<TreeNode> q = new LinkedList<TreeNode>();
            q.add(target);
            visited.add(target);
            while (!q.isEmpty()) {
                int size = q.size();
                if (K == 0) {
                    for (int i = 0; i < size ; i++) res.add(q.poll().val);
                    return res;
                }
                for (int i = 0; i < size; i++) {
                    TreeNode node = q.poll();
                    for (TreeNode next : map.get(node)) {
                        if (visited.contains(next)) continue;
                        visited.add(next);
                        q.add(next);
                    }
                }
                K--;
            }
            return res;
        }
        
        private void buildMap(TreeNode node, TreeNode parent) {
            if (node == null) return;
            if (!map.containsKey(node)) {
                map.put(node, new ArrayList<TreeNode>());
                if (parent != null)  { map.get(node).add(parent); map.get(parent).add(node) ; }
                buildMap(node.left, node);
                buildMap(node.right, node);
            }
        }    
    }
    
    //Method 2: No HashMap
    //kind of like clone the tree, in the meanwhile add a parent link to the node
    class Solution {
        private GNode targetGNode;
        
        private class GNode {
            TreeNode node;
            GNode parent, left, right;
            GNode (TreeNode node) {
                this.node = node;
            }
        }           
        
        public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
            List<Integer> res = new ArrayList<Integer> ();
            if (root == null || K < 0) return res;
            cloneGraph(root, null, target);
            if (targetGNode == null) return res;
            Set<GNode> visited = new HashSet<GNode>();
            Queue<GNode> q = new LinkedList<GNode>();
            q.add(targetGNode);
            visited.add(targetGNode);
            while (!q.isEmpty()) {
                int size = q.size();
                if (K == 0) {
                    for (int i = 0; i < size ; i++) res.add(q.poll().node.val);
                    return res;
                }
                for (int i = 0; i < size; i++) {
                    GNode gNode = q.poll();
                    if (gNode.left != null && !visited.contains(gNode.left)) { visited.add(gNode.left); q.add(gNode.left); }
                    if (gNode.right != null && !visited.contains(gNode.right)) { visited.add(gNode.right); q.add(gNode.right); }
                    if (gNode.parent != null && !visited.contains(gNode.parent)) { visited.add(gNode.parent); q.add(gNode.parent); }
                }
                K--;
            }
            return res;
        }
        
        private GNode cloneGraph(TreeNode node, GNode parent, TreeNode target) {
            if (node == null) return null;
            GNode gNode = new GNode(node);
            if (node == target) targetGNode = gNode;
            gNode.parent = parent;
            gNode.left = cloneGraph(node.left, gNode, target);
            gNode.right = cloneGraph(node.right, gNode, target);
            return gNode;
        }
    }
    X. DFS
    https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/143713/Easy-to-understand-Graph-DFS


    It would be very easy to find the neighbors in K distance in a graph, so I converted the tree into a graph whose node(GNode) has neighbors, which include it’s parent and left & right children:
    https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/143775/very-easy-to-understand-c%2B%2B-solution.
    1. Using recursion to find all of the son=>parent pair into a map.
    2. Using dfs to find K distance node, visited nodes will be recorded.
        vector<int> ans;   
        map<TreeNode*, TreeNode*> parent;  // son=>parent  
        set<TreeNode*> visit;    //record visied node
        
        void findParent(TreeNode* node){
            if(!node ) return;
            if( node->left ){
                parent[node->left] = node;
                findParent(node->left);
            }
            if( node->right){
                parent[node->right] = node;
                findParent(node->right);
            }
        }
        
        vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
            if( !root ) return {};
            
            findParent(root);
            dfs(target, K );
            return ans;
        }
        void dfs( TreeNode* node, int K){
            if( visit.find(node) != visit.end() )
                return;
            visit.insert(node);
            if( K == 0 ){
                ans.push_back(node->val);
                return;
            }
            if( node->left ){
                dfs(node->left, K-1);
            }
            if( node->right){
                dfs(node->right, K-1);
            }
            TreeNode* p = parent[node];
            if( p )
                dfs(p, K-1);
        } 
    As we know, if the distance from a node to target node is k, the distance from its child to the target node is k + 1 unless the child node is closer to the target node which means the target node is in it's subtree.
    To avoid this situation, we need to travel the tree first to find the path from root to target, to:
    • store the value of distance in hashamp from the all nodes in that path to target
    Then we can easily use dfs to travel the whole tree. Every time when we meet a treenode which has already stored in map, use the stored value in hashmap instead of the value from its parent node.
    Great solution, but both helper method has one parameter never used.
    Keeping the distance from parents node to the target node is so brilliant!!!
    the most brilliant part is to update the length and do the check then pass the length + 1 to next level in dfs function
    https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/163101/Java-Solution
    • Note the distances from target node to all the nodes up the path to root from target in a map.
    • Apply pre-order traversal using the map above.
      • If the node is present in the map, use that distance
      • else assume d+1 where d = distance for the parent.
        Map<TreeNode, Integer> map = new HashMap<>();
            
        public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
            List<Integer> res = new LinkedList<>();
            find(root, target);
            dfs(root, target, K, map.get(root), res);
            return res;
        }
        
        // find target node first and store the distance in that path that we could use it later directly
        private int find(TreeNode root, TreeNode target) {
            if (root == null) return -1;
            if (root == target) {
                map.put(root, 0);
                return 0;
            }
            int left = find(root.left, target);
            if (left >= 0) {
                map.put(root, left + 1);
                return left + 1;
            }
     int right = find(root.right, target);
     if (right >= 0) {
                map.put(root, right + 1);
                return right + 1;
            }
            return -1;
        }
        
        private void dfs(TreeNode root, TreeNode target, int K, int length, List<Integer> res) {
            if (root == null) return;
            if (map.containsKey(root)) length = map.get(root);
            if (length == K) res.add(root.val);
            dfs(root.left, target, K, length + 1, res);
            dfs(root.right, target, K, length + 1, res);
        }
    https://leetcode.com/articles/all-nodes-distance-k-in-binary-tree/

    From root, say the target node is at depth 3 in the left branch. It means that any nodes that are distance K - 3 in the right branch should be added to the answer.
    Algorithm
    Traverse every node with a depth first search dfs. We'll add all nodes x to the answer such that node is the node on the path from x to target that is closest to the root.
    To help us, dfs(node) will return the distance from node to the target. Then, there are 4 cases:
    • If node == target, then we should add nodes that are distance K in the subtree rooted at target.
    • If target is in the left branch of node, say at distance L+1, then we should look for nodes that are distance K - L - 1 in the right branch.
    • If target is in the right branch of node, the algorithm proceeds similarly.
    • If target isn't in either branch of node, then we stop.
    In the above algorithm, we make use of the auxillary function subtree_add(node, dist) which adds the nodes in the subtree rooted at node that are distance K - dist from the given node.
    • Time Complexity: O(N), where N is the number of nodes in the given tree.
    • Space Complexity: O(N)

      List<Integer> ans;
      TreeNode target;
      int K;
      public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
          ans = new LinkedList();
          this.target = target;
          this.K = K;
          dfs(root);
          return ans;
      }

      // Return distance from node to target if exists, else -1
      public int dfs(TreeNode node) {
          if (node == null)
              return -1;
          else if (node == target) {
              subtree_add(node, 0);
              return 1;
          } else {
              int L = dfs(node.left), R = dfs(node.right);
              if (L != -1) {
                  if (L == K) ans.add(node.val);
                  subtree_add(node.right, L + 1);
                  return L + 1;
              } else if (R != -1) {
                  if (R == K) ans.add(node.val);
                  subtree_add(node.left, R + 1);
                  return R + 1;
              } else {
                  return -1;
              }
          }
      }

      // Add all nodes 'K - dist' from the node to answer.
      public void subtree_add(TreeNode node, int dist) {
          if (node == null) return;
          if (dist == K)
              ans.add(node.val);
          else {
              subtree_add(node.left, dist + 1);
              subtree_add(node.right, dist + 1);
          }
      }

    X.
    https://leetcode.com/problems/all-nodes-distance-k-in-binary-t
    ree/discuss/143798/1ms-beat-100-simple-Java-dfs-using-hashmap-with-explanation
    As we know, if the distance from a node to target node is k, the distance from its child to the target node is k + 1 unless the child node is closer to the target node which means the target node is in it's subtree.
    To avoid this situation, we need to travel the tree first to find the path from root to target, to:
    • store the value of distance in hashamp from the all nodes in that path to target
    Then we can easily use dfs to travel the whole tree. Every time when we meet a treenode which has already stored in map, use the stored value in hashmap instead of the value from its parent node.
    If we know the parent of every node x, we know all nodes that are distance 1 from x. We can then perform a breadth first search from the target node to find the answer.
    Algorithm
    We first do a depth first search where we annotate every node with information about it's parent.
    After, we do a breadth first search to find all nodes a distance K from the target.
    • Time Complexity: O(N), where N is the number of nodes in the given tree.

      Map<TreeNode,TreeNode> parent;

      public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        parent = new HashMap();
        dfs(root, null);

        Queue<TreeNode> queue = new LinkedList();
        queue.add(null);
        queue.add(target);

        Set<TreeNode> seen = new HashSet();
        seen.add(target);
        seen.add(null);

        int dist = 0;
        while (!queue.isEmpty()) {
          TreeNode node = queue.poll();
          if (node == null) {
            if (dist == K) {
              List<Integer> ans = new ArrayList();
              for (TreeNode n : queue)
                ans.add(n.val);
              return ans;
            }
            queue.offer(null);
            dist++;
          } else {
            if (!seen.contains(node.left)) {
              seen.add(node.left);
              queue.offer(node.left);
            }
            if (!seen.contains(node.right)) {
              seen.add(node.right);
              queue.offer(node.right);
            }
            TreeNode par = parent.get(node);
            if (!seen.contains(par)) {
              seen.add(par);
              queue.offer(par);
            }
          }
        }

        return new ArrayList<Integer>();
      }

      public void dfs(TreeNode node, TreeNode par) {
        if (node != null) {
          parent.put(node, par);
          dfs(node.left, node);
          dfs(node.right, node);
        }
      }

    //Method 1: use HashMap
    //1. build a undirected graph using treenodes as vertices, and the parent-child relation as edges
    //2. do BFS with source vertice (target) to find all vertices with distance K to it.
    class Solution {
        Map<TreeNode, List<TreeNode>> map = new HashMap();
    //here can also use Map<TreeNode, TreeNode> to only store the child - parent mapping, since parent-child mapping is inherent in the tree structure
        
        public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
             List<Integer> res = new ArrayList<Integer> ();
            if (root == null || K < 0) return res;
            buildMap(root, null); 
            if (!map.containsKey(target)) return res;
            Set<TreeNode> visited = new HashSet<TreeNode>();
            Queue<TreeNode> q = new LinkedList<TreeNode>();
            q.add(target);
            visited.add(target);
            while (!q.isEmpty()) {
                int size = q.size();
                if (K == 0) {
                    for (int i = 0; i < size ; i++) res.add(q.poll().val);
                    return res;
                }
                for (int i = 0; i < size; i++) {
                    TreeNode node = q.poll();
                    for (TreeNode next : map.get(node)) {
                        if (visited.contains(next)) continue;
                        visited.add(next);
                        q.add(next);
                    }
                }
                K--;
            }
            return res;
        }
        
        private void buildMap(TreeNode node, TreeNode parent) {
            if (node == null) return;
            if (!map.containsKey(node)) {
                map.put(node, new ArrayList<TreeNode>());
                if (parent != null)  { map.get(node).add(parent); map.get(parent).add(node) ; }
                buildMap(node.left, node);
                buildMap(node.right, node);
            }
        }    
    }
    
    //Method 2: No HashMap
    //kind of like clone the tree, in the meanwhile add a parent link to the node
    class Solution {
        private GNode targetGNode;
        
        private class GNode {
            TreeNode node;
            GNode parent, left, right;
            GNode (TreeNode node) {
                this.node = node;
            }
        }           
        
        public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
            List<Integer> res = new ArrayList<Integer> ();
            if (root == null || K < 0) return res;
            cloneGraph(root, null, target);
            if (targetGNode == null) return res;
            Set<GNode> visited = new HashSet<GNode>();
            Queue<GNode> q = new LinkedList<GNode>();
            q.add(targetGNode);
            visited.add(targetGNode);
            while (!q.isEmpty()) {
                int size = q.size();
                if (K == 0) {
                    for (int i = 0; i < size ; i++) res.add(q.poll().node.val);
                    return res;
                }
                for (int i = 0; i < size; i++) {
                    GNode gNode = q.poll();
                    if (gNode.left != null && !visited.contains(gNode.left)) { visited.add(gNode.left); q.add(gNode.left); }
                    if (gNode.right != null && !visited.contains(gNode.right)) { visited.add(gNode.right); q.add(gNode.right); }
                    if (gNode.parent != null && !visited.contains(gNode.parent)) { visited.add(gNode.parent); q.add(gNode.parent); }
                }
                K--;
            }
            return res;
        }
        
        private GNode cloneGraph(TreeNode node, GNode parent, TreeNode target) {
            if (node == null) return null;
            GNode gNode = new GNode(node);
            if (node == target) targetGNode = gNode;
            gNode.parent = parent;
            gNode.left = cloneGraph(node.left, gNode, target);
            gNode.right = cloneGraph(node.right, gNode, target);
            return gNode;
        }
    }
    
    https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/143886/Java-O(1)-space-excluding-recursive-stack-space

    https://leetcode.com/articles/all-nodes-distance-k-in-binary-tree/
    If we know the parent of every node x, we know all nodes that are distance 1 from x. We can then perform a breadth first search from the target node to find the answer.
    Algorithm
    We first do a depth first search where we annotate every node with information about it's parent.
    After, we do a breadth first search to find all nodes a distance K from the target.
    • Time Complexity: O(N), where N is the number of nodes in the given tree.
    • Space Complexity: O(N)
      Map<TreeNode, TreeNode> parent;

      public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        parent = new HashMap();
        dfs(root, null);

        Queue<TreeNode> queue = new LinkedList();
        queue.add(null);
        queue.add(target);

        Set<TreeNode> seen = new HashSet();
        seen.add(target);
        seen.add(null);

        int dist = 0;
        while (!queue.isEmpty()) {
          TreeNode node = queue.poll();
          if (node == null) {
            if (dist == K) {
              List<Integer> ans = new ArrayList();
              for (TreeNode n : queue)
                ans.add(n.val);
              return ans;
            }
            queue.offer(null);
            dist++;
          } else {
            if (!seen.contains(node.left)) {
              seen.add(node.left);
              queue.offer(node.left);
            }
            if (!seen.contains(node.right)) {
              seen.add(node.right);
              queue.offer(node.right);
            }
            TreeNode par = parent.get(node);
            if (!seen.contains(par)) {
              seen.add(par);
              queue.offer(par);
            }
          }
        }

        return new ArrayList<Integer>();
      }

      public void dfs(TreeNode node, TreeNode par) {
        if (node != null) {
          parent.put(node, par);
          dfs(node.left, node);
          dfs(node.right, node);
        }

      }

    X. Approach 2: Percolate Distance
    From root, say the target node is at depth 3 in the left branch. It means that any nodes that are distance K - 3 in the right branch should be added to the answer.
    Algorithm
    Traverse every node with a depth first search dfs. We'll add all nodes x to the answer such that node is the node on the path from x to target that is closest to the root.
    To help us, dfs(node) will return the distance from node to the target. Then, there are 4 cases:
    • If node == target, then we should add nodes that are distance K in the subtree rooted at target.
    • If target is in the left branch of node, say at distance L+1, then we should look for nodes that are distance K - L - 1 in the right branch.
    • If target is in the right branch of node, the algorithm proceeds similarly.
    • If target isn't in either branch of node, then we stop.
    In the above algorithm, we make use of the auxillary function subtree_add(node, dist) which adds the nodes in the subtree rooted at node that are distance K - dist from the given node.
    Time Complexity: O(N), where N is the number of nodes in the given tree.


      List<Integer> ans;
      TreeNode target;
      int K;

      public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        ans = new LinkedList<>();
        this.target = target;
        this.K = K;
        dfs(root);
        return ans;
      }

      // Return vertex distance from node to target if exists, else -1
      // Vertex distance: the number of vertices on the path from node to target
      public int dfs(TreeNode node) {
        if (node == null)
          return -1;
        else if (node == target) {
          subtree_add(node, 0);
          return 1;
        } else {
          int L = dfs(node.left), R = dfs(node.right);
          if (L != -1) {
            if (L == K)
              ans.add(node.val);
            subtree_add(node.right, L + 1);
            return L + 1;
          } else if (R != -1) {
            if (R == K)
              ans.add(node.val);
            subtree_add(node.left, R + 1);
            return R + 1;
          } else {
            return -1;
          }
        }
      }

      // Add all nodes 'K - dist' from the node to answer.
      public void subtree_add(TreeNode node, int dist) {
        if (node == null)
          return;
        if (dist == K)
          ans.add(node.val);
        else {
          subtree_add(node.left, dist + 1);
          subtree_add(node.right, dist + 1);
        }
      }

    TODO https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/143886/Java-O(1)-space-excluding-recursive-stack-space

    Labels

    LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

    Popular Posts