Monday, June 13, 2011

WAP to Delete a Character before the Given Index in Character Array (You Have Given Array of Ascii & kanji Characters)

First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always '0'. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is '1'.

Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index).

We have to write an algorithm & a quality working code for this.


Explanation

1. Look at MSB of the previous character. If 1, then delete the previous two bytes. This is because an MSB of 1 can only be part of a Kanjii character.
2. If the MSB is 0 then all you know is that the previous byte ENDs a character. The previous byte could be an Ascii character, the single byte is the start and the end of the character OR the previous byte is the second byte of a Kanjii character. Look the following figures which show the characters to the left the given character, denoted by ‘|’.

xxx10|xxxxx. You cannot decide on the previous character based on the scan so far because there are two possibilities after this
1. xx010|xxxxx - The previous character is a Kanjii character. After first 0 from left we are left with ‘10’ which is Kanjii.
2. xx110|xxxxx - We have to scan even further. Leads to two choices
x1110|xxxxx - We have to scan even further.
x0110|xxxxx - after leftmost 0, we have ‘110’ which break into ‘11’ and ‘0’. So the previous character is Ascii.

Continuing on this logic you will notice that you have to first find the end byte of a previous character and the only way to do that is to find the previous ‘0’ OR start of the file. After you have found the previous end byte of a character, you count the number of ‘1’ in between the 0 before the cursor and the previous end byte.
1. If number of ‘1’s is even then the previous character is Ascii so the backspace should delete one byte.
2. If the number of ‘1’s is odd then the previous character is Kanjii and two bytes should be deleted.


Data Structure Used: Array

Algorithm

Working Code(In progress)


Time Complexity
Space Complexity
Run Here

WAP to Calculate Maximum Height & Depth of Tree With & Without Recursion

Height/Depth of Tree Without Recursion


Data Structure Used:Queue

Algorithm
1.Insert Root Node in Queue & NUll After root Node.Inserting NULL will help us in measuring height of tree.
2.do remove front element from the queue until its is empty
if(front==NULL)
increment height=height+1;
check queue is empty or not if not insert NULL every time at this step.
else
insert root->left & root->right node into queue.

repeat above step 2 until queue is empty



#include
#include
#include

typedef struct TreeNode {
struct TreeNode *left, *right;
int data;

}TreeNode;


typedef TreeNode * Tree;

/*
*Function which returns height of a binary tree without recursion

We are using level order traversal
*/

int Height(Tree t) {

int height = 0;//-1;

if(t != NULL) {

std::list q; //Queue to store tree nodes

q.push_back(t);
q.push_back(NULL); //null is the delimeter to show end of the level

while(!q.empty()) {

TreeNode *node = q.front();
q.pop_front();

if(node == NULL) {//delimeter encountered, increase height and push NULL if q not empty

height++;

if(!q.empty())
q.push_back(NULL);

}
else {

if(node->left)
q.push_back(node->left);

if(node->right)
q.push_back(node->right);
}

}

}

return height;
}


TreeNode * newNode(int data)
{
TreeNode *node = (TreeNode *)
malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

int main()
{
Tree root = newNode(1);

root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

printf("Height of tree is %d", Height(root));

getchar();
return 0;
}



Time Complexity O(N)
Space Complexity O(1)
Run Here http://ideone.com/gfgru


Maximum Height/Depth of Tree Using Recursion

Algorithm

1. If tree is empty then return 0
2. Else
(a) Get the max depth of left subtree recursively i.e.,
call maxDepth( tree->left-subtree)
(a) Get the max depth of right subtree recursively i.e.,
call maxDepth( tree->right-subtree)
(c) Get the max of max depths of left and right
subtrees and add 1 to it for the current node.
max_depth = max(max dept of left subtree,
max depth of right subtree)
+ 1
(d) Return max_depth



#include
#include
#include

struct node
{
int data;
struct node* left;
struct node* right;
};
int maxDepth(struct node* node)
{
if (node==NULL)
return 0;
else
{ int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);

/* use the larger one */
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}

struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

int main()
{
struct node *root = newNode(1);

root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

printf("Hight of tree is %d", maxDepth(root));

getchar();
return 0;
}

Time Complexity O(N)
Space Complexity O(1)
Run Here http://ideone.com/SoqlA

Sunday, June 12, 2011

WAP to Implement the hash Function For String Variable Which Act as a Key in hashTable

The String hash function

In the String class, for example, the hash code h of a string s of length n is calculated as

hash=a[0]*31^n-1+a[1]*31^n-2+........a[n-1]*31^0

or, in code,

int h = 0;
for (int i = 0; i < n; i++)
 {
     h = 31*h + s.charAt(i);

}
 For example the hash code of hello uses the Unicode values of its characters
h e l l o
  h      e     l      l       o
 104 101 108 108 111(ASCII Values) to give the value 99162332=104*31^4+101*31^3+108*31^2+108*31^1+111
benefits of Doing This is that we won't get same hash values for anagram string e.g. hello & olhel, helol etc.

 In general the arithmetic operations in such expressions will use 32-bit modular arithmetic ignoring overflow. For example Integer.MAX_VALUE + 1 = Integer.MIN_VALUE
 where Integer.MAX_VALUE =2147483647 Integer.MIN_VALUE =-2147483648 Note that, because of wraparound associated with modular arithmetic, the hash code could be negative, or even zero. It happened to be positive in this case because hello is a fairly short string. Thus, for example, the hash code for helloa, which is 31 times the hash code for hello plus 97, would not be , which is outside the range of 32-bit signed integers, but 3074032079-2^32=-1220935217 (which is in the range)

 so After All The Basic & Efficient has Function For String Looks Like
int hash(String key)
{ int h = 0;
  for (int i = 0; i < key.length; i++)
 {
     h = 31*h + s.charAt(i); }
     if(h>INT_MAX)
     return h-INT_MAX // or h % table_size
     else if(h<INT_MIN)
       return h+INT_MAX;

return h; //else return h
}

Another Hash Function Cloud be if consider string only combination of alpha-bates so base 26

if we simply use the sum or crc type hash function we will get the same hash value thus collision.

see hash function

int hash (String s)
{
int k = 0, m = 26;
for (int i=0; i < s.length(); i++)
k += (int)s.charAt (i);
return ( k%m );
}

it will return same hash value for all anagram string as explained above .

int hash(String s)
{
int k = 0, m = 26;
for (int i=0; i < s.length(); i++)
k += (int)s.charAt (i) + i*(int)s.charAt (i);
return ( k%m );
}

benefits of Doing This is that we won't get same hash values for anagram string e.g. hello &
olhel, helol etc.



Some other information on String Hash Function .
http://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier
http://www.jchq.net/certkey/0902certkey.htm 

 
 Feel Free to Comment.

Saturday, June 11, 2011

Application of Segment Tree A data Structure Which Support Update and Query Operation on Array Intervals in Logarithmic Time

A segment tree is a heap-like data structure that can be used for making update/query operations upon array intervals in logarithmical time. We define the segment tree for the interval [i, j] in the following recursive manner:

the first node will hold the information for the interval [i, j]
if i
See the picture below to understand more :

WAP to add a Marble to Box i & sum all the Marbles from Box k to box l .You Have Given The Number of Boxes.

Let's define the following problem: We have n boxes. Possible queries are
1. add marble to box i
2. sum marbles from box k to box l

we have to write an efficient algorithm & then code so that if do m queries in 2nd operation we can efficiently find out the sum of marbles from box i to box j.

This Question is Exactly Asked in Google Interview.

Solution

The naive solution has time complexity of O(1) for query 1 and O(n) for query 2. Suppose we make m queries. The worst case (when all queries are 2) has time complexity O(n * m). (BIT)Binary Indexed Trees are easy to code and have worst time complexity O(m log n).

(BIT)Fenwick tree supports the following basic operations each of which take O(log n) time:
Change the frequency at some position and update the tree
Read the cumulative frequency for a given key
Read the actual (not cumulative) frequency at a certain position
Find the index with a given cumulative frequency, if all individual frequencies are positive, or all indices with a given cumulative frequency, if all individual frequencies are non-negative
It also supports scaling all frequencies in the entire tree by a constant factor in O(n) time.


Algorithm

The two major functions are

update (idx,val) : increases the frequency of index idx with the value val
read (idx) : reads the cumulative frequency of index idx
Note : tree[idx] is sum of frequencies from index (idx – 2^r + 1) to index idx where r is rightmost position of 1 in the binary notation of idx, f is frequency of index, c is cumulative frequency of index, tree is value stored in tree data structure.

Notataion

BIT - Binary Indexed Tree
MaxVal - maximum value which will have non-zero frequency
f[i] - frequency of value with index i, i = 1 .. MaxVal
c[i] - cumulative frequency for index i (f[1] + f[2] + ... + f[i])
tree[i] - sum of frequencies stored in BIT with index i (latter will be described what index means); sometimes we will write tree frequency instead sum of frequencies stored in BIT
num¯ - complement of integer num (integer where each binary digit is inverted: 0 -> 1; 1 -> 0 )
NOTE: Often we put f[0] = 0, c[0] = 0, tree[0] = 0, so sometimes I will just ignore index 0.



Index
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

f
1 0 2 1 1 3 0 4 2 5 2 2 3 1 0 2

c
1 1 3 4 5 8 8 12 14 19 21 23 26 27 27 29

tree
1 1 2 4 1 4 0 12 2 7 2 11 3 4 0 29

Table 1.1



Index
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

tree
1 1..2 3 1..4 5 5..6 7 1..8 9 9..10 11 9..12 13 13..14 15 1..16

Table 1.2 – table of responsibility

#include
using namespace std;

template
class BIT
{
T *tree;
int maxVal;
public:
BIT(int N)
{
tree = new T[N+1];
memset(tree,0,sizeof(T)*(N+1));
maxVal = N;
}
void update(int idx, T val)
{
while (idx <= maxVal) { tree[idx] += val; idx += (idx & -idx); } } //Returns the cumulative frequency of index idx T read(int idx) { T sum=0; while (idx>0)
{
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}
};

int main()
{
int a[100],cur=1,mul=2,add=19,MAX=65536,x,i;
//Initialize the size by the
//maximum value the tree can have
BIT B(MAX);
for (i=0;i<50 data-blogger-escaped-a="" data-blogger-escaped-add="" data-blogger-escaped-b.update="" data-blogger-escaped-cin="" data-blogger-escaped-cur="((cur" data-blogger-escaped-i="" data-blogger-escaped-max="" data-blogger-escaped-mul="" data-blogger-escaped-while="">>x)
{
cout< }

}

Time Complexity O(logn) fro m queries it will be O(mlogn)
Space Complexity O(1)

Source : http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees

Friday, June 10, 2011

Given a binary matrix of N X N of integers , you need to return only unique rows of binary arrays

eg:
0 1 0 0 1
1 0 1 1 0
0 1 0 0 1
1 1 1 0 0
ans:
0 1 0 0 1
1 0 1 1 0
1 1 1 0 0

Data Structure Used: 2 D Array, Hashing


Algorithm:
Find the value of each row, as in 2^(n-1)*a[0][i]+2^(n-2)*a[1][i]+...+2^(0)*a[n][i]
then compare values and write rows which have difft values (think each row as binary representation of number then we just have to convert each row to decimal representation of number)



Working Code:

#include
#include
#define N 5
int main()
{
int a[N]={0,0,0,0,0},b[N]={-1,-1,-1,-1,-1},p,i,j;
int A[][N] = {
{1,1,0,0,1},
{1,1,0,0,1},
{1,0,0,0,1},
{1,1,0,0,1},
{1,0,0,0,0}
};


for(i=0;i=0;j--)
{
if(A[i][j] == 1)
{
a[i] += pow(2,(N-1)-(j));}
}
}
}

for(i=0;i {
j=a[i] % N;
p=0;
while(b[j] != -1)
{
if(b[j] != a[i])
j = (j+1)%N;
else
{
p=1;
break;
}
}

if(p!=1)
{
for(p=0;p printf("%d ",A[i][p]);

b[j] = a[i];
printf("\n");
}
}

return 0;
}


Time Complexity O(N^2)
Space Complexity O(1)
Auxiliary Space O(N)
Run Here http://ideone.com/clpST

WAP to output all the intervals (i, j) where the number of 0s and numbers of 1s are equal.You have an array of 0s and 1s. Efficiently


Example
 
pos = 0 1 2 3 4 5 6 7 8
 
arr = 0 1 0 0 1 1 1 1 0
 
One interval is (0, 1) because there the number of 0 and 1 are 
equal.There are many other intervals, find all of them in linear time.
  
A naive Algorithm will take O(N^3) of time find all such interval 
if wont pre-process till auxiliary array x (where each x[i] will0 
contains the cumulative sum from o to ith index)because in this 
case we need to find all i,j such that they represents equal number 
of 0s & 1s so it will take O(N^3) Time.
But This Algo Will fail for array like 1 0 1 0 1 0 1 0 
you can run here above Algo will print only few intervals 
but as i have counted contains 16 such intervals which are 
of equal numbers of 0s & 1s.
 
2nd Algorithm O(N^2) Efficient
 
Approach
 
In This question we need to find all the intervals and in worst case
no of intervals can grow as large as O(n^2) so hashing will not work
we need to form as adjacency list type of thing :(
 
here what i m trying to do is after calculating the array x if any x[i]
is zero means that that sum of elements from 0 to i is zero hence it
contains equal no of zeros and ones. so for every x[i] = 0 [0,i] is 
a solution, ans also for every x[i] and x[j] if(x[i] == x[j]) implies
that sum does not changes from x[i] to x[j] hence equal no of 0's and
1's [i+1,j].
 
now what i think is finding all the intervals is going to be O(n^2)
 
1.Pre-processing Step
a.Replace all zeros with -1
b.calculate cumulative array X such each x[i] represents the sum from 0
 to ith index in array A
2.Check for every ith index in X array if
a. x[i]==0 then we have found the interval in 0 to i
b. else check for every i if x[i]==x[j] then print the interval from i+1toj
 


#include <iostream>
using namespace std;
 
void isASolution(int i, int j){
    cout << "Interval [" << i << "," << j <<"] contains equal no of 0's and 1's\n";
}
 
void Solve(int a[], int size){
    // replacing 0 with -1
    for(int i = 0; i < size; i++){
        a[i] = 2*a[i] - 1;
    }
 
    int x[100];         //x[i] contains sum of values in a from 0 to ith position
    x[0] = a[0];
    cout << x[0] << " ";
    for(int i = 1; i < size; i++){
            x[i] = x[i-1] + a[i];
        cout << x[i] <<" ";
    }
    cout << endl;
 
    for(int i = 0; i < size; i++){
        if(x[i] == 0){
            isASolution(0,i);
        }
        for(int j = i+1; j < size; j++){
            if(x[i] == x[j]){
                isASolution(i+1,j);
            }
        }
    }
 
}
 
 
int main(){
    int a[9] = {1,0,1,0,1,0,1,0};//{0, 1, 0, 1, 1, 1, 1, 0, 0};
    int n = sizeof(a)/sizeof(a[0]);
    Solve(a,n);
}
 


Time Complexity O(N^2)
Space Complexity O(1)
Run Here http://ideone.com/dF52e
 
Feel Free To Comment, Suggest new Algorithm & Optimize The Solution

Variation:Find the maximum length subarray which maximize the no of 0s and 1s.

Wednesday, June 8, 2011

WAP to Find Nearest Palindrome of Given Number Efficiently

Given a number u need to find a closest palindrome of a number..
Example..
For Example 7957, the nearest palindrome is 7997
if i/p is 1999 then o/p is 2002 not 1991 (Special Case)

1st I thought About By Finding the solution using this algo

Algorithm
Find the Mid Number the from mid + 1 position copy the previous digits in the number in reverse order, i.e .... copy ( mid + 1 ..... N ) positions with ( mid ......1 )
but above case fail for 1999

#include

int nearPalin(int n){
int temp = n;
int count = 0;
while(temp>0){
temp /= 10;
count++;
}
if(count%2 == 0){
count = count/2;
while(count--)
n = n / 10;
temp = n;
printf("%d",n); //testing
while(n>0){
temp = temp*10 + n%10;
n = n/10;
}
return temp;
}
else{
count = count/2;
while(count--)
n = n / 10;
temp = n;
n = n/10;
printf("%d",n); //testing
while(n>0){
temp = temp*10 + n%10;
n = n/10;
}
return temp;
}
}

int main()
{
printf("%d",nearPalin(1999));//1234567890));
return 0;
}

Time Complexity O(N)
Space Complexity O(1)
Run Here http://ideone.com/8B7UO


So After Discussing From Some of The Friends we can solve with some efficient algorithm that will cover the all test cases.

Algorithm
Find The Mid Number & then store half number & append it into in reverse order to original.say it a.

2nd subtract 1 from mid of number & append this half number into reverse number to itself. it will show the number that is palindrome thats is less then given number.
say it b.

3rd add 1 to mid of number & then add reverse of this to itself it will represent the number thats palindrome greater then original number
say it c.

now we have to find which is near to original number so basically we have to find the minimum of 3 number.

Note: Need to Review. As This Algorithm Will Suffer With Integer Over Flow

#include
#include
using namespace std;
long long int abs(long long int a)
{
if (a>0)
return a;
return (-a);
}

int count(long long int a)
{
int count=0;
while (a>0)
{
a=a/10;
count++;
}

return count;

}
long long int reverse(long long int a)
{
long long int b=0;
while(a>0)
{
b=b*10+(a%10);
a=a/10;
}
return b;

}

long long int NearestPalindrom(long long int a,int size)
{
long long rev;

if(size%2==0)
rev=reverse(a);
else rev=reverse(a/10);

long long int num=a;

for (int i=0; i num=num*10;

num=num+rev;
return num;
}

int main()
{

long long int a;
cin>>a;
long long int num=a;

int sizea=count(a);
for(int i=0; i num=num/10;

long long int pa = NearestPalindrom(num,sizea);
long long int pb = NearestPalindrom(num-1,sizea);
long long int pc = NearestPalindrom(num+1,sizea);

int da,db,dc;
da=abs(pa-a);
db=abs(pb-a);
dc=abs(pc-a);
if (da cout< if (db cout< if (dc cout<
}

Time Complexity O(n)
Space Complexity O(1)
Run Here http://ideone.com/l1EY8

Tuesday, June 7, 2011

WAP to Find Number of Way You Can Climb The Stairscase



"You are climbing a staircase. Each time you can either take one step or two. The staircase has n steps. In how many distinct ways can you climb the staircase?"

Algorithm & Approach
is I got the problem correctly then its really nice recursive problem that can solved using F(n)=F(n-1)+F(n-2) recurrence solution as its given that we can either can goto 1 step or 2 step so its just like calculating Fibonacci number using recursion which has exponentiation time complexity . we can initialize f(0)=0 & f(1)=1 as 1st pretty clear that when we are at ground floor we don't need any step to climb & to climb on next staircase up we need only 1 step from 0th staircase. so we start in from n=2 calculate nth Fibonacci number will gives us number of distinct ways can you climb the staircase.

To Calculate The nth Fibonacci Number All Possible & Optimized Solution I have posted in This Post

http://shashank7s.blogspot.com/2011/03/wap-fro-fibonacci-numbers.html

Data Structure Used: Array is Sufficient

Time Complexity O(logn)Most Efficient
Space Complexity O(n)

Sunday, June 5, 2011

WAP to Print All Possible Combination of Given Number From The Given Set "Only".

Given a set of numbers eg:{2,3,6,7,8}.Any one who is playing the game can score points only from this set using the numbers in that set. given a number, print all the possible ways of scoring that many points. Repetition of combinations are not allowed.
eg:
1. 6 points can be scored as
6
3+3
2+2+2

2. 7 can be scored as
7
2+2+3
but 2+3+2 and 3+2+2 is not allowed as they are repetitions of 2+2+3 & so on

3. 8 can be scored as
2+2+2+2
2+3+3
2+6
8

& so on

Algorithms is Pretty Clear if I understand the problem clear, i have already posted the same question with slight modification in which we are not restricted by array elements but we have to print all possible combinations without duplication such that
makes the given sum.

Algorithm

Here is What we do the same keep adding the array value into current-sum until it becomes equals to desired sum isn't it while checking array value is not equals to 0 (as zero don't counts in sum simple )& array values should be <= desired-sum so that we can get all combinations.& repeat the same process until we run out of array.


class PrintAllCombinations
{

public static void main(String[] args)
{
int s = 9;
//int[] a = new int[] {2,3,6,7,8};
int[] a = new int[] {2,3,6,7,8,0,10,66,45,3,56,89};
getCombinatsions(a, 0, s, 0, "");
}

static void getCombinatsions(int[] a, int j, int desiredSum, int currentSum, String st)
{
if(desiredSum == currentSum) {
System.out.println(st);
return;
}


if(currentSum > desiredSum)
{
return;
}



for(int i = j; i < a.length; i++)
{
if (a[i] <= desiredSum && a[i] != 0)
getCombinatsions(a, i, desiredSum, currentSum + a[i], st + "+" + a[i]);
else
break;
}
}


}


Time Complexity (N*2)
Space Complexity O(logn)
Run Here http://ideone.com/x2ICo

Suggestion/Comments are Welcome.??