Sunday, June 28, 2015

Advantages Of BST Over Hash Table

Hash Table supports following operations in Θ(1) time.
1) Search
2) Insert
3) Delete

What are the advantages of Binary Search Tree Over Hash Table?

 The time complexity of above operations in a self-balancing Binary Search Tree (BST) (like Red-Black Tree, AVL Tree, Splay Tree, etc) is O(Logn).
So Hash Table seems to beating BST in all common operations. When should we prefer BST over Hash Tables, what are advantages. Following are some important points in favor of BSTs.
  1. We can get all keys in sorted order by just doing Inorder Traversal of BST. This is not a natural operation in Hash Tables and requires extra efforts.
  2. Doing order statistics, finding closest lower and greater elements, doing range queries are easy to do with BSTs. Like sorting, these operations are not a natural operation with Hash Tables.
  3. BSTs are easy to implement compared to hashing, we can easily implement our own customized BST. To implement Hashing, we generally rely on libraries provided by programming languages.
  4. With BSTs, all operations are guaranteed to work in O(Logn) time. But with Hashing, Θ(1) is average time and some particular operations may be costly, especially when table resizing happens.

Thursday, April 2, 2015

Which one we should use Binary Search Tree or HashTable??

Its a very rare question which one will ask but we should know When to use BST and when hashtable?

To solve this problem, we will discuss the pros and cons of BST over hashTable.
1) BST always gives elements in sorted order by default if we do the inorder traversal of it as compared to hashtable where extra efforts are required to sort the elements.
2) While writing our own custom BST, it is always easy as compared to a hashTable  where writing a customized hashtable is difficult as we have to rely on different third party libraries to achieve the same .
3) BST's will guranteed O(logn) for basic operations including search, delete and insert which cannot be the case with hashtable as although hashtable will give O(1)  time complexity for such operations but sometimes its not guranteed as these operations can be costly if resizing of hashtable happens.


Tuesday, March 31, 2015

How to find the day of the week for a given date? Ever Heard Of Sakamotos Algorithm?

This is a very common question which is usually asked for 2-3 years experience guys to find the day of a week if a given date is given? Lets suppose if i give 3rd March, 2014, the program should output me the day of the week whether that day was Saturday or Wednesday?

This algorithm is solved by using Sakamotos algorithm which is a very famous algo for calculating the day of the week for a given date!
For more info about this algorithm you can find it here:-
http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week

The following code helps us in finding the exact day of the week for any date:-

package com.pack;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DayOfWeek {
private static int dayofweek(int d, int m, int y)
{
   int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
   boolean b=m<3;
   if(b){
    y=y-1;
   }
   return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}
    public static void main(String[] args) {
int day = dayofweek(31, 3, 2015);
     System.out.println(day);
      }
   }

This will return me the exact day of the week for a given date.

Here, we have declared an array t which contains values which are derived from Sakamotos algorithm.
These values are used to compute a formula and we are passing Date, Month and year as inputs to the method dayofweek().




Friday, March 27, 2015

How to write a Custom HashMap in java? ?

This is one of a crucial question which is asked mostly for senior positions.

We all have worked with hashMaps and how internally they behave? But what if someone will ask you to write your own custom hashmap in java?

i.e the actual implementation of get and put method of your own irrespective of the implementation given in rt.jar file of JDK 1.7.

So lets discuss a mechanism to write your own hashmap implementation in java:-

package com.pack;
import com.pack.CustomHashMap;
import com.pack.KeyValuePair;


public class CustomHashMap<K,V>{
KeyValuePair<K,V> mapList[]=new KeyValuePair[100];
public V get(K key){
int index=getHash(key);
KeyValuePair<K,V> list=mapList[index];
return getMatchValue(list,key);
}
public void put(K key,V value){
int index=getHash(key);
storeValue(index,key,value);
}
public void remove(K key){
int index=getHash(key);
KeyValuePair<K,V> list=mapList[index];
if(list==null){
return;
}
if(list.getKey().equals(key)){
if(list.next==null){
mapList[index]=null;
return;
}
}
KeyValuePair<K,V> prev=null;
do{
if(list.key.equals(key)){
if(prev==null){
list=list.getNext();
}else{
prev.next=list.getNext();
}
break;
}
list=list.next;
}while(list!=null);
mapList[index]=list;
}
private V getMatchValue(KeyValuePair<K,V> list,K key){
while(list!=null){
if(list.getKey().equals(key))
return list.getValue();
list=list.getNext();
}
return null;
}
private void storeValue(int index,K key,V value){
KeyValuePair<K,V> list=mapList[index];
if(list==null){
mapList[index]=new KeyValuePair<K,V>(key, value);
}else{
boolean done=false;
while(list.next!=null){
if(list.getKey().equals(key)){
list.setValue(value);
done=true;
break;
}
list=list.getNext();
}
if(!done)
list.next=new KeyValuePair<K,V>(key, value);
}
}
private int getHash(K key){
int hash=key.hashCode();
return hash%100;
}
public static void main(String args[]){
CustomHashMap<Integer, Integer> map=new CustomHashMap<Integer, Integer>();
map.put(1,1);
map.put(2,2);
map.put(201,201);
    System.out.println("get value is: "+map.get(1));
    System.out.println("get value is: "+map.get(2));
    System.out.println("get value is: "+map.get(201));
    map.remove(1);
    System.out.println("After deletion "+map.get(1));
    System.out.println("get value is "+map.get(201));
 }
}

class KeyValuePair<K,V>{
K key;
V value;
KeyValuePair<K,V> next=null;
public KeyValuePair<K, V> getNext(){
return next;
}
public void setNext(KeyValuePair<K,V> next){
this.next=next;
}
public KeyValuePair(K key,V value){
super();
this.key=key;
this.value=value;
}
public K getKey(){
return key;
}
public void setKey(K key){
this.key=key;
}
public V getValue(){
return value;
}
public void setValue(V value){
this.value=value;
}
}


This code has 3 main methods:-
get, put and remove which are the basic methods defined in any hashMap. It helps us in writing our own custom hashMap with proper get and put methods implemented using a linked list.