AdSense

Friday, January 2, 2015

Median of Two Sorted Arrays

There are two sorted arrays A and B 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)).

This problem is an implementation of the Find k-th smallest number in two sorted array .

Note that if the total number of elements of two arrays is odd, we need to find the( (A.length + B.length) / 2 + 1 )-th element. If it is even, we need to find that number and the number before that and take the average.

The following code compares between B[j - 1] and A[i], and thus reduces the comparison among B[j - 1], A[i] and B[j]. This may reduce couple lines of code. Yet the trade-off is that each time we only discard 1/4 of the total number of elements in each recursion, even though the solution can still be accepted.

I prefer to write couple more lines. :)



public class Solution {
    public double findMedianSortedArrays(int A[], int B[]) {
        if (A == null || B == null)
            throw new NullPointerException("Null array(s)!");
        if (A.length == 0 && B.length == 0)
            return 0.0;
        int len = A.length + B.length;
        if (len % 2 != 0)
            return (double)findMedian(A, 0, B, 0, len / 2 + 1);
        int r1 = findMedian(A, 0, B, 0, len / 2);
        int r2 = findMedian(A, 0, B, 0, len / 2 + 1);
        double rst = (double)(r1 + r2) / 2.0;
        return rst;
        
    }
    private int findMedian(int[] A, int A_start, int[] B, int B_start, int k) {
        if (A_start >= A.length)
            return B[B_start + k - 1];
        if (B_start >= B.length)
            return A[A_start + k - 1];
        if (k == 1)
            return Math.min(A[A_start], B[B_start]);
        //A_key = k / 2 - 1
        //B_key - 1 = k / 2 - 1
        int index_A = A_start + k / 2 - 1;
        int index_B = B_start + k / 2 - 1;
        int A_i = (index_A >= A.length) ? Integer.MAX_VALUE : A[index_A];
        int B_i = (index_B >= B.length) ? Integer.MAX_VALUE : B[index_B];
        if (A_i < B_i)
            return findMedian(A, index_A + 1, B, B_start, k - k / 2);
        else
            return findMedian(A, A_start, B, index_B + 1, k - k / 2);
    }
}

Update: 2015 - 01 - 15
I realize that if I use the code in the post Find k-th smallest number in two sorted array, it will exceed time limit.

Find k-th smallest number in two sorted array

The algorithm is explained here.

I will explain it briefly based on my understanding. Choose any index in array A, say i. Choose a corresponding index in array B, say j,  that maintain the equivalence i + j = k - 1. Then the k-th smallest element can be acquired if one of the following conditions is fulfilled:

1. if k == 1, return the smallest between the first elements in A and B;
2. if (B[j - 1] <= A[i] < B[j +1]), then return A[i].
3. if (A[i - 1] <= B[j] < A[i] ), then return B[j].

Condition 2 and 3 are similar, take 2 as the example.






If A[i] is between B[j -1] and B[j], and there are i elements before A[i] and j elements before B[j], and because k = i + j + 1, then A[i] is the k-th smallest element we are looking for. 

Well, life would be perfect if one of the above conditions can always be fulfilled, what if not? 

So, if A[i] is not greater than or equal to B[j -1], but A[i] is smaller than B[j], what does that imply? It means A[i] must also be smaller than B[j - 1], and since k = i + j + 1, it must not be in A[i] and all elements less than A[i]. Then we can discard that part of the array. (Switch j - 1 and i in the figure to make it easier to understand). Likewise, we may conclude that all elements larger than B[j] will also not be in the range.  Similarly, we can discard corresponding elements if B[j] is smaller than A[i]. Good, we just halve the total array. 

And the solution will get by... Recursion! 

I follow the author of my reference and choose i and j  based on the weights of the lengths of two arrays. Alternatively, we can choose k/2 or anything else as long as both i and j are smaller than the lengths of A and B. 







public class FindKthSmallest {
 public int findKth(int[] A, int[] B, int k) {
  if (A == null || A.length == 0 || B == null || B.length == 0 
    || k < 0 || k > A.length + B.length)
   throw new IllegalArgumentException("Invalid input!");
  return findKthSmallest(A, 0, A.length, B, 0, B.length, k);
 }
 public int findKthSmallest(int[] A, int A_start, int la, int[] B, int B_start, int lb, int k) {
  if (A_start >= A.length)
   return B[B_start + k - 1];
  if (B_start >= B.length)
   return A[A_start + k - 1];
  if (k == 1)
   return Math.min(A[A_start], B[B_start]);
  
  //choose index based on the weight of length of A and B
  int A_key = (int) ((double) la / (la + lb) * (k - 1));
  int B_key = (k - 1) - A_key;
  //note the actual index will be A_start + A_key
  int index_A = A_start + A_key;
  int index_B = B_start + B_key;
  //index_A == 0: la = 1; lb = 10; k = 3; index_A = (1/11 *3) = 0
  int A_i_1 = (index_A == 0) ? Integer.MIN_VALUE : A[index_A - 1];
  int B_j_1 = (index_B == 0) ? Integer.MIN_VALUE : B[index_B - 1];
  //index_A == la: la = 10; lb = 1; k = 11; index_A = 10/11 * 11 = 10
  int A_i = (index_A == la) ? Integer.MAX_VALUE : A[index_A];
  int B_j = (index_B == lb) ? Integer.MAX_VALUE : B[index_B];
  
  if (B_j_1 <= A_i && A_i < B_j) 
   return A_i;
  if (A_i_1 <= B_j && B_j < A_i)
   return B_j;
  //if A_i < B_j and apparently from above A_i is NO larger than B_j_1
  if (A_i < B_j) 
   //discard A_i and below
   //length = la - (index_A - A_start + 1) = la - A_key -1
   return findKthSmallest(A, index_A + 1, la - A_key - 1, B, B_start, B_key + 1, k - A_key - 1);
  else
   return findKthSmallest(A, A_start, A_key + 1, B, index_B + 1, lb - B_key - 1, k - B_key - 1);
  
 }
}

Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9].
(order does not matter).

Two maps are used to store the words in the list and those in the string.  I used two hash sets at first because I didn't realize that duplicates are allowed in the list. For example, "aaa" and ["a", "a"].

Another mistake I made was that the increment of index in S cannot be the word length in the list, since those that are not in the list can be in any length. For example, "afoobar" and ["foo", "bar"].

The inner loop is used to check if the substring is a concatenation of all words in the list. Thus, index i becomes the starting index of the substring, which will be added into the result list if all conditions are satisfied.

If any condition is not satisfied, e.g., the substring cannot be found in the list, or the word occurs more than once, we break the inner loop and start from the next index.

The map is cleared at the beginning of every outer loop. If an index is found, or if a concatenation cannot be found from the last index, everything inside the map is useless. We need to start all over again. :)

Update: 2015 - 01 - 15
Walk through:
1. Store all strings in the list to a map.
2. Since all strings in the list needs to be included, the loop will exit at S.length() - L.length * L[0].length().
3. Use another loop to check for the concatenation of the words in the list. Use count to check if all strings in the list are included.
    1. If the substring that equals to the length of the words is not in the list map, break;
    2. If the number of any string in the list exceeds the number of that string in the list, break;
4. Add the start index if count == L.length.
5. Increment index, clear map.


public class SubstringWithConcatenation {
    public List findSubstring(String S, String[] L) {
        if (S == null || L == null)
            throw new NullPointerException("Null string or list!");
        List rst = new ArrayList ();
        if (S.length() == 0 || L.length == 0)
            return rst;
        int len = L[0].length();
        if (len > S.length())
            return rst;
        HashMap L_map = new HashMap ();
        for (int i = 0; i < L.length; i++) {
            if (!L_map.containsKey(L[i]))
                L_map.put(L[i], 1);
            else
                L_map.put(L[i], L_map.get(L[i]) + 1);
        }
        HashMap hm = new HashMap ();
        for (int i = 0; i <= S.length() - L.length * len; i++) {
            hm.clear();
            int count = 0;
            for (count = 0; count < L.length; count++) {
                int pos = i + count * len;
                String tmp = S.substring(pos, pos + len);
                if (!L_map.containsKey(tmp)) 
                    break;
                if (!hm.containsKey(tmp)) {
                        hm.put(tmp, 1);
                }
                else {
                    hm.put(tmp, hm.get(tmp) + 1);
                    if (hm.get(tmp) > L_map.get(tmp))
                        break;
                }
            }
            if (count == L.length)
                rst.add(i);
        }
        return rst;
    }
}

Thursday, January 1, 2015

Find missing integer -- Bit manipulation


An array A[1...n] contains all the integers from 0 to n except for one number which is missing.In this problem, we cannot access an entire integer in A with a single operation.The elements of A are represented in binary, and the only operation we can use to access them is “fetch the jth bit of A[i]”, which takes constant time.Write code to find the missing integer.Can you do it in O(n) time?

I am not good at bit manipulation, and that's the reason every such problem becomes so interesting to me. This one, we need to implement a method for the very easy question: search a missing integer in an array. And no, no array traversal, only bit operation is allowed.

So, considering any array of integers that are in binary representations, what will it look like? 0s and 1s, right? Then, what will the least significant digit of numbers look like?

For any array, it will be like:

0 1 0 1 0 1

or

0 1 0 1 0 1 0

depending on if n is an odd number or even number. So from the above array, we can make a conclusion that the number of 0s in the array is always >= the number of 1s in the array.

Next, what will happen if an odd number is removed? The number of 1s will be strictly smaller than the number of 0s. And alternatively, if we remove an even number, the number of 1s will be >= the number of 0s.

Ok, now all we need to do is to separate the lists to 0s and 1s and check which one has the larger size.
If we have determined that 1 (0) is removed, we pretty much can get rid of half of the list. If 1 is removed, it definitely is an odd number so we only have to check the odd number list and alternatively if 0 is removed, we only need to look at the even number list.

The problem is almost solved. What's next? We move to the next digit! Yup, recursion.

So, what about complexity? Is it O(n)?

Well, let's see, at the beginning of the recursion, i.e., when we check the least significant digit, we go through the whole array, so it takes O(n) time. Then the next recursion, O(n/2) time since we only check half of the input array, and then.... yeah, you get it?

O(n) + O(n/2) + O(n/4) + ... =O(2n) = O(n).

A-ha!, it is O(n)!


public class BitInteger {
 public static final int INTEGER_SIZE = 32;
 private boolean[] bits;
 public BitInteger() {
  bits = new boolean[INTEGER_SIZE];
 }
 public BitInteger(int value) {
  bits = new boolean[INTEGER_SIZE];
  for (int j = 0; j < INTEGER_SIZE; j++) {
   if (((value >> j) & 1) == 1)
    bits[INTEGER_SIZE - 1 - j] = true;  
  }
 }
 public int fetch(int k) {
  if (bits[k])
   return 1;
  else
   return 0;
 }
 public void set (int k, int bitValue) {
  if (bitValue == 0)
   bits[k] = false;
  else
   bits[k] = true;
 }
 public void set (int k, char bitValue) {
  if (bitValue == '0')
   bits[k] = false;
  else
   bits[k] = true;
 }
 public void set(int k, boolean bitValue) {
  bits[k] = bitValue;
 }
 public void swapValues(BitInteger number) {
  for (int i = 0; i < INTEGER_SIZE; i++) {
   int tmp = number.fetch(i);
   number.set(i, this.fetch(i));
   this.set(i, tmp);
  }
 }
 public int toInt() {
  int number = 0;
  for (int j = INTEGER_SIZE - 1; j >= 0; j--) {
   number = number | fetch(j);
   if (j > 0)
    number = number << 1;
  }
  return number;
 }

}
public class FindMissing {
 public int findMissing(ArrayList input) {
  return theMissingNumber(input, BitInteger.INTEGER_SIZE - 1);
 }
 private int theMissingNumber(ArrayList input, int column) {
  if (column < 0)
   return 0;
  ArrayList oddIndices = new ArrayList ();
  ArrayList evenIndices = new ArrayList ();
  for (int i = 0; i < input.size(); i++) {
   if (input.get(i).fetch(column) == 0) 
    evenIndices.add(input.get(i));
   if (input.get(i).fetch(column) == 1)
    oddIndices.add(input.get(i));
  }
  if (evenIndices.size() > oddIndices.size()) 
   return (theMissingNumber(oddIndices, column - 1) << 1) | 1;
  else
   return (theMissingNumber(evenIndices, column - 1) << 1) | 0;
 }

}

Search in Rotated Sorted Array I & II

Search in Rotated Sorted Array |
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.

The first one is just Binary Search. If A[start] <A[mid], it means the rotation is in the second half of the array, accordingly we can choose the start point or end point based on the target value. If A[start] > A[mid], the the rotation is in the first half.

public class SearchRotatedArray {
    public int search(int[] A, int target) {
        if (A == null)
            throw new NullPointerException("Null Array!");
        if (A.length == 0)
            return -1;
        int start = 0;
        int end = A.length - 1;
        while (start < end) {
            int mid = (start + end) / 2;
            if (A[mid] == target)
                return mid;
            if (A[start] < A[mid]) {
                if (A[start] == target)
                    return start;
                if (A[start] < target && target < A[mid]) 
                    end = mid - 1;
                else 
                    start = mid + 1;
            }
            else {
                if (target == A[end])
                    return end;
                if (A[mid] < target && target < A[end])
                    start = mid + 1;
                else
                    end = mid - 1;
            }
            
        }
        if (A[start] == target)
            return start;
        return -1;
    }
}


Search in Rotated Sorted Array ||
Duplicates allowed
The second problem. Since duplicates are allowed, A[start] <= A[mid] cannot tell if the rotation is in the first half or the second half. Of course we can separate the case to A[start] < A[mid] and A[start] == A[mid]. However, for the second case, what's next? We still have to go through every element to find the pivot, and the complexity will not be significantly less than O(n), especially for cases where there are lots of duplicates. So, why not just go through all the elements?


Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
First, if you are interested in the rule, see here.

So, a method to check if the added number is valid is necessary. A hashset is used. Basically, check the entire row, the column and the sub-box where the number is at and see if the same number has already added, if it has, return false. Note the indices of the first element in the sub-box is calculated by row / 3 * 3  and col / 3 * 3. For example, row = 4, col = 5, we get the indices x = 3 and y = 3.

The main method is a boolean method. The game is solved by recursion. That is, when we add a valid number, we recursively check the next number we can add to the board until we find a solution. If a number added is not valid, we remove the number and add the next one.

That is, yeah, of course you love it, the backtracking!


public class Solution {
    public void solveSudoku(char[][] board) {
        if (!canBeSolved(board))
            System.out.println("Cannot be solved!");
    }
    private boolean canBeSolved (char[][] board) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.')
                    continue;
                for (int k = 1; k <= 9; k++) {
                    board[i][j] = (char) (k + '0');
                    if (isValid(board, i, j) && canBeSolved(board))
                        return true;
                    //return to '.' for next recursion
                    board[i][j] = '.';
                }
                
                return false;
            }
        }
        //go through the whole board
        return true;
    }
    private boolean isValid(char[][] board, int row, int col) {
        HashSet hs = new HashSet ();
        //the column
        for (int j = 0; j < board[0].length; j++) {
            if(hs.contains(board[row][j]))
                return false;
            //only add numbers
            if (board[row][j] != '.')
                hs.add(board[row][j]);
        }
        //the row
        hs.clear();
        for (int i = 0; i < board.length; i++) {
            if (hs.contains(board[i][col]))
                return false;
            if (board[i][col] != '.')
                hs.add(board[i][col]);
        }
        //the sub-box
        hs.clear();
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                int x = row / 3 * 3 + i;
                int y = col / 3 * 3 + j;
                if (hs.contains(board[x][y]))
                    return false;
                if (board[x][y] != '.')
                    hs.add(board[x][y]);
            }
        }
        return true;
    }
}

Jump Game I && II

Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position. 
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

First thought, 1D DP, the current point can be reached as long as any of the previous points has the maximum step greater than the distance from that point to this point, i.e., can[i] = (can[j] & (j + A[j] >= i).


public boolean canJump(int[] A) {
        boolean[] can = new boolean[A.length];
        can[0] = true;
        
        for (int i = 1; i < A.length; i++) {
            for (int j = 0; j < i; j++) {
                if (can[j] && j + A[j] >= i) {
                    can[i] = true;
                    break;
                }
            }
        }
        
        return can[A.length - 1];
    }


Of course, didn't pass the time limit!

Second thought, greedy approach, and with a similar idea. Use a number to track the farthest point it can reached. At point i, the farthest point it can reach is A[i] + i. So keep tracking the farthest point it can reach and return if it is greater than A.length - 1.


public class JumpGame {
    public boolean canJump(int[] A) {
        int farthest = 0;
        for (int i = 0; i <= farthest && i < A.length; i++) {
            farthest = (A[i] + i > farthest) ? (A[i] + i) : farthest;
            if (farthest >= A.length - 1)
                return true;
        }
        return false;
    }
}


Jump Game II


Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position. 
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Still greedy approach. At each position "farthest", find the maximum position, "maxPos" it can reach, jump to that, and get the next maximum position it can reach. When the maximum position reaches the end of the array, break the loop and return number of jumps needed.

Update: 2015 - 01 - 16
An example that may be helpful to understand:
2   1   3   2   1
index = 0, maxPos = 2;
farthest = 2, numSteps = 1;
index = 0, maxPos = 2;
index = 1, maxPos = 2;
index = 2, maxPos = 5;
farthest = 5, numSteps = 2;
break, return 2


public class JumpGame {
    public int jump(int[] A) {
        if (A == null)
            throw new NullPointerException("Null array!");
        if (A.length <= 1)
            return 0;
        int farthest = 0;
        int maxPos = 0;
        int index = 0;
        int numSteps = 0;
        while (index < A.length) {
            if (farthest >= A.length - 1)
                break;
            while (index <= farthest) {
                maxPos = Math.max(maxPos, A[index] + index);
                index++;
            }
            farthest = maxPos;
            numSteps++;
        }
        return numSteps;
    }
}