Showing posts with label Bit Manipulation. Show all posts
Showing posts with label Bit Manipulation. Show all posts

Monday, June 26, 2017

320. Generalized Abbreviation

Write a function to generate the generalized abbreviations of a word.
Example:
Given word = "word", return the following list (order does not matter):
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]



Solution:

Method 1: DFS

We use DFS to search for all valid outputs.

When we go through the word and check every character, in any character, we can do two things:

1. Abbreviate this character.

2. Do not abbreviate this character.

In the first case, we just pass the current states to the next recursion.

In the second, case, we need to add the previously abbreviated count to the current path, with the current character, and pass it to the next recursion.



Code:


public class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> result = new ArrayList<>();
        helper(word, result, "", 0, 0);
        return result;
    }
    public void helper(String word, List<String> result, String path, int count, int pos) {
        if (pos == word.length()) {
            if (count > 0) {
                path += count;
            }
            result.add(path);
            return;
        }
        else {
            // abbreviate this character
            helper(word, result, path, count + 1, pos + 1);
            
            // do not abbreviate this character
            helper(word, result, path + (count > 0 ? count : "") + word.charAt(pos), 0, pos + 1);
        }
    }
}



Method 2: Bit Manipulation (Iterative)

We can use the binary representation of two to the power of the number's length, to have a mapping with each character in the word.

Let's see an example of "word":

0000 word
0001 wor1
0010 wo1d
0011 wo2
0100 w1rd
0101 w1r1
0110 w2d
0111 w3
1000 1ord
1001 1or1
1010 1o1d
1011 1o2
1100 2rd
1101 2r1
1110 3d
1111 4

Notice that when we have a 1, the corresponding character is abbreviated.

When we have a 0, we keep this character.



Code:


public class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < Math.pow(2, word.length()); i++) {
            int count = 0;
            String abbr = "";
            for (int j = 0; j < word.length(); j++) {
                if (((i >> j) & 1) == 1) {
                    count++;
                }
                else {
                    if (count != 0) {
                        abbr += count;
                        count = 0;
                    }
                    abbr += word.charAt(j);
                }
            }
            if (count != 0) {
                abbr += count;
            }
            result.add(abbr);
        }
        return result;
    }
}

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;
    }
}

393. UTF-8 Validation

A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
  1. For 1-byte character, the first bit is a 0, followed by its unicode code.
  2. For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.
This is how the UTF-8 encoding would work:
   Char. number range  |        UTF-8 octet sequence
      (hexadecimal)    |              (binary)
   --------------------+---------------------------------------------
   0000 0000-0000 007F | 0xxxxxxx
   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Given an array of integers representing the data, return whether it is a valid utf-8 encoding.
Note:
The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.
Example 1:
data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.

Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
Example 2:
data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100.

Return false.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.



Solution:

We check the first several bits of the element and determine how many trailing elements start with "10" it should have.

If the first three bits are "110", there are 1 trailing elements.

If the first three bits are "1110", there are 2 trailing elements.

If the first three bits are "11110", there are 3 trailing elements.

Otherwise if the first bit is "1", this is an invalid element, we return false.

When we check the trailing element, if it is not start with "10", we return false.



Code:


public class Solution {
    public boolean validUtf8(int[] data) {
        int count = 0;
        for (int d : data) {
            if (count == 0) {
                if ((d >> 5) == 0b110) {
                    count = 1;
                }
                else if ((d >> 4) == 0b1110) {
                    count = 2;
                }
                else if ((d >> 3) == 0b11110) {
                    count = 3;
                }
                else if ((d >> 7) == 1) {
                    return false;
                }
            }
            else {
                if ((d >> 6) != 0b10) {
                    return false;
                }
                count--;
            }
        }
        return count == 0;
    }
}

Saturday, June 24, 2017

389. Find the Difference

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.



Solution:

XOR all elements.

Pairs will cancel out.



Code:


public class Solution {
    public char findTheDifference(String s, String t) {
        char xor = 0;
        for (char c : s.toCharArray()) {
            xor ^= c;
        }
        for (char c : t.toCharArray()) {
            xor ^= c;
        }
        return xor;
    }
}

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;
    }
}

231. Power of Two

Given an integer, write a function to determine if it is a power of two.



Solution:

The binary representations of the numbers that are power of 2s' are:

2 -> 10
4 -> 100
8 -> 1000
16 -> 10000

And all these numbers are positive numbers.



Code:


public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
}

Tuesday, June 6, 2017

29. Divide Two Integers

Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.



Solution:

There are a few corner case to deal with first.

To avoid overflow, we set dividend and divisor to long.

The idea is try to double divisor each time and check until it exceeds dividend.

When this happens, we can subtract the dividend by previous doubled divisor, and increase the result.

We do it again until dividend < divisor.



Code:

public class Solution {
    public int divide(int dividend, int divisor) {
        if (divisor == 0) {
            return dividend >= 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
            return Integer.MAX_VALUE;
        }
        int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1;
        long a = Math.abs((long) dividend);
        long b = Math.abs((long) divisor);
        int result = 0;
        while (a >= b) {
            int shift = 0;
            while (a >= (b << shift)) {
                shift++;
            }
            a -= (b << (shift - 1));
            result += (1 << (shift - 1));
        }
        return sign * result;
    }
}

Sunday, June 4, 2017

78. Subsets

Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]



Solution:

Method 1: DFS

Use DFS to traverse all possible combinations and store all of them into results.

To keep the subsets in order, we first sort the input array.



Code:


public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return result;
        }
        helper(nums, result, new ArrayList<Integer>(), 0);
        return result;
    }
    
    public void helper(int[] nums, List<List<Integer>> result, List<Integer> list, int pos) {
        result.add(new ArrayList<Integer>(list));
        
        for (int i = pos; i < nums.length; i++) {
            list.add(nums[i]);
            helper(nums, result, list, i + 1);
            list.remove(list.size() - 1);
        }
    }
}



Method 2: Bitset


Sunday, May 28, 2017

477. Total Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2

Output: 6

Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Note:
  1. Elements of the given array are in the range of 0 to 10^9
  2. Length of the array will not exceed 10^4.



Solution:

Any number can be represented as a 32-bit binary code.

If we have n numbers, for each binary position, we count the 1s' of all n numbers as bitCount.

The hamming distance between all these n numbers at this position is bitCount * (n - bitCount).

Therefore, after going through all 32 positions, we add up the hamming distances in each position and output the result.

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



Code:


public class Solution {
    public int totalHammingDistance(int[] nums) {
        int total = 0;
        int n = nums.length;
        for (int j = 0; j < 32; j++) {
            int bitCount = 0;
            for (int i = 0; i < n; i++) {
                bitCount += (nums[i] >> j) & 1;
            }
            total += bitCount * (n - bitCount);
        }
        return total;
    }
}

Saturday, May 27, 2017

461. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.



Solution:

We can use xor on a and b such that all their bits in difference become 1.

The problem becomes to count the 1s of a number.



Code:


public class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int count = 0;
        while (xor != 0) {
            xor = xor & (xor - 1);
            count++;
        }
        return count;
    }
}

Thursday, May 4, 2017

191. Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.



Solution:

n & (n - 1) will eliminate a 1 in binary representation.

Therefore we keep doing this until n becomes zero, which means no more 1s in binary representation.



Code:


public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n = n & (n - 1);
            count++;
        }
        return count;
    }
}

Monday, May 1, 2017

268. Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?



Solution:

There is one missing number between 0 and n. Let's say it's x.

If we want to find it, we can xor these number with 0, 1, ..., n to cancel out the duplicate pairs.

result = 0 ^ 0 ^ 1 ^ 1 ^ ... ^ x ^ (x + 1) ^ (x + 1) ^ ... ^ n ^ n = x, which is the missing number.

We use the index as 0 ~ n - 1, and nums.length as n.

The time complexity is O(n) and space complexity is O(1).



Code:


public class Solution {
    public int missingNumber(int[] nums) {
        int xor = 0;
        for (int i = 0; i < nums.length; i++) {
            xor = xor ^ i ^ nums[i];
        }
        return xor ^ nums.length;
    }
}