Showing posts with label Zenefits. Show all posts
Showing posts with label Zenefits. Show all posts

Saturday, July 15, 2017

52. N-Queens II

Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.



Solution:

This problem is a simplified version of N-Queens.

We use the same DFS to keep inserting queens to valid positions.

The only difference is that we do not need to draw the board.



Code:


public class Solution {
    public int sum;
    public int totalNQueens(int n) {
        sum = 0;
        if (n <= 0) {
            return sum;
        }
        int[] col = new int[n];
        helper(n, col, 0);
        return sum;
    }
    public void helper(int n, int[] col, int row) {
        if (row == n) {
            sum++;
            return;
        }
        for (int i = 0; i < n; i++) {
            col[row] = i;
            if (isValid(col, row)) {
                helper(n, col, row + 1);
            }
        }
    }
    public boolean isValid(int[] col, int row) {
        for (int i = 0; i < row; i++) {
            if (col[row] == col[i] || Math.abs(col[row] - col[i]) == row - i) {
                return false;
            }
        }
        return true;
    }
}

Tuesday, June 20, 2017

317. Shortest Distance from All Buildings

You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
  • Each 0 marks an empty land which you can pass by freely.
  • Each 1 marks a building which you cannot pass through.
  • Each 2 marks an obstacle which you cannot pass through.
For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):
1 - 0 - 2 - 0 - 1
|   |   |   |   |
0 - 0 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 1 - 0 - 0
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.
Note:
There will be at least one building. If it is not possible to build such house according to the above rules, return -1.



Solution:

To find the shortest distance from an empty land to all buildings, we can use BFS for each empty land  and find the minimum.

However, it is too slow.

Instead, we can use BFS from each building and find all distances to all empty lands and calculate the minimum.

We use two auxiliary array to store the aggregate distances to each point, and the number of times each point has been reached.

To calculate the minimum, we first check if the times to reach a point is exactly the number of buildings.



Code:


public class Solution {
    class Point {
        int x;
        int y;
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    public int m;
    public int n;
    public int[][]grid;

    public int shortestDistance(int[][] grid) {
        this.grid = grid;
        this.m = grid.length;
        this.n = grid[0].length;
        
        List<Point> houses = getPoints(1);
        int[][] times = new int[m][n];
        int[][] dist = new int[m][n];
        for (Point house : houses) {
            bfs(house, dist, times);
        }
        
        List<Point> lands = getPoints(0);
        int min = Integer.MAX_VALUE;
        for (Point land : lands) {
            if (times[land.x][land.y] == houses.size()) {
                min = Math.min(min, dist[land.x][land.y]);
            }
        }
        return min == Integer.MAX_VALUE ? -1 : min;
    }
    
    public void bfs(Point house, int[][] dist, int[][] times) {
        Queue<Point> queue = new LinkedList<>();
        boolean[][] hash = new boolean[m][n];
        queue.offer(house);
        hash[house.x][house.y] = true;
        
        int[] k = {1, 0, -1, 0, 1};
        int step = 0;
        while (!queue.isEmpty()) {
            step++;
            int size = queue.size();
            for (int s = 0; s < size; s++) {
                Point pt = queue.poll();
                for (int i = 0; i < 4; i++) {
                    Point nei = new Point(
                        pt.x + k[i], 
                        pt.y + k[i + 1]
                    );
                    if (!inBound(nei)) {
                        continue;
                    }
                    if (hash[nei.x][nei.y]) {
                        continue;
                    }
                    queue.offer(nei);
                    hash[nei.x][nei.y] = true;
                    times[nei.x][nei.y]++;
                    dist[nei.x][nei.y] += step;
                }
            }
        }
    }
    
    public List<Point> getPoints(int type) {
        List<Point> list = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == type) {
                    list.add(new Point(i, j));
                }
            }
        }
        return list;
    }
    
    public boolean inBound(Point pt) {
        if (pt.x < 0 || pt.x >= m || pt.y < 0 || pt.y >= n) {
            return false;
        }
        return grid[pt.x][pt.y] == 0;
    }
}

Thursday, June 15, 2017

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]



Solution:

We use DFS to find all possible solutions.

The rule we need to follow is:

1. number of "(" should < n, we can add a "(".

2. number of ")" should < number of "(", we can add a ")".



Code:


public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        helper(result, "", 0, 0, n);
        return result;
    }
    
    public void helper(List<String> result, String path, int left, int right, int count) {
        if (path.length() == count * 2) {
            result.add(path);
            return;
        }
        if (left < count) {
            helper(result, path + "(", left + 1, right, count);
        }
        if (right < left) {
            helper(result, path + ")", left, right + 1, count);
        }
    }
}

Saturday, June 10, 2017

207. Course Schedule

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, is it possible for you to finish all courses?
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 it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Note:
  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.
Hints:
  1. This problem is equivalent to finding if a cycle exists 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.



Solution:

This is a topological order question.

It asks whether the courses can be formed a topological order.

Therefore we use a count variable to store the number of courses that can form such order.

If it equals to the total number of courses, we return true.



Code:


public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<Integer>[] adj = new List[numCourses];
        for (int i = 0; i < numCourses; i++) {
            adj[i] = new ArrayList<Integer>();
        }
        int[] degree = new int[numCourses];
        for (int[] pair : prerequisites) {
            int courseFrom = pair[1];
            int courseTo = pair[0];
            adj[courseFrom].add(courseTo);
            degree[courseTo]++;
        }
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < degree.length; i++) {
            if (degree[i] == 0) {
                queue.offer(i);
            }
        }
        int count = 0;
        while (!queue.isEmpty()) {
            int course = queue.poll();
            count++;
            for (int nei : adj[course]) {
                degree[nei]--;
                if (degree[nei] == 0) {
                    queue.offer(nei);
                }
            }
        }
        return count == numCourses;
    }
}

Sunday, May 28, 2017

261. Graph Valid Tree

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
For example:
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.



Solution:

Method 1: BFS

If a graph is a valid tree, it satisfies:

1. If and only if the number of edges equals n - 1.

2. All n vertices are connected.

We use BFS to traverse the graph and store all reached vertices to a HashSet.

After traversing, we check if the size of HashSet is n.



Code:


public class Solution {
    public boolean validTree(int n, int[][] edges) {
        if (n == 0) {
            return false;
        }
        if (edges.length != n - 1) {
            return false;
        }
        
        ArrayList<Integer>[] adj = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            adj[i] = new ArrayList<Integer>();
        }
        for (int[] edge : edges) {
            adj[edge[0]].add(edge[1]);
            adj[edge[1]].add(edge[0]);
        }
        
        HashSet<Integer> set = new HashSet<>();
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);
        set.add(0);
        
        while (!queue.isEmpty()) {
            int v = queue.poll();
            for (int neighbor : adj[v]) {
                if (!set.contains(neighbor)) {
                    set.add(neighbor);
                    queue.offer(neighbor);
                }
            }
        }
        
        return set.size() == n;
    }
}



Method 2: Union Find


Code:

210. 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:
  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.
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.



Solution:

Kahn's algorithm

One of these algorithms, first described by Kahn (1962), works by choosing vertices in the same order as the eventual topological sort. First, find a list of "start nodes" which have no incoming edges and insert them into a set S; at least one such node must exist in a non-empty acyclic graph. Then:
L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
    remove a node n from S
    add n to tail of L
    for each node m with an edge e from n to m do
        remove edge e from the graph
        if m has no other incoming edges then
            insert m into S
if graph has edges then
    return error (graph has at least one cycle)
else 
    return L (a topologically sorted order)
If the graph is a DAG, a solution will be contained in the list L (the solution is not necessarily unique). Otherwise, the graph must have at least one cycle and therefore a topological sorting is impossible.

Reflecting the non-uniqueness of the resulting sort, the structure S can be simply a set or a queue or a stack. Depending on the order that nodes n are removed from set S, a different solution is created. A variation of Kahn's algorithm that breaks ties lexicographically forms a key component of the Coffman–Graham algorithm for parallel scheduling and layered graph drawing.



Code:


public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        ArrayList<Integer>[] adj = new ArrayList[numCourses];
        int[] indegree = new int[numCourses];
        int[] order = new int[numCourses];
        
        for (int i = 0; i < numCourses; i++) {
            adj[i] = new ArrayList<Integer>();
        }
        
        for (int[] pre : prerequisites) {
            adj[pre[1]].add(pre[0]);
            indegree[pre[0]]++;
        }
        
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] == 0) {
                queue.offer(i);
            }
        }
        
        int count = 0;
        while (!queue.isEmpty()) {
            int course = queue.poll();
            order[count++] = course;
            for (int neighbor : adj[course]) {
                indegree[neighbor]--;
                if (indegree[neighbor] == 0) {
                    queue.offer(neighbor);
                }
            }
        }
        
        if (count == numCourses) {
            return order;
        }
        
        return new int[0];
    }
}

Wednesday, May 10, 2017

125. Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.



Solution:

Use two pointers to check character pairs from two sides to the centre.

If the character is not a number of alphabetical letters we skip it.

When we check if two characters are equal, we check if they are equal numbers, or same alphabetical letters without cases.

Notice if x and y are numbers, we cannot check them by taking the difference and see if it is equal to 'A' - 'a'.



Code:


public class Solution {
    public boolean isPalindrome(String s) {
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            if (!isValid(s.charAt(i))) {
                i++;
                continue;
            }
            if (!isValid(s.charAt(j))) {
                j--;
                continue;
            }
            if (!isEqual(s.charAt(i), s.charAt(j))) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
    
    public boolean isValid(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
    }
    
    public boolean isEqual(char a, char b) {
        if (a >= '0' && a <= '9') {
            return a == b;
        }
        return (a == b) || (a == b - 'A' + 'a') || (b == a - 'A' + 'a');
    }
}

Monday, May 8, 2017

4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5



Solution:

If the total length of two sorted arrays is odd. the median is one number from the array. Otherwise, the median is the average of two numbers from the arrays.

We are actually trying to find the kth smallest number in two sorted arrays.

To find it, we check the (k / 2)-th smallest number (let's say valueA )in array A and (k / 2)-th smallest number (let's say valueB) in array B.

If valueA < valueB, we know we can safely remove all the numbers in array A which are smaller than valueA (including valueA itself). And reduce the problem to find (k - k / 2)-th smallest number in two sorted arrays.

If valueB > valueA, we know we can safely remove all the numbers in array B which are smaller than valueB (including valueB itself).

If we find either the remaining array A or B's length is smaller than k / 2, we know we cannot remove element in it. Thus we remove k / 2 elements from the other array.

The time complexity is O(log(m + n)).



Code:


public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len = nums1.length + nums2.length;
        if (len % 2 == 0) {
            return (findKthElement(nums1, 0, nums2, 0, len / 2) + findKthElement(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0;
        }
        return findKthElement(nums1, 0, nums2, 0, len / 2 + 1);
    }
    
    public int findKthElement(int[] A, int startA, int[] B, int startB, int k) {
        if (startA >= A.length) {
            return B[startB + k - 1];
        }
        if (startB >= B.length) {
            return A[startA + k - 1];
        }
        if (k == 1) {
            return Math.min(A[startA], B[startB]);
        }
        
        int valueInA = startA + k / 2 - 1 < A.length ? A[startA + k / 2 - 1] : Integer.MAX_VALUE;
        int valueInB = startB + k / 2 - 1 < B.length ? B[startB + k / 2 - 1] : Integer.MAX_VALUE;
        
        if (valueInA < valueInB) {
            return findKthElement(A, startA + k / 2, B, startB, k - k / 2);
        }
        return findKthElement(A, startA, B, startB + k / 2, k - k / 2);
    }
}

Wednesday, May 3, 2017

20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.



Solution:

If we find a left parenthesis, we push its right parenthesis into the stack.

If we find a non-left parenthesis character, we pop the stack and check if there's a match. If not, simply return false.



Code:

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(')');
            }
            else if (c == '[') {
                stack.push(']');
            }
            else if (c == '{') {
                stack.push('}');
            }
            else if (stack.isEmpty() || stack.pop() != c) {
                return false;
            }
        }
        
        return stack.isEmpty();
    }
}

Tuesday, May 2, 2017

146. LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4



Solution:

The idea is to have a doubly linked list to cache elements. The most recent element will be put into the tail.

We also maintains a HashMap to mapping a key to each element.

In a get operation, we try to find the node in HashMap and put it to the tail.

In a put operation, if the node exists, we put it to the tail and update its value. If it does not exist, we create a new node and put it to the tail. In the meantime, we check if the cache is full.

If the cache is full, we need to remove the mapping of the head in the linked list.

We use a dummy head and a dummy tail for convenience.



Code:


public class LRUCache {
    
    class ListNode {
        int key;
        int value;
        ListNode prev;
        ListNode next;
        public ListNode(int key, int value) {
            this.key = key;
            this.value = value;
            ListNode prev = null;
            ListNode next = null;
        }
    }
    private int capacity;
    private HashMap<Integer, ListNode> map;
    private ListNode head;
    private ListNode tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        head = new ListNode(-1, -1);
        tail = new ListNode(-1, -1);
        head.next = tail;
        tail.prev = head;
        map = new HashMap<>();
    }
    
    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        ListNode node = map.get(key);
        node.prev.next = node.next;
        node.next.prev = node.prev;
        moveToTail(node);
        
        return node.value;
    }
    
    public void put(int key, int value) {
        if (get(key) != -1) {
            map.get(key).value = value;
            return;
        }
        
        if (map.size() == this.capacity) {
            map.remove(head.next.key);
            head.next = head.next.next;
            head.next.prev = head;
        }
        
        ListNode node = new ListNode(key, value);
        map.put(key, node);
        moveToTail(node);
    }
    
    public void moveToTail(ListNode node) {
        node.prev = tail.prev;
        tail.prev.next = node;
        tail.prev = node;
        node.next = tail;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

Sunday, April 30, 2017

200. Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3



Solution:

Method 1: DFS

Go through the grid. If we find a '1', use DFS to find all connected '1's and set them to '0'. And increase the number of islands by 1.

Since all points in this island are set to '0' after traversal. We will not check these points any more.

Each point in the grid is checked exactly twice (one from for loop and one from dfs). The time complexity is O(mn) where m and n are the dimension of the grid.



Code:


public class Solution {
    
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        if (grid[0] == null || grid[0].length == 0) {
            return 0;
        }
        int m = grid.length;
        int n = grid[0].length;
        int islands = 0;
        
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    dfs(grid, i, j);
                    islands++;
                }
            }
        }
        
        return islands;
    }
    
    public void dfs(char[][] grid, int x, int y) {
        if (x < 0 || x >= grid.length || 
            y < 0 || y >= grid[0].length || 
            grid[x][y] == '0') {
            
            return;
        }
        grid[x][y] = '0';
        dfs(grid, x - 1, y);
        dfs(grid, x + 1, y);
        dfs(grid, x, y - 1);
        dfs(grid, x, y + 1);
    }
}




Method 2: BFS

Time complexity is O(n) and space complexity is O(n).



Code:


public class Solution {
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        if (grid[0] == null || grid[0].length == 0) {
            return 0;
        }
        int m = grid.length;
        int n = grid[0].length;
        int islands = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    bfs(grid, i, j);
                    islands++;
                }
            }
        }
        return islands;
    }
    public void bfs(char[][] grid, int i, int j) {
        int m = grid.length;
        int n = grid[0].length;
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(i * n + j);
        HashSet<Integer> set = new HashSet<>();
        set.add(i * n + j);
        while (!queue.isEmpty()) {
            int coordinate = queue.poll();
            int x = coordinate / n;
            int y = coordinate % n;
            grid[x][y] = '0';
            int[] k = new int[] {1, 0, -1, 0, 1};
            for (int p = 0; p < 4; p++) {
                int newx = x + k[p];
                int newy = y + k[p + 1];
                if (!set.contains(newx * n + newy)) {
                    if (newx >= 0 && newx < m && newy >= 0 && newy < n) {
                        if (grid[newx][newy] == '1') {
                            queue.offer(newx * n + newy);
                            set.add(newx * n + newy);
                        }
                    }
                }
            }
        }
    }
}



Method 3: Union-Find