Showing posts with label Two Sigma. Show all posts
Showing posts with label Two Sigma. Show all posts

Saturday, July 8, 2017

547. Friend Circles

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:
Input: 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. 
The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input: 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, 
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Note:
  1. N is in range [1,200].
  2. M[i][i] = 1 for all students.
  3. If M[i][j] = 1, then M[j][i] = 1.



Solution:

We can use Union-Find to connect all connected components.

Initially we set the number of components to the number of elements.

While traveling all elements and union friends, if the root of two components are not the same, we union them and decrease the number of components by 1.

The time complexity is O(n2) and the space complexity is O(n).



Code:


public class Solution {
    public int component;
    public int findCircleNum(int[][] M) {
        int n = M.length;
        this.component = n;
        int[] root = new int[n];
        for (int i = 0; i < n; i++) {
            root[i] = i;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if(i != j && M[i][j] == 1) {
                    union(root, j, i);
                }
            }
        }
        return component;  
    }
    public int find(int[] root, int i) {
        while (i != root[i]) {
            root[i] = root[root[i]];
            i = root[i];
        }
        return i;
    }
    public void union(int[] root, int p, int q) {
        int i = find(root, p);
        int j = find(root, q);
        if (i != j) {
            root[i] = j;
            component--;
        }       
    }
}

Sunday, June 25, 2017

289. Game of Life

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state.
Follow up: 
  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?



Solution:

In order to do in-place, we set four states: 0, 1, 2, 3.

The states means [next state, current state] in binary representation.

For example,

0: 00 means current state is 0 and next state is 0.
1: 01 means current state is 1 and next state is 0.
2: 10 means current state is 0 and next state is 1.
3: 11 means current state is 1 and next state is 1.

In each round, we only have 0 and 1 in the grid, which means by default the next state is always 0.

For each cell, we can count the number of other living cells around it.

If the cell is a live cell, and it's surrounded by 2 or 3 live cells, it can live in the next round.

We set its value to 3.

If a cell is a dead cell, and it's surrounded by 3 live cells, it can live in the next round.

We set its value to 2.

In all other cases, the cell will dead.

Since the initial value of the next state is 0, we do not need to do anything.

After counting neighbors of all cells, we update the entire whole states in-place.

Simply, go through all cells and shift a bit to the right to discard the current states.

Again, after shifting the value of the new next states are initialized to 0.



Code:


public class Solution {
    public void gameOfLife(int[][] board) {
        if (board == null || board.length == 0) {
            return;
        }
        if (board[0] == null || board[0].length == 0) {
            return;
        }
        int m = board.length;
        int n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int live = countLive(board, m, n, i, j);
                if (board[i][j] == 1 && (live == 2 || live == 3)) {
                    board[i][j] = 3;
                }
                if (board[i][j] == 0 && live == 3) {
                    board[i][j] = 2;
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j] >>= 1;
            }
        }
    }
    public int countLive(int[][] board, int m, int n, int x, int y) {
        int live = 0;
        for (int i = Math.max(x - 1, 0); i <= Math.min(x + 1, m - 1); i++) {
            for (int j = Math.max(y - 1, 0); j <= Math.min(y + 1, n - 1); j++) {
                live += (board[i][j] & 1);
            }
        }
        live -= (board[x][y] & 1);
        return live;
    }
}

Wednesday, June 14, 2017

349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
  • Each element in the result must be unique.
  • The result can be in any order.



Solution:

Method 1: HashSet

Put all elements from nums1 to the HashSet.

Check every element in nums2.

If it is in the HashSet, this element is an intersection element.

The time complexity is O(n) and the space complexity is O(n);



Code:


public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> set = new HashSet<>();
        for (int num : nums1) {
            set.add(num);
        }
        HashSet<Integer> intersect = new HashSet<>();
        for (int num : nums2) {
            if (set.contains(num)) {
                intersect.add(num);
            }
        }
        int res[] = new int[intersect.size()];
        int i = 0;
        for (int key : intersect) {
            res[i++] = key;
        }
        return res;
    }
}



Method 2: Two Pointers

Sort two arrays.

Use two pointers from the beginning of two arrays.

Advance one pointer if it points to a smaller number.

If two pointer points to same value elements, this number is an intersection element.

The time complexity is O(nlogn).



Code:


public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> intersect = new HashSet<>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0;
        int j = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] < nums2[j]) {
                i++;
            }
            else if (nums1[i] > nums2[j]) {
                j++;
            }
            else {
                intersect.add(nums1[i]);
                i++;
                j++;
            }
        }
        i = 0;
        int res[] = new int[intersect.size()];
        for (int key : intersect) {
            res[i++] = key;
        }
        return res;
    }
}



Method 3: Binary Search

Sort one array.

Go through the other array.

For every element, use binary search to check if it is in the sorted array.

The time complexity is O(nlogn).



Code:


public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> intersect = new HashSet<>();
        Arrays.sort(nums2);
        for (int num : nums1) {
            if (search(nums2, num)) {
                intersect.add(num);
            }
        }
        int[] res = new int[intersect.size()];
        int i = 0;
        for (int key : intersect) {
            res[i++] = key;
        }
        return res;
    }
    public boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        int start = 0;
        int end = nums.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] >= target) {
                end = mid;
            }
            else {
                start = mid;
            }
        }
        return nums[start] == target || nums[end] == target;
    }
}

Wednesday, June 7, 2017

342. Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?



Solution:

If a number is power of four, it must be power of two.

If a number is power of two, it only has one 1 in binary representation.

If a number is power of four, it minus 1 can be divided by 3.

Let's say 4n-1 = (2n+1) x (2n - 1).

Any three consecutive number, there must be one that can be divided by 3.

So in 2n + 1, 2n, 2n - 1, we know 2n cannot be divided by 3.

Therefore, either 2n + 1 or 2n - 1 can be divided by 3.



Code:

public class Solution {
    public boolean isPowerOfFour(int num) {
        return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
    }
}

Sunday, May 28, 2017

44. Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false



Solution:

Method 1: Two Pointers

We use two pointers.

One points to the string and one points to the pattern.

When we find a '?' in the pattern, we advance two pointers.

When we find a '*' in the pattern, we mark the current index of the string and the current index of the '*'. And start to do the match from mark and star + 1.

If we cannot find match, we go back to mark + 1 and star + 1 and try to match. (Every time we backtrack, we need to increase mark by 1.)

Worst case time complexity is O(mn).

The space complexity is O(1).



Code:


public class Solution {
    public boolean isMatch(String s, String p) {
        int i = 0;
        int j = 0;
        int mark = 0;
        int star = -1;
        while (i < s.length()) {
            if (j < p.length() && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '?')) {
                i++;
                j++;
            }
            else if (j < p.length() && p.charAt(j) == '*') {
                mark = i;
                star = j;
                j++;
            }
            else if (star != -1) {
                mark++;
                i = mark;
                j = star + 1;
            }
            else {
                return false;
            }
        }
        while (j < p.length() && p.charAt(j) == '*') {
            j++;
        }
        return j == p.length();
    }
}



Method 2: Dynamic Programming


Code: