Sunday, September 27, 2015

Find values at kth row are 0 and kth column in a 2D mattrix are 1

This question comes from geekforgeek: http://www.geeksforgeeks.org/find-k-such-that-all-elements-in-kth-row-are-0-and-kth-column-are-1-in-a-boolean-matrix/

Given a square boolean matrix mat[n][n], find k such that all elements in k’th row are 0 and all elements in k’th column are 1. The value of mat[k][k] can be anything (either 0 or 1).  If no such k exists, return -1. Do it in O(n) time.

Note there is only one such k can satisfy the rules.

Simple way is to do that is to find a kth row that all values are 0s except the kth element. Then check the kth column if all values are 1s except the kth element. This requires us to check all of the element. Time complexity: O(n*n)

Another way to travel from top-left corner, we start with 0th row:
go right if the element is 0, if we reach the end of row, then that means: 1) this rth row is potential candidate; 2) the columns/rows from r+1 to n-1 are not candidate; And we check kth row/col values.
go down if the element is 1, for the current row is no longer qualifies.

Since we either go right or go down, then time complexity is O(n)

     public static int findKthRow(int[][] mat){
        int n = mat.length;
        int row = 0;
        while(row<n-1){
            int col = row + 1;
            //move from left to right at current row
            while(col<n && mat[row][col] == 0){
                col++;
            }
           
            /*
             * if we reach the last column of current row, then
             *    this row is candidate and
             *    rest of rows are not candidates
             * otherwise
             *     we go down one row below   
             */       
            if(col == n){
                //check if this row is qualified
                return checkKthRowCol(mat, row)?row:-1;
            }else{
                row++;
            }
        }
       
        return checkKthRowCol(mat, row)?row:-1;
    }
   
    private static boolean checkKthRowCol(int[][] mat, int k){
        int n = mat.length;
        for(int i = 0; i<n; i++){
            if(i==k)
                continue;
            else{
                if(mat[k][i]==1 || mat[i][k]==0)
                    return false;
            }
        }
        return true;
    }


Friday, September 18, 2015

a simple regular expression implementation

Implement a simple regular expression based string match. 

. - any character
* - match 0 or more times of previous character

/**
     *
     * @param target
     * @param regex
     * @return
     */
    public static boolean isMatch(String target, String regex){
        assert !target.isEmpty() && !regex.isEmpty();
        int p1 = 0;
        int p2 = 0;
        int len1 = target.length();
        int len2 = regex.length();
        char pre = '\0', c1, c2 = '\0';
       
        while(p1<len1 && p2<len2){
            c1 = target.charAt(p1);
            c2 = regex.charAt(p2);
           
            if(c2 == '.'){
                p1++;p2++;
                pre = '.';
            }else if(c2 == '*'){               
                if(pre == '\0'){
                    return false;
                }
                else if(pre == '.' || pre == c1){
                    p1++;
                }else{
                    p2++;
                    pre = '\0';
                }
            }else{
                if(c1 == c2){
                    pre = c1;
                    p1++; p2++;
                }else{
                    if(p2+1<len2 && regex.charAt(p2+1) == '*'){
                        p2++;p2++;
                    }else
                        return false;
                }
                   
            }
        }
       
        if(p1 == len1)
            return true;
        else
            return false;
    }

Thursday, September 17, 2015

Least recently used cache (LRU) implementation

One of the leetcode questions is to implement a least recently used cache. Basically a cache has to combine two kinds of data structures: a hash table so we can get/set item and a linked list so we can maintain the order of entries.

In JDK there is LinkedHashMap, which does the above, its implement a special Map.Entry class which only has key and value, but also maintain pointer to the next and previous Map.Entry.

Here are couple of my implementations:

1. Use LinkedHapMap directly:

public class SimpleLRUCache {
    private int capacity;
    LinkedHashMap<Object, Object> map;
   
    public SimpleLRUCache(final int capacity){
        this.capacity = capacity;
      
        map = new LinkedHashMap<Object, Object>(12, 0.76f, true){
            protected boolean removeEldestEntry(Map.Entry<Object,Object> eldest){
                return this.size() == capacity;              
            }
        };
      
    }
}

2. Use HashMap and LinkedList:

import java.util.HashMap;
import java.util.Map;

public class LRUCache {
    public static class Node{
Object key;
Object value;
Node pre;
Node next;
}

Map<Object, Node> map;

int capacity;

//head points to the oldest entry
Node head;
Node tail;

public LRUCache (int c){
this.capacity = c;
this.map = new HashMap<Object, Node>();
}

public Object get(Object key){
if(map.containsKey(key)){
Node n = map.get(key);
remove(n);
addLast(n);
return n.value;
}else
return null;

}

public void set(Object key, Object value){
if(map.containsKey(key)){
Node n = map.get(key);
remove(n);
addLast(n);
return;
}

if(map.size() == this.capacity){
map.remove(head.key);
remove(head);
}

Node n = new Node();
n.key = key;
n.value = value;

addLast(n);

map.put(key, n);

}

public void addLast(Node n){
if(head==null){
head = n;
tail = n;
}else{
tail.next = n;
n.pre = tail;
tail = n;
}
}


public void remove(Node n){
if(n.pre == null){
head = n.next;

}else{
n.pre.next = n.next;
}

if(n.next == null){
tail = n.pre;
}else
n.next.pre = n.pre;

//set the pointer so n can be gc'd
n.pre = n.next = null;
}
}

3. Synchronized LRU

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/*
 * a thread-safe LRUCache implementation using lock
 *
 * note only most important methods are implemented
 */
public class SynchronizedLRUCache<K, V> implements Map<K,V> {

    private final Map<K, V> cache;
   
    public SynchronizedLRUCache(final int maxSize, final int initSize, final float lf){  
        this.cache = new LinkedHashMap<K ,V>(initSize, lf){
            private static final long serialVersionUID = -1218440011343946609L;

            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> oldest){
                return size() > maxSize;
            }
        };
    }
   
    public SynchronizedLRUCache(final int maxSize, final int initSize){  
        this(maxSize, initSize, 0.75f);
    }
   
    public SynchronizedLRUCache(final int maxSize){  
        this(maxSize, 1<<4, 0.75f);
    }
   

    public int size() {
        synchronized(cache){
            return cache.size();
        }      
    }

   
    public boolean isEmpty() {
        synchronized(cache){
            return cache.isEmpty();
        }
    }

   
    public boolean containsKey(Object key) {
        synchronized(cache){
            return cache.containsKey(key);
        }
    }

   
    public V put(K key, V value) {
        synchronized(cache){
            return cache.put(key, value);
        }
    }
   
   
    public V get(Object key) {
        synchronized(cache){
            return cache.get(key);
        }
    }
   
   
    public void putAll(Map<? extends K, ? extends V> m) {
        synchronized(cache){
            cache.putAll(m);
        }
      
    }
   
   
    public boolean containsValue(Object value) {
        // TODO Auto-generated method stub
        return false;
    }
   

    public V remove(Object key) {
        // TODO Auto-generated method stub
        return null;
    }  

   
    public void clear() {
        // TODO Auto-generated method stub
      
    }

   
    public Set<K> keySet() {
        // TODO Auto-generated method stub
        return null;
    }

   
    public Collection<V> values() {
        // TODO Auto-generated method stub
        return null;
    }

   
    public Set<java.util.Map.Entry<K, V>> entrySet() {
        // TODO Auto-generated method stub
        return null;
    }

   

}

Saturday, August 22, 2015

String tokenizer

Given a function which will tell if a string is word or not, and given a string, break it into multiple words. For example: "usaway" can be broken into "us away" or "usa way".

If we think each index of characters in the string is a node in a direct graph, then there is edge from node i to j if substring from index i to j is a word. Start from node at index 0, if we can find a path to node at index of last character, then we find a way to tokenize the string.  To do this we can use depth first search. 

The following is the code. Note if there are multiple ways to break a string into words, then the method will only return one way. 

public static String tokenize(String s){
String[] result = new String[1];
result[0] = "";
dfs(s, 0, result);
return result[0];
}

private static boolean dfs(String s, int index, String[] result){
if(index == s.length())
return true;
for(int i=index+1; i<=s.length(); i++){
String substring = s.substring(index, i);
if(isWord(substring) && dfs(s, i, result)){
result[0] =  substring + " " + result[0];
return true;
}
}
return false;
}


The second tokenize method will return a list. Each item in the return list is a list of indices which form a path from index at 0 to the last index of the string. 

public List<List<Integer>> tokenize2(String input){
/*
* map character index position to the next character index position if they are part of the solution
*/
Map<Integer, List<Integer>> store = new TreeMap<Integer, List<Integer>>();
dfs(input, store, 0);
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(0);
result.add(list);
boolean flag = true;
while(flag){
flag = false;
List<List<Integer>> copy = new ArrayList<List<Integer>>();
for(List<Integer> li : result){
int k = li.get(li.size()-1);
if(store.containsKey(k)){
flag = true;
for(int n : store.get(k)){
List<Integer> temp = new ArrayList<Integer>(li);
temp.add(n);
copy.add(temp);
}
}else
copy.add(li);
}
result = copy;
}
return result;
}
private Integer dfs(String s, Map<Integer, List<Integer>> store, int from){
int len = s.length();
if(from == len-1)//we find the leaf node
return from;
for(int i=from+1; i<len-1; i++){
if(isWord(s, from, i)){
Integer ret = dfs(s, store, i);
if(!store.containsKey(from)){
List<Integer> list = new ArrayList<Integer>();
store.put(from, list);
}
//the edge from-ret form the path which is the solution
store.get(from).add(ret);
return ret==null?null:from;
}
}
return null;
}

N-queens puzzle

The n-queens puzzle is a classic dynamic programming puzzle. The problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],
 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]


public static void findAllValidQueenPositions(int k){
/*
* an array indicate the queens' column index position on each row
* e.g. if k = 2, array of 0, 1 means queens are placed at 0,0 and 1,1 cells
*/
int[] pos = new int[k];
for(int r = 0; r<pos.length; r++)
pos[r] = -1;
move(pos, 0);
}

private static void move(int[] pos, int row){
int length = pos.length;
if(row == length){//we finish the whole chess board
System.out.println(Arrays.toString(pos));
return;
}

/*
* go through each col on current row
*/
for(int col = 0; col<length; col++){
if(isValidMove(pos, col, row)){
int[] copy = Arrays.copyOf(pos, length);
copy[row] = col;
move(copy, row+1);
}
}

}


private static boolean isValidMove(int[] pos, int col, int row) {
if(row==0)
return true;
else{
for(int r = 0; r<row; r++){
if(Math.abs(pos[r] - col) == Math.abs(r - row) || pos[r] == col)
return false;
}
}

return true;

}

Sunday, August 16, 2015

Longest Valid Parentheses

There is the longest valid parentheses problem definition.

We are given a string containing just parentheses of character ')' and '(' only, find the length of the longest valid (well-formed) parentheses substring. For example, for "(()", the longest valid parentheses substring is "()", output is 2. Anther example is ")()())", the longest valid parentheses substring is "()()", which has length of 4.

Approach I: dynamic programming

As usual many of the string related problems can be solved by dynamic problem. Given a substring from index at i to j, how can we find out the longest valid parentheses substring, which is not easy to construct the dynamic function. But we can convert this problem to another problem, that is, given substring S from index i to j, find out if all of the parentheses in the substring S form valid pair.

Here is how we construct isValid dynamic function based on index i and j, which is to break the substring(i,j) to two part: i,k and k+1, j. in which k = i+1, i+3, i+5, ..., j-2.

if(isValid(i,k) && isValid(k+1,j)) then isValid(i,j) = true.

Here is the java code:

public static int longestValidParentheses(String str){
int len = str.length();
boolean[][] isValid = new boolean[len][len];
int maxLen = 0;
for(int i =0; i< len-1; i++){
if(str.charAt(i)=='(' && str.charAt(i+1) == ')'){
isValid[i][i+1] = true;
maxLen = 2;
}
}
for(int step=3; step<len; step=step+2){ for(int i=0; i+step<len; i++){ int j = i+step;
if(isValid[i+1][j-1]&&isValid(str,i,j)) isValid[i][j] = true; for(int k=i+1; k<=j-2; k=k+2){ if(isValid[i][k] && isValid[k+1][j]) isValid[i][j] = true; if(isValid[i][j]){ maxLen = Math.max(maxLen, j - i + 1); break; } } } }
return maxLen;
}
private static boolean isValid(String str, int i, int j){
return str.charAt(i) == '(' && str.charAt(j) == ')';
}

Approach II: using stack

Stack is great data structure, the difference between stack and queue is that you update and query from the same place: the back, while in queue you have two places to update: insert at back, remove at front. That is the reason we can use stack is constructed data structure like max/min stack and max/min queue, in this case, the queue is built on top of stack, as well.

static class Node {
        int pos;
        char c;
        Node(int p, char c){
            this.pos = p;
            this.c = c;
        }
    }
    public static int maxValidParenthesis(String input){
        int max = 0;
        Stack<Node> s = new Stack<Node>();
        for(int i=0, j= input.length(); i<j; i++){
            char c = input.charAt(i);
            if(s.isEmpty() || c == '(' || s.peek().c == ')')
                s.push(new Node(i, c));
            else{
                s.pop();
                max = Math.max(i - (s.isEmpty()?-1:s.peek().pos), max);
            }
        }
        return max;
    }
 

Trie implementation and related string search problems

Trie is special purpose tree to store set of strings to solve a specific set of problems. In stead of storing the characters in the nodes, it is stored on the edges. The string can be constructed by concatenating all the characters found in the path.

For example it can store a dictionary contains a set of words, then it can answer the questions such as:

1. Does word S exist in the dictionary?
2. Given a string S, find all of the words which has the prefix equals to S. Think about design a data structure to support a auto-complete search box.

The followings are Java implementation of Trie to store the set of words from dictionary and support word search in the dictionary.


/*
* trie node definition
* it assumes the character are ascii chacaters
* each word in the dictionary is stored at leaf level
*/


public class TrieNode {
        private final static ALPHABET_SIZE = 256;
        TrieNode[] children = new SuffixNode[ALPHABET_SIZE];
boolean isLeaf;
String word;
}

/*
* suffix tree class
* it defines couple operations to support string search in a dictionary 
* 
*/
public class Trie {
TrieNode root;
public Trie(){
root = new TrieNode();
}
/*
* insert a string into suffix tree
*/
public void insert(String s){
insertHelper(s, 0, root);
}
private void insertHelper(String s, int index, TrieNode node){
if(index == s.length()){
node.isLeaf = true;
node.word = s;
return;
}
TrieNode trieNode = node.children[s.charAt(index)];
if(trieNode==null)
trieNode = new TrieNode();
insertHelper(s, index+1, trieNode);
}
/*
* check if string is prefix of one of the words contained in the tree
*/
public boolean containsPrefix(String s){
return containsPrefix(s, 0, root);
}
private boolean containsPrefix(String s, int index, TrieNode node){
if(index == s.length())
return true;
TrieNode trieNode = node.children[s.charAt(index)];
if(trieNode != null)
return containsPrefix(s, index+1, trieNode);
else
return false;
}

/*
* check if the string is a word existing in the suffix tree
*/
public boolean isWord(String s){
return isWordHelper(s, 0, root);
}
private boolean isWordHelper(String s, int index, TrieNode node){
if(index == s.length())
return node.isLeaf; //the current node must be leaf node
TrieNode trieNode = node.children[s.charAt(index)];
if(trieNode != null)
return isWordHelper(s, index+1, trieNode);
else
return false;
}
/*
* find if the word is prefix of any words contained in the trie tree
* and return the last node which contains the word
*/
public TrieNode searchFor(String s){
return searchFor(s, 0, root);
}
private TrieNode searchFor(String s, int index, TrieNode node){
if(index == s.length())
return node;
TrieNode trieNode = node.children[s.charAt(index)];
if(trieNode != null)
return searchFor(s, index+1, trieNode);
return null;
}
}