Wednesday, March 23, 2011

WAP to Sort 2D Array/Matrix

// --Sorting Program--
// -------------------
// Example Program to sort
// 2D array using linear
// representation of the array
#include

#define MAX 3

int main(void)
{
int arr[MAX][MAX]={{8,9,7},{3,2,1},{5,4,6}} ;
int i,j,temp;
int *arr_ptr;



// we have taken a pointer
// to the 2D array to
// represent it linearly

// C-style type cast
// is necessary here
arr_ptr=(int*)arr;

// sorting is done here.
// selection sort method of
// sorting is employed here
// you can use whichever
// method you like

// here MAX*MAX is used
// because the no. of elements
// in the linear representation
// of the 2D array has that
// many elements
for(i=0;i<((MAX*MAX)-1);i++)
for(j=i+1;j<(MAX*MAX);j++)
if(*(arr_ptr+i)>*(arr_ptr+j))
{
temp=*(arr_ptr+i);
*(arr_ptr+i)=*(arr_ptr+j);
*(arr_ptr+j)=temp;
}
// sorting is done till here



for(i=0;i {
for(j=0;j printf(" %d ",arr[i][j]);
printf(" \n");
}
}

WAP to Calculate The Factorial of BIG NUmber(Obvious Integer,Long) That Can't Fit In Memory at a time

In order to learn this big number arithmetic lets take an example of calculating factorial of big numbers

24 = 4!
120 = 5! 8-bit unsigned int
720 = 6!
5040 = 7!
40320 = 8! 16-bit unsigned int(not exactly)
362880 = 9!
39916800 = 11!

479001600 = 12! 32-bit unsigned (this is the maximum number that can fit in the integer of size of 32 bit) =2147483647

87178291200 = 14!
6402373705728000 = 18!
121645100408832000 = 19!
2432902008176640000 = 20! 64-bit unsigned
51090942171709440000 = 21!
8222838654177922817725562880000000 = 31!
263130836933693530167218012160000000 = 32
295232799039604140847618609643520000000 = 34! 128-bit unsigned

Now if we have to calculate something like 100! then it not possible to do with inbuilt int(4 byte) long long int (8 byte)Now, the maximum number that we can store in an unsigned 32 bit integer is 2 ^ 32 - 1 and in an unsigned 64 bit integer is 2 ^ 64 - 1. Something like 100!('!' is the notation for factorial) has over 150 decimal digits. The data types mentioned earlier can store numbers having at most 9 and 19 decimal digits respectively. So, we need to find a way to store the 150+ digits that we will get as the answer. The simplest data structure that we can use is an integer array of size of about 200 to be on the safe side.
#include
#include
void factorial(int n)
{
int digit[160];
int m, carry,d,i,last;
for(i=0;i<160;i++) digit[i]=0; digit[0]=1; last=0; for(m=1;m<=n;m++) { carry=0; for(i=0;i<=last;i++) {d=digit[i]*m+carry; digit[i]=d%10; carry=d/10; } while(carry>0)
{
last=last + 1;
digit[last]=carry%10;
carry=carry/10;
}
}

for(i=last;i>=0;i--)
printf("%d",digit[i]);
printf("\n");

}
int main()
{
factorial(100);
int n=pow(2,32)-1;
printf(" %d ", n);

}

Factorial of 100 =93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Run Here https://ideone.com/fgaSP

C++ Code Recursive Version

#include
#include

int max = 5000;

void display(int arr[]){
int ctr = 0;
for (int i=0; i<=0; --i){
arr[i] = (arr[i] * n) + carry;
carry = arr[i]/10;
arr[i] %= 10;
}
factorial(arr,n-1);
}

int main(){
int *arr = new int[max];
std::memset(arr,0,max*sizeof(int));
arr[max-1] = 1;
int num=100;
std::cout<<"Enter the number: ";

std::cout<<"factorial of "<<<"is :\n";
factorial(arr,num);
display(arr);
delete[] arr;
return 0;
}

Run Here https://ideone.com/R7Q0F

I suggest you people to go through this article http://www.codeproject.com/KB/recipes/factorial.aspx 

5 Fast Way to Computer Big Factorial https://www.luschny.de/math/factorial/FastFactorialFunctions.htm

Tuesday, March 22, 2011

we have an array of 2n elements like "a1 a2...an b1 b2...bn". WAP to rearrange the array as "a1 b1 a2 b2...an bn" time complexity is O(n) no extra RAM

#include
#define SWAP(a,b) a^=b^=a^=b

int string[100];
int m;

void Replace(int n,int start){
int i,j;
for(i=start,j=0;j {
SWAP(string[i],string[n+i]);
}
n=n-1;
if(n>0)
Replace(n,start+1);
}

main()
{
int i;
printf("Enter no of elements (max 100): ");
scanf("%d",&m);
if(m%2){
printf("odd nos\n");
}
else{
printf("Enter numbers: ");
for(i=0;i scanf("%d",&string[i]);
for(i=0;i printf("%d\t",string[i]);
printf("\n");

Replace(m/2-1,1);
for(i=0;i printf("%d\t",string[i]);
printf("\n");
}
}

.WAP for Thread pool Scenario .Make a class diagram for thread-pool. Also discuss how to allocate threads for different calls Read WIKIpedia for this

import java.util.LinkedList;

class ThreadTask extends Thread {
private ThreadPool pool;

public ThreadTask(ThreadPool thePool) {
pool = thePool;
}

public void run() {
while (true) {
// blocks until job
Runnable job = pool.getNext();
try {
job.run();
} catch (Exception e) {
// Ignore exceptions thrown from jobs
System.err.println("Job exception: " + e);
}
}
}
}

public class ThreadPool {
private LinkedList tasks = new LinkedList();

public ThreadPool(int size) {
for (int i = 0; i < size; i++) {
Thread thread = new ThreadTask(this);
thread.start();
}
}

public void run(Runnable task) {
synchronized (tasks) {
tasks.addLast(task);
tasks.notify();
}
}

public Runnable getNext() {
Runnable returnVal = null;
synchronized (tasks) {
while (tasks.isEmpty()) {
try {
tasks.wait();
} catch (InterruptedException ex) {
System.err.println("Interrupted");
}
}
returnVal = (Runnable) tasks.removeFirst();
}
return returnVal;
}

public static void main(String args[]) {
final String message[] = { "Java", "Source", "and", "Support" };
ThreadPool pool = new ThreadPool(message.length / 2);
for (int i = 0, n = message.length; i < n; i++) {
final int innerI = i;
Runnable runner = new Runnable() {
public void run() {
for (int j = 0; j < 25; j++) {
System.out.println("j: " + j + ": " + message[innerI]);
}
}
};
pool.run(runner);
}
}
}

WAP to Remove Remove vowels from a string in place.

This is asked in many preliminary tech interviews.

Question:

Write a program to remove all vowels from a string in place.

The key to solving this is that since we are removing characters from the string, the resultant string length will be less than or equal to the original string's length. So, the idea here would be to accumulate all the vowels and push them towards the end of the string and at the end, if we keep a running count of the number of vowels in the string and we already know the length of the original string, we can place our C string terminating null char at the appropriate position to give us a new string, sans the vowels. The algorithm in plain words is as follows:

We run across the word from left to right. The first time we encounter a vowel, we store that position (the index if you look at the string as a char array) in the string in a variable.

Each time we encounter a consonant we swap its position with the position of the vowel and just increment the index that points to the vowel. If another vowel is encountered, we just increment a count that stores the vowels encountered thus far.

This keeps all the vowels contiguous in the string and as each swap with a consonant happens, this contiguous block of vowels gets pushed further down the string until we reach the end of string. We can then just put a null char at (n - vowel_count) where n is the length of the original string.

For the example word PEEPERS:

1. vowel_count=0, vowel_start_index=-1
2. P is encountered first, do nothing because we haven't come across a vowel yet.
3. E is encountered next, so vowel_count=1 and vowel_start_index=1 (assuming 0 based array indices. So the first E is at position number 1 in the string PEEPERS
4. E is encountered again, so vowel_count=2
5. P is encountered next, its a consonant so swap position of P with position held in vowel_start_index. Then increment vowel_start_index. So the string looks like PPEEERS and vowel_start_index=2
6. E is encountered next (this is the third E in PEEPERS). vowel_count becomes 3.
7. R is encountered. Its a consonant so swap it with character held at vowel_start_index (which is 2). So the string becomes PPREEES and increment vowel_start_index to 3
8. Finally we come across S. Do the same as above and whola!! You have the string PPRSEEE with vowel_count = 3.
9. Now just place a null at (n - vowel_count) = 7-3 = 4 and you have the string PPRS which is the desired output.

The code is as follows. It uses C++ string but can easily be emulated for C style strings.
We scan through the string only once and no extra storage space is used. So time complexity is O(n) and space complexity is O(1).

#include

bool isVowel(char a)
{
if(a == 'a' || a == 'A' ||
a == 'e' || a == 'E' ||
a == 'i' || a == 'I' ||
a == 'o' || a == 'O' ||
a == 'u' || a == 'U')
return true;
else
return false;
}

void removeLetters(std::string& s)
{
int len = s.length();
int vcount = 0;
int vstart = -1;

for(int i=0; i {
if(isVowel(s[i]))
{
if(vstart == -1)
vstart = i;
vcount++;
}

if(!isVowel(s[i]) && vstart != -1)
{
/* Encountered letter is a consonant. So do swap.
The below method for swap does not need a tmp variable */
s[i] = s[i] + s[vstart];
s[vstart] = s[i] - s[vstart];
s[i] = s[i] - s[vstart];
vstart++;
}
}
s = s.substr(0, len-vcount);
}

int main(int argc, char** argv)
{
std::string s = "the rain in spain is mainly from the plains.";
removeLetters(s);
std::cout << s << std::endl;
return 0;
}

WAP to Find Maximum difference between two elements in Array of +ive & -Ive Elements

Given an array arr[] of integers, find out the difference between any two elements such that larger element appears after the smaller number in arr[].

Examples: If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9)

Method 1 (Simple)
Use two loops. In the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far.
?
#include

/* The function assumes that there are at least two
elements in array.
The function returns a negative value if the array is
sorted in decreasing order.
Returns 0 if elements are equal */
int maxDiff(int arr[], int arr_size)
{
int max_diff = arr[1] - arr[0];
int i, j;
for(i = 0; i < arr_size; i++)
{
for(j = i+1; j < arr_size; j++)
{
if(arr[j] - arr[i] > max_diff)
max_diff = arr[j] - arr[i];
}
}
return max_diff;
}

/* Driver program to test above function */
int main()
{
int arr[] = {1, 2, 90, 10, 110};
printf("Maximum difference is %d", maxDiff(arr, 5));
getchar();
return 0;
}

Time Complexity: O(n^2)

Method 2 (Tricky and Efficient)
In this method, instead of taking difference of the picked element with every other element, we take the difference with the minimum element found so far. So we need to keep track of 2 things:
1) Maximum difference found so far (max_diff).
2) Minimum number visited so far (min_element).
?
#include

/* The function assumes that there are at least two
elements in array.
The function returns a negative value if the array is
sorted in decreasing order.
Returns 0 if elements are equal */

int maxDiff(int arr[], int arr_size)
{
int max_diff = arr[1] - arr[0];
int min_element = arr[0];
int i;
for(i = 1; i < arr_size; i++)
{
if(arr[i] - min_element > max_diff)
max_diff = arr[i] - min_element;
if(arr[i] < min_element)
min_element = arr[i];
}
return max_diff;
}
int main()
{
int arr[] = {1, 2, 6, 80, 100};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Maximum difference is %d", maxDiff(arr, size));
getchar();
return 0;
}

Time Complexity: O(n)
Source & Algo You Can Find Several Places

WAP to Implement All Operation of AVL Tree

Algorithm


1. Input A tree rooted at root.
2. Output Tree after insertion of node.
3. Complexity O(logn)
4.
5. AVL Insertion
6. AVL insert (root)
7. if item 8. AVL insert(left[root])
9. else AVL insert(right[root])
10. if (root = null)
11. Temp[info]=item;
12. Temp =root;
13. if (left[root]=null and right[root]=null) then
14. Root [info]=item;
15. if (item 16. Left [root] =temp;
17. if (item >info [root] ) then
18. Right [root]=temp;
19. AVL rotation (x, p[x] , p[p[x]] );
20.
21. AVL deletion
22. Input A tree rooted at root.
23. Output Tree after deletion of node.
24. Complexity O(logn).
25.
26. AVL delete (item, p)
27. If (item=info[root]) then
28. if (right[root] != null) then
29. q=successor(root);
30. info[root]=q;
31. AVL delete(q);
32. else if(left[root] !=null) then
33. q=predecessor(root)
34. info[root]=q;
35. AVL delete(q);
36. else AVL delete(p);
37. else
38. if (item 39. AVL delete(left[p]);
40. else
41. AVL delete(right[p]);
42. AVL rotate(p, pr[p] , sib[p]);

Input A tree rooted at root.
Output Tree after insertion of node.
Complexity O(logn)

AVL Insertion
AVL insert (root)
if item AVL insert(left[root])
else AVL insert(right[root])
if (root = null)
Temp[info]=item;
Temp =root;
if (left[root]=null and right[root]=null) then
Root [info]=item;
if (item Left [root] =temp;
if (item >info [root] ) then
Right [root]=temp;
AVL rotation (x, p[x] , p[p[x]] );

AVL deletion
Input A tree rooted at root.
Output Tree after deletion of node.
Complexity O(logn).

AVL delete (item, p)
If (item=info[root]) then
if (right[root] != null) then
q=successor(root);
info[root]=q;
AVL delete(q);
else if(left[root] !=null) then
q=predecessor(root)
info[root]=q;
AVL delete(q);
else AVL delete(p);
else
if (item AVL delete(left[p]);
else
AVL delete(right[p]);
AVL rotate(p, pr[p] , sib[p]);


Algorithm Description

Notations:
Info [root] : Item stored at root node.
Left[root]: left child of root;
Right[root]: right child of root;
P[x]=parent of node x;



#include
#include
#include


typedef struct node1
{
int data;
int bf;
struct node1 *left;
struct node1 *right;
} node;


void insert_node(node **, int);
void delete_node(node **, int);
int find_height(node *);
void delete_tree(node **);
node *findmax(node *);
void traverse_inorder(node *);


int main()
{
int choice; /* variable to store choice of user */
int element; /* variable to store data of node entered bu user */
node *root = NULL; /* intialising root node */
while (1)
{
printf("\n\t MENU\n");
printf("\t--------\n");
printf(" 1. Insert node\n");
printf(" 2. Delete node\n");
printf(" 3. Height of Tree\n");
printf(" 4. Traverse inorder\n");
printf(" 5. Exit\n\n");
printf("Enter your choice (1-5) ::");
scanf("%d", &choice);
switch (choice)
{
case 1: printf("\n Enter the element to be inserted::");
scanf("%d", &element);
insert_node(&root, element);
break;
case 2: printf("\n Enter the element to be deleted ::");
scanf("%d", &element);
delete_node(&root, element);
break;
case 3: printf("Height of AVL Tree = %d", find_height(root));
break;
case 4: printf("\n\n In-Order Traversal is\n");
traverse_inorder(root);
break;
case 5: delete_tree(&root);
return;
}
}
}

void insert_node(node ** root, int element)
{
node *ptr1;
node *ptr2;
/* checking if there is no elemnt in th tree */
if(NULL == *root)
{
*root = (node *) malloc (sizeof(node)); /* allocating memory */
(*root)->data = element;
(*root)->left = NULL;
(*root)->right = NULL;
(*root)->bf = 0; /* allocating balance factor to root */
}
/* element is less than root than */
else if(element < (*root)->data)
{
insert_node(&((*root)->left), element);
switch((*root)->bf)
{
case 1: ptr1 = (*root)->left;
if(1 == ptr1->bf)
{
/* right rotation */
(*root)->left = ptr1->right;
ptr1->right = *root;
(*root)->bf = 0;
*root = ptr1;
}
else
{
ptr2 = ptr1->right;
ptr1->right = ptr2->left;
ptr2->left = ptr1;
(*root)->left = ptr2->right;
ptr2->right = *root;
(*root)->bf = ptr2->bf == 1 ? -1 : 0;
ptr1->bf = ptr2->bf == -1 ? 1 : 0;
*root = ptr2;
}
break;
case 0: (*root)->bf = 1;
break;
case -1: (*root)->bf = 0;
break;
}
}
else
{
insert_node(&(*root)->right, element);
switch((*root)->bf)
{
case 1: (*root)->bf = 0;
break;
case 0: (*root)->bf = -1;
break;
case -1: ptr1 = (*root)->right;
if(ptr1->bf == -1)
{
/* left rotation */
(*root)->right = ptr1->left;
ptr1->left = *root;
(*root)->bf = 0;
*root = ptr1;
}
else
{
/* double rotation ,right left */
ptr2 = ptr1->left;
ptr1->left = ptr2->right;
ptr2->right = ptr1;
(*root)->right = ptr2->left;
ptr2->left = (*root);
(*root)->bf = ptr2->bf == -1 ? 1 : 0;
ptr1->bf = ptr2->bf == 1 ? -1 : 0;
*root = ptr2;
}
}
}
}

int find_height (node *tree)
{
int height_of_left_subtree;
int height_of_right_subtree;
int height;
if (NULL == tree)
{
height = 0;
}
else
{
height_of_left_subtree = find_height(tree->left);
height_of_right_subtree = find_height(tree->right);
if(height_of_left_subtree > height_of_right_subtree)
height = height_of_left_subtree + 1;
else
height = height_of_right_subtree + 1;
}
return height;
}

void delete_node (node **h, int element)
{
node *temp; /* variable to store node which has to be freed */
node *ptr1;
node *ptr2;
if (NULL == *h)
{
printf("Element %d not found in the AVL tree\n", element);
printf("press any key to continue....");
getch();
}
else if(element < (*h)->data)
{
delete_node(&(*h)->left, element);
switch((*h)->bf)
{
case 1: (*h)->bf = 0;
break;
case 0: (*h)->bf = -1;
break;
case -1: ptr1 = (*h)->right;
if(ptr1->bf == -1)
{
/* left rotation */
(*h)->right = ptr1->left;
ptr1->left = *h;
(*h)->bf = 0;
*h = ptr1;
}
else
{
ptr2 = ptr1->left;
ptr1->left = ptr2->right;
ptr2->right = ptr1;
(*h)->right = ptr2->left;
ptr2->left = *h;
(*h)->bf = ptr2->bf == -1 ? 1 : 0;
ptr1->bf = ptr2->bf == 1 ? -1 : 0;
*h = ptr2;
}
}
}
else if (element > (*h)->data)
{
delete_node (&(*h)->right, element);
switch ((*h)->bf)
{
case 1: ptr1 = (*h)->left;
if(ptr1->bf == 1)
{
/* right rotation */
(*h)->left = ptr1->right;
ptr1->right = *h;
(*h)->bf = 0;
*h = ptr1;
}
else
{
/* double rotation , left-right */
ptr2 = ptr1->right;
ptr1->right = ptr2->left;
ptr2->left = ptr1;
(*h)->left = ptr2->right;
(*h)->bf = ptr2->bf == 1 ? -1 : 0;
ptr1->bf = ptr2->bf == -1 ? 1 : 0;
*h = ptr2;
}
break;
case 0: (*h)->bf = 1;
break;
case -1: (*h)->bf = 0;
break;
}
}
/* when element found and it has both the child than find predecessor */
else if( (*h)->left && (*h)->right)
{
temp = findmax((*h)->left); /* find predecessor */
(*h)->data = temp->data; /* replace node with predecessor */
delete_node(&(*h)->left, temp->data); /* delete predecessor */
}
else
{
temp = *h;
if(((*h)->left == NULL) && ((*h)->right == NULL)) /* terminal node */
*h = NULL;
else if ((*h)->right == NULL) /* left child only */
*h = (*h)->left;
else
*h = (*h)->right; /* right child only */
free(temp);
}
}

node * findmax(node *root)
{
if((NULL == root) || (NULL == root->right))
{
return root;
}
else
return findmax(root->right);
}

void traverse_inorder(node *root)
{
if(NULL != root)
{
traverse_inorder(root->left);
printf("%d, ", root->data);
traverse_inorder(root->right);
}
}
void delete_tree(node **root)
{
if (NULL != *root)
{
delete_tree(&((*root)->left));
delete_tree(&((*root)->right));
free(root);
}
}

Source AlgoGuru

WAP to Add and Remove Method In/From Binary Heap Efficiently

import java.io.*;
class heapsort{
int n;
int heap[];
heapsort(int i){
n=i;
heap=new int[i+1];
}
void downheap(int start,int finish)
{
int i=start,l,r,max,temp;
l=2*start;
r=l+1;
if(l<=finish)
{
max=heap[l];
i=l;
if(r<=finish)
if(heap[r]>max)
{
max=heap[r];
i=r;
}
}
if(heap[start] {
temp=heap[start];
heap[start]=heap[i];
heap[i]=temp;
downheap(i,finish);
}
}
void upheap(int start)
{
int temp,par;
if(start>1)
{
par=start/2;
if(heap[par] {
temp=heap[start];
heap[start]=heap[par];
heap[par]=temp;
upheap(par);
}
}
}
void insert(int n,int item)
{
n++;
heap[n]=item;
upheap(n);
}
void heapify(int n)
{
int i,index;
index=n/2;
for(i=index;i>=1;i--)
downheap(i,n);
}

int Delete()
{
int temp;
temp=heap[1];
heap[1]=heap[n];
n--;
downheap(1,n);
return temp;
}
}
class heapsortmethod
{
public static void main(String args[]) throws Exception
{
int temp,n,i,j,k;
BufferedReader cin= new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter the no. of elements");
n=Integer.parseInt(cin.readLine());
heapsort arr = new heapsort(n);
System.out.println("enter the integers to be sorted");
for(i=1;i<=n;i++)
{
arr.heap[i]= Integer.parseInt(cin.readLine());
}
arr.heapify(n);
System.out.println("the elements indescending order are:");
for(i=1;i<=n;i++)
System.out.println(arr.Delete());
}
}

Only of Add & Remove & Heapify Method

Time Complexity O(logn)
Space Complexity O(1)

Saturday, March 19, 2011

WAP to Spell Checking Using Trie

import java.util.*;
import java.io.*;

public class Speller {

Trie trie;

public Speller() {

RandomAccessFile file = null;
trie = new Trie();

try {
file = new RandomAccessFile("C:/Documents and Settings/gur25950/My Documents/Downloads/words.txt","r"); }
catch (IOException ioe) { System.err.println("File not found"); }

try {
for (int i=0; ; i++) {
String word = file.readLine();
if (word == null) break;
if (word.indexOf((int)'\'')!= -1) continue;
trie.insert(word); }

trie.insert("aardvark");
}
catch (EOFException eofe) { }
catch (IOException ioe) { ioe.printStackTrace(); }}


public void insert (String string) {
trie.insert(string); }

public boolean search(String string) {
return trie.search(string); }

public static void main(String [] s)
{
Speller speller = new Speller();
}

}

class Trie {

// make private in implementation
public TrieNode root;


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

// returns index 1-26 for valid words, -1 for
public static int getIndex(char ch) {

if (ch >= 'a' && ch <= 'z')
return (int)ch - 'a' + 1;
else if (ch >= 'A' && ch <= 'Z')
return (int)ch - 'A' + 1;
else
return -1; }


public boolean insert(String string) {

if (string == null) return false;

char ch = string.charAt(0);

TrieNode curr = root.getNext(ch);

if (curr == null) { // 1st word starting with given letter
return addNodesFromRoot(string); }

TrieNode prev = null;

// for each character in the string
for (int i = 0; curr != null && i < string.length(); i++) {
ch = string.charAt(i);

// set node value to character
curr.setValue(ch);

if (curr != null) { // curr NOT null: we have a character match
// is it the end of the string (a match)

if (i == string.length() -1) { // end of string
if (curr.getTerminator() != null) // already exists
return false;
else // terminator for word does not exist
curr.setTerminator(); }

else { // not end of string yet
// select next current

// create a new TrieNode for next iteration if one does not exist
if (curr.getNext(string.charAt(i+1)) == null)
curr.setNext(string.charAt(i+1), new TrieNode());

prev = curr;
curr = curr.getNext(string.charAt(i+1)); } }

else // curr IS null
return addNodes(prev, null, string.substring(i)); } // for

return true; }


public boolean search(String string) {

if (string == null) return false;

char ch = string.charAt(0);

// eliminate non-alpha characters
if ( ! Character.isLetter(ch)) return true; // assume correct

TrieNode node = root.getNext(ch);

boolean found = true;

for (int i = 0; node != null && i < string.length(); i++) {
ch = string.charAt(i);


if (! String.valueOf(node.getValue()).equalsIgnoreCase(String.valueOf(ch))) {
found = false;
break; }
else {
if ( i == string.length() -1) {

return node.isTerminatorSet(); }

else { // keep search going
// System.out.println("CC");
if (! Character.isLetter(string.charAt(i+1)))
return false;
node = node.getNext(string.charAt(i+1)); }
} // else

} // for

if (node == null)
return false;
else
return found; } // search

// completes a word which partially exists in the trie


private boolean addNodes(TrieNode prev, TrieNode curr, String substring) {

curr = prev;
// System.out.println("adding: " + substring);
for (int i =0; i < substring.length(); i++) {
// System.out.println("adding character: " + substring.charAt(i));

curr.setValue(substring.charAt(i));

// curr = new TrieNode(substring.charAt(i));


// now advance prev/curr and test if need to set terminator


if (i == substring.length() -1) { // end of string
// System.out.println("terminating with " + substring.charAt(i));
curr.setTerminator(); }

else { // not end of string yet
// select next current from upcoming character
prev = curr;
curr.setNext(substring.charAt(i+1), new TrieNode());
curr = curr.getNext(substring.charAt(i+1)); } } // for
return true; }

// method adds a new word which is 1st starting with its letter
// need this method since it is the only one which modifies the trie root

private boolean addNodesFromRoot(String string) {
TrieNode node = new TrieNode(string.charAt(0));
root.setNext(string.charAt(0),node);

// determine if word is a one letter word

if (string.length() == 1) {
// System.out.println("setting terminator");
node.setTerminator(); }
else {

node.setNext(string.charAt(1), new TrieNode());
return addNodes(node.getNext(string.charAt(1)), null, string.substring(1)); }

return true; }}

class TrieNode {

TrieNode [] next; // index 0 reserved for terminator value
char value;

public TrieNode(char object) {
value = object;
next = new TrieNode[27]; }

public TrieNode() {
next = new TrieNode[27]; }

public void setValue (char ch) {
value = ch; }

public char getValue() { return value; }

public TrieNode getNext(char ch) {
return next[Trie.getIndex(ch)]; }

public TrieNode getNext(int i) {
if ( ! ( i > 0 && i <= 27 )) return null;
return next[i]; }

public boolean setNext(char ch, TrieNode node) {
next[Trie.getIndex(ch)] = node;
return true; }

public TrieNode getTerminator() {
return next[0]; }

// marks terminator as non null (the TrieNode is just a placeholder)
public void setTerminator() {
next[0] = new TrieNode(); }

public boolean isTerminatorSet() {
return next[0] != null; }

public String toString() {

String string = "";

for (int i=0; i < 27; i++)
if ( next[i] == null ) string += " null";
else string += " +++";
return string; } } // TrieNod


Algo & program Developed By: Julius Dichter

WAP to Efficient Implementation of Trie Data Structure

TRIE is an interesting data-structure used mainly for manipulating with Words in a language. This word is got from the word retrieve. TRIE (pronounced as 'try') has a wide variety of applications in

* Spell checking
* Data compression
* Computational biology
* Routing table for IP addresses
* Storing/Querying XML documents etc.,

We shall see how to construct a basic TRIE data structure in Java.

Data Structure :Trie (Re"trie"ve)

Algorithm For Insertion In Trie

Any insertion would ideally be following the below algorithm.

1. If the input string length is zero, then set the marker for the root node to be true.
2. If the input string length is greater than zero, repeat steps 3 and 4 for each character
3. If the character is present in the child node of the current node, set the current node point to the child node.
4. If the character is not present in the child node, then insert a new node and set the current node to that newly inserted node.
5. Set the marker flag to true when the end character is reached.

Now if you go through the already written code for this, you can have a better understanding by comparing it with the above algorithm.


Algorithm For Searching In Trie

The search alogirthm involves the following steps

1. For each character in the string, see if there is a child node with that character as the content.
2. If that character does not exist, return false
3. If that character exist, repeat step 1.
4. Do the above steps until the end of string is reached.
5. When end of string is reached and if the marker of the current Node is set to true, return true, else return false.

Complexity Ananlysis

operations on how to work with a TRIE, we shall now see the space and time complexities in order to get a real feel of how good a TRIE data structure is. Lets take the two important operations INSERT and SEARCH to measure the complexity.

INSERT operation first. Lets always take into account the worst case timing first and later convince ourselves of the practical timings. For every Node in the TRIE we had something called as Collection where the Collection can be either a Set or a List. If we choose Set, the order of whatever operation we perform over that will be in O(1) time, whereas if we use a LinkedList the number of comparisons at worst will be 26 (the number of alphabets). So for moving from one node to another, there will be at least 26 comparisons will be required at each step.

Having these in mind, for inserting a word of length 'k' we need (k * 26) comparisons. By Applying the Big O notation it becomes O(k) which will be again O(1). Thus insert operations are performed in constant time irrespective of the length of the input string (this might look lik an understatement, but if we make the length of the input string a worst case maximum, this sentence holds true).

Same holds true for the search operation as well. The search operation exactly performs the way the insert does and its order is O(k*26) = O(1).

To understand this, you will have to have a deep knowledge on what "Order" means. The Big O notation is used to tell how the complexity increases according to the increase in the input space. For TRIE ADT, the input space is the number of words that we use. Assume we have 10 words, the insert operation will take a total of its word length multiplied by the 26 letters in the linked list. Which will be equal to k*26. Applying Big O we have O(k*26) = O(1). The reason is this does not depend upon the increase in the number of words that the TRIE is going to have.
Even if the TRIE has a billion words, the insert operation will take a constant time of k*26 which is irrespective of 'n'. So, if you plot a curve you could see that its constant and in Big O terms, it is called as O(1) or constant time insertion


Working Code:

import java.util.Collection;
import java.util.LinkedList;
import java.io.*;

class Node
{
char content;
boolean marker;
Collection child;

public Node(char c){
child = new LinkedList();
marker = false;
content = c;
}

public Node subNode(char c){
if(child!=null){
for(Node eachChild:child){
if(eachChild.content == c){
return eachChild;
}
}
}
return null;
}
}


class Trie{
private Node root;

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

public void insert(String s){
Node current = root;
if(s.length()==0) //For an empty character
current.marker=true;
for(int i=0;i Node child = current.subNode(s.charAt(i));
if(child!=null){
current = child;
}
else{
current.child.add(new Node(s.charAt(i)));
current = current.subNode(s.charAt(i));
}
// Set marker to indicate end of the word
if(i==s.length()-1)
current.marker = true;
}
}

public boolean search(String s){
Node current = root;
while(current != null){
for(int i=0;i if(current.subNode(s.charAt(i)) == null)
return false;
else
current = current.subNode(s.charAt(i));
}
/*
* This means that a string exists, but make sure its
* a word by checking its 'marker' flag
*/
if (current.marker == true)
return true;
else
return false;
}
return false;
}
}

public class TrieLoader
{

public static Trie trieDSA;

public static void main(String[] args)
{
TrieLoader trieLoader = new TrieLoader();
trieLoader.load();

System.out.println(trieDSA.search("bate")) ;

}

public void load(){
trieDSA = new Trie();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
String eachLine = null;
while(!(eachLine=br.readLine()).equals("quit")){
trieDSA.insert(eachLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Processing Time of Dictionary is O(N) N is length of documnet we wants to preprocess.

Time Complexity & Space Complexity Explined Above in Detail as said it is contants e.g. O(k) lenth of String for all operation like inesrting,serching & deleting words in dictionary or trie even if we we wants to play around billions of words :)thats the power of trie.

Time Complexity O(K)
Run Here https://ideone.com/eHGjG

Example Application Trie
http://www.topcoder.com/stat?c=problem_statement&pm=7411
http://www.topcoder.com/stat?c=problem_statement&pm=6215

Algo & Program Developed By BregBoy( A Great Programmer & Tech Lover)