Monday, February 23, 2015

TRIE data structure

TRIE, another Search Tree!

Trie is an infix of the word reTRIEval, and pronounced as TREE but to distinguish it from the tree some people also pronounce it as TRY. As the name suggests it is an efficient retrieval or searching data structure. 

The root node represents an empty string (""), if you go down one level it represents all single character words. Similarly, at level 10, trie represents words or prefixes of 10 letters/characters. It is a search tree where each vertex or node represents a single word or a prefix (but each node actually stores a single letter or character). 


Let's take a sample dictionary of 6 words.
Dictionary, D = {a, an, out, the, them, their}

You can use Hashing or Binary search tree to implement a dictionary,  but here we will use trie to implement it.

Below are trie representations of the above dictionary, D. Both left as well as right trie represents the same dictionary (two different representations). If you want to understand the trie the right one is more suitable and left one represents trie from the implementation point of view. Leaf nodes (colored in blue) represents the last node of a word so 'e' of the word 'the' will be the leaf node. The leaf node signals end of a word, but it can get extended further (like 'a' and 'an'). So every node which is the last character of the word will be the leaf node. The implementation can be achieved by a boolean flag.

Two TRIE representation of the same dictionary

Possible operations:
addWord(String): adds a single word to the trie
search(String): search if the given word or prefix exists in the trie
countWords(String): number of words that match in trie with the given word
countPrefixes(String): number of words that have given the prefix

Implementation

To make it simple, let's consider only English alphabets (a-z); and also make case insensitive. This means each node can have maximum of 26 children. So it's just a generalization of Binary Search Tree.

Java implementation this post, here. 

Trie implementation provides operations like add a word and find a word. If you understand the fundamentals, implementing other methods is not going to be difficult. 

Analyzing Performance

Cost of looking up a word or prefix in a vocabulary/dictionary implemented using trie depends only on the number of characters in the word/prefix. It doesn't depend on the size of the dictionary. This is an important distinction from the HashMap/HashTable based dictionary implementations.  As shown in the above diagram the cost of finding the word 'the' requires just 3 steps. 

Runtime complexity of lookup = O(length of word)
String comparison is considered as a single operation, so above can be generalized as O(1).

Trie implementation requires more memory than an array or tree. This is because at each level, the node takes space for 26 characters but not all of them will be used. But the space overhead gets compensated with the constant time search performance. 


References:
keep coding !!!

TRIE implementation in Java

I have covered the fundamentals of trie in this post.

/**
 * TRIE implementation in Java 
 * Tries are general search tree where every node
 * can have some pre-defined number of children. Length of children is 26. Max
 * depth of trie is equal to max length of the word in the dictionary
 *
 * Constraints: 1. assume that all words are lowercase (uppercase letters are
 * converted to lowercase) 2. accept only a-z letters—no punctuation, no
 * hyphens, no accents, etc
 * 
 * Main Operations supported: 1. addword(..) : add a word to the dictionary 2.
 * search(..) : check if the given word exists in dictionary
 *
 * @author Siddheshwar
 */
public class Trie {
 private Node root;

 public Trie() {
  root = new Node();
 }

 /**
  * adds a dictionary word to the vocabolary or dictionary
  * 
  * @param word
  */
 public void addWord(String word) {
  if (word == null || !word.matches("[a-zA-Z]+")) { // or matches ("\\w+")
   return;
  }

  Node r = root;
  int index;
  for (char c : word.toLowerCase().toCharArray()) {
   index = this.getIndex(c);

   if (!r.hasChildAt(index)) {
    r = r.addChild(c);
   } else {
    r = r.getChildAt(index);
   }
  }
  r.setAsLeaf();
 }

 /**
  * Get index where the character will get mapped in the array 'a'/'A' will
  * be mapped to 0th, 'z'/'Z' will get mapped to 25th index
  * 
  * @param ch
  * @return index
  */
 private int getIndex(char ch) {
  // return (int)(ch - 'a');
  return String.valueOf(ch).codePointAt(0)
    - String.valueOf('a').codePointAt(0);
 }

 /**
  * Is word present in the trie
  * 
  * @param word
  * @return
  */
 public boolean contains(String word) {
  if (word == null)
   return true;
  Node r = root;
  for (char c : word.toCharArray()) {
   r = r.getChildAt(this.getIndex(c));
   if (r == null) {
    return false;
   }
  }
  return true;
 }

 /**
  * Returns the node (or null if word is not found)
  * 
  * @param word
  * @return Node
  */
 public Node getNodeEndingWithWord(String word) {
  if (word == null)
   return null;
  Node r = root;
  for (char c : word.toCharArray()) {
   r = r.getChildAt(this.getIndex(c));
   if (r == null) {
    return null;
   }
  }
  return r;
 }
}

import java.util.Arrays;
import java.util.List;

/**
 * Vertex or Node of a TRIE tree. Supports only alphabets a-z (ignores case) 'a'
 * occupies 0th position and 'z', 25th in Node array(i.e. children)
 */
public class Node {
 private Node[] childen;
 private boolean leaf;
 private char value;
 static final char NULL_CHAR = '\0';

 public Node() {
  childen = new Node[26];
  leaf = false;
  value = NULL_CHAR;
 }

 public Node(char c) {
  childen = new Node[26];
  leaf = false;
  value = c;
 }

 public List<Node> getChilden() {
  return Arrays.asList(childen);
 }

 public boolean hasChildAt(int index) {
  return this.childen[index] == null ? false : true;
 }

 public boolean isLeaf() {
  return leaf;
 }

 public char getValue() {
  return value;
 }

 public Node getChildAt(int index) {
  return this.childen[index];
 }

 public void setAsLeaf() {
  this.leaf = true;
 }

 public boolean isCharValid() {
  return this.value != NULL_CHAR ? true : false;
 }

 /**
  * add a child node to the current node
  * 
  * @param ch
  * @return Node
  */
 public Node addChild(char ch) {
  Node childNode = new Node(ch);
  // int index = (int)(ch - 'a'); prefer below approach
  int index = String.valueOf(ch).codePointAt(0)
    - String.valueOf('a').codePointAt(0);
  this.childen[index] = childNode;
  return childNode;
 }

 /**
  * Get count of valid children; upper limit is 26.
  * 
  * @return count
  */
 public int getChildrenCount() {
  int count = 0;
  for (int i = 0; i < 26; i++) {
   if (this.hasChildAt(i)) {
    count++;
   }
  }
  return count;
 }

 /**
  * Returns comma separated list of children for the node
  * 
  * @return
  */
 public String getChildren() {
  StringBuilder output = new StringBuilder();
  for (int i = 0; i < 26; i++) {
   if (this.hasChildAt(i)) {
    output.append((char) (i + 65)).append(",");
   }
  }
  return output.substring(0, output.length() - 1);
 }
}

Friday, February 20, 2015

Convert character to ASCII value in Java

This post, I will be discussing one of the incredibly popular wrong practice of converting characters into their ASCII value in Java. Can you spot any problem with below?


public class CharToAscii {
 public static void main(String[] args) {
         char aAsChar = 'A';
         System.out.println((int)aAsChar); //prints ASCII value
 }
}
The output on console:
65   

The program runs properly and prints the output as expected. So what's the issue? Above program will not mind as long as you can guarantee that input character is an english alphabet or some well known special character.

The issue is with the message it conveys, it conveys that each character is mapped to a unique integer representation (which is ASCII number for English letters and some common characters like @, - etc). It gives impression that a number can be typecast to character and vice-versa. There is no one-to-one mapping between the two; the above code works as expected but it's WRONG. Char in Java takes 2 bytes (or 16 bits), so it maps 65535 characters (i.e. math.pow(2,16)-1), whereas ASCII is restricted to 128. There is huge list of characters which don't have ASCII representation at all. So definitely above approach is misleading. 

So what should be the proper way to convert character 'A' to its ASCII value. The proper way would be to use Unicode code point which is numerically equivalent to ASCII value. Unicode is the superset of ASCII.  English alphabet 'A' in Unicode is U+0041 or 65 in decimal. So below approach should be preferred to convert characters into ASCII value or their encoded integer value.

      int ascii = String.valueOf('A').codePointAt(0);
      //return 65

If you interested in knowing the evolution of character encoding systems and knowing it in more details, I would strongly recommend this article, from Joelonsoftware.

--
keep coding !!!

Tuesday, January 13, 2015

Bit level tricks: XOR

Here goes exclusive post for Exclusive-OR / XOR !

XOR is a binary operator which acts on two number like A XOR B, denoted as A ^B.  A ^ B basically tells how different A is from B (or vice-versa). If a bit of A is different from the same bit of B, the resulting bit is 0.

Properties

1.   XOR with itself results 0

XOR-ing a number with itself returns 0. This also goes with the definition that XOR tells how different two numbers are. X ^ X = 0

     00000100   (4 in binary)                     
^   00000100   (4 in binary)
     ------------
     00000000

 

2.   XOR with 0 results number

 XOR-ing with zero gives back the same number.  X ^ 0 = X

     00000100   (4 in binary)                     
^   00000000   (0 in binary)
     ------------
     00000100

 

3.   XOR is associative and cumulative

 XOR is associative as well cumulative.

Associativity:  (X^Y)^Z = X^(Y^Z)

Cumulative:  X^Y = Y^X 

 

Bit Hacks

Let's see some XOR hacks.

#1: Swapping without temp variable

 X = X ^ Y
 Y = X ^ Y
 X = X ^ Y

Let's prove it by taking an example
X = A, Y = B

X = X ^ Y = A^ B
Y = X ^ Y = (A^B)^B = A^(B^B)  
    = A^0 //by property 1
    = A // by property 2
X = X ^ Y = (A^B)^A
    = B^(A^A)
    = B

#2: Check if two numbers have same sign

If two numbers have same sign then the MSB will be same (i.e. either both will be 0 or 1). This means that XOR of that bit will result in zero. 

 X ^ Y --> MSB of both numbers will be 0 if both numbers have same sign.

     00100100   (X)
^   01100011    (Y)
     ------------
     01000111     (>=0)

Above approach can be generalized as 
X ^ Y >= 0 

#3: Toggle between two values of a variable

Change value of a variable between two allowed values. So if the value is A change it to B and vice-versa. 

if X = A
change value of X to B 

XOR properties discussed above helps in achieving this. 

X = A ^ B ^ X

X = A ^ B ^ X
    = A ^ B ^ A   // X = A
    = (A^A)^B
    = B

 ---

keep coding !!!

Bit level tricks: setting and unsetting right most 1 bit

This post is in continuation with the earlier post, where I have discussed some of the bit manipulation techniques. In previous post, I discussed about how to set, unset and toggle a bit at fixed position like 3rd from right/LSB, 1st from left/MSB etc. Setting and unsetting a bit at fixed position is relatively easier to achieve by using left and right shift operators.
 
This post will discuss about manipulating a bit at relative positions, like right most 1 bit, left most 0th bit etc. Here also, I will explain all tricks using 8 bit number.

 

Bit Hacks

#1: Unset the rightmost 1 bit

So objective is to turn off the right most 1 bit in a number.  If input number is 10100100 then it needs to get converted into a number with b2 (b0 is LSB; highlighted bit is b2) getting turn off.

                           X    = 00100100 
                          X-1  = 00100011   
   Expected response = 00100000   ??

As shown above, subtracting 1 from number unsets the right most 1 but it also sets the zeros right to 1. Please note that other bits left of targeted 1 remain unchanged. Can X and X-1 be combined to get the expected response. If you notice closely the last 2 bits, ANDing looks to do the job. 

     00100100   (36 in binary)
&  00100011    (36 -1 )
     ------------
     00100000 

     10000000 (-128 in binary)
&  01111111  (-128 -1 in binary = 127 )
     ------------
     00000000
 
     00000000 (0 in binary; there is no right most bit)
&  11111111  (0 -1 in binary = -1)
     ------------
     00000000  (no change)


General formula for unsetting the right most 1 bit of a number, X
X = X  & (X-1)

Also, be careful of the impact of changing AND to OR in above formula.

#2: Unset all except rightmost 1 bit

So we need to unsets (clears off or changes to 0) all bits except the right most 1 bit. Trivial approach to solve this would be to RIGHT SHIFT the number until you encounter the set bit (i.e. 1) and counting the number of shifts done. 

    while(X & 1 != 0){
        count++;
        X = X>> 1;
    }

 Above approach more easier to think logically but execution complexity and verbosity is high. Let's think of abstracting it into minimal number of steps. 

     00100100   (X = 36;  in binary)
     11011011    (~X )
                +1
     ------------
     11011100  (-X; in two's complement system -X = ~X+1)

Let's use above -X 

     00100100   (X = 36;  in binary)
&  11011100  (-X)
     ------------
     00000100  (bingo!!!)

     10000000   (X = -128;  in binary)
&  10000000  (-X = -128)
     ------------
     10000000  

And it can be generalized as:
X = X  & (~X)


#3: Set the right most 0-bit

So this hack expects to turn on the right most 0 bit (irrespective of position). This also can be achieved by multiple steps but we want to achieve it compactly. 

     00100100   (X = 36;  in binary)
                +1
     ------------
     00100101  (X+1; )

So adding 1 sets up the right most 0. This can be used to set the right most 0 to 1. 

      00100100   (X = 36;  in binary)
  |   00100101   (X+1 )
     ------------
      00100101  

      01110111   (X )
  |   01111000   (X+1 )
     ------------
      01111111

So OR-ing X with X+1 does the job. 
X = X  | (X+1) 


Related Post : Bit manipulation in Java
 Bit level tricks : setting, unsetting and toggling a bit

----
keep coding !