Anda di halaman 1dari 68

Confused..

trees
I have s alight confusion..
We know that given any two traversals of a tree we can regenerate the tree. Also given,
the preorder we can convert it into inorder. Same is the case with postorder , which can
be converted to postorder.
so basically, if we have either the preorder or postorder of a tree, we can regenerate the
original tree.. is that rt?? so, the preorder or postorder of any tree is unique.. Is it?? Or are
their any conditions that I have missed, just like the conditions for converting a preorder
to postorder...
smbdy pls clear up this mess...
saurabh! taylor
7/28/2006 11:44 AM

if you are a preorder of a tree you jsut can't create a tree , there can be lots of trees, for
constructing a tree we require preorder and the inorder of the tree...
Anket
7/28/2006 11:04 PM

Hey Abhinav,
Well i wont answer ur question, instead u'll answer it urself. Start with any binary tree
and write their respective preorder and postorder traversals, and using them work urself
back all the way to get the original tree. And yeah you do need atleast 2 traversal coz the
any traversal by itself does not provide any partitioning information, so for getting that
information, i mean to recognize root and subtrees you definitely need atleast two
traversals. Hope ur not confused anymore....
Nirmal
8/3/2006 6:47 AM

no no, u cannot regenerate the tree using its preorder and postorder traversals.root will be
found alright but how will u distinguish b/w left and right subtree? think about it
simplest eg of this situation is:
preorder:AB
postorder:BA
here 2 binary trees are possible.
an interesting question can be: find a condition neccesary and sufficient which the tree
must fulfill in order to be regenerated using preorder and postorder traversals?
Satyendra
8/3/2006 10:02 AM

condition= no distinction shud be made between left and right subtrees or binary tree
shud nit be ordered. m i correct?
Nirmal
8/4/2006 3:41 AM

correct,
but it can be generalized further, even for ordered trees like BST
Vipin
10/8/2006 12:07 AM

Hey Nirmal BST can be constructed with just preorder or postorder traversal Given.
InFact this was one of the question given in this years Versata paper. Becos inorder
traversal is always in increasing order in BST
A NEW THREAD WITH NEW TOPIC(DYNAMIC PROGRAMMING)
u r given an array containing real values(+ve,-ve or 0). find the contiguos subarray in this
array with maximum sum using dynamic programming.
for eg
with array={ 1,25,-3,-6,3,-10,-20,10} answer is 26 here
with startpos=0,endpos=1 0-based index.
also specify recurrence or realtion used.
Time complexity=O(n) and space complexity =O(1)
***Use Dynamic Programming
vikas
9/2/2006 4:15 AM

here s the solution using DP approach...


int maxsum(vector<int>a)
{ int mx=a[0];
vector<int>soln(a.size());
soln[0]=a[0];
for(int i=1;i<a.size();i++)
{ soln=max (soln[i-1]+a,a);
mx=max (mx,soln);
}
return mx;
}
this is based on the following recurrence relation..
soln[i+1]=max (soln+a,a)
and mx=max(soln)
Satyendra
9/2/2006 5:46 AM

gr8 work recurrence is soln(i)=max(soln(i-1)+a(i),a(i))


as orkut has done sum cutting with what vikas wrote
now see that only previous value is needed so can be done in O(1) space and sub array
can also be got
Satyendra
9/2/2006 5:57 AM

int maxsum(vector<int>array,int&start,int&end)
{ int maxval=array(0);
2

start=end=0;
int cursum=maxval;
int curst=0,curen=0;
for(int i=1;i<array.size();i++)
{ if(cursum+array(i)>array(i))
{ curen++;
cursum+=array(i);
}
else
{ curst=i,curen=i;
cursum=array(i);
}
if(cursum>maxval)
{ maxval=cursum;
start=curst;
end=curen;
}
}
return maxval;
}
Nirmal
9/5/2006 3:10 AM

try this
find maximum sum subsequence( different from subarray in the sense that it cud be non
contiguous) in the same array. try to do this in O(nlogn) time
Satyendra
9/5/2006 7:06 AM

is the sequence in increasing order as without this condition soln is quite easy?
Nirmal
9/5/2006 7:54 PM

oh i meant maximum length inc/dec subsequence, not maximum sum


Siddharth
9/17/2006 5:50 AM

Can you please explain


I am not familiar with DP.
Can you please explain how this code works.
thnx.
Sid
Siddharth
9/17/2006 6:00 AM

Somethings Wrong
The solution feels weird.
Are you sure it is correct. I profess full humility and i may be dumb.
Question#11 [O(1) List Reversal]

7/10/2006 3:24 AM

Shivkumar Question#11 [O(1) List Reversal]


A linked list is to be implemented in C using the structures declared as

struct node
{
void *data ;
struct node *next ;
};
struct list
{
struct node *head, *tail ;
};

write the function struct list* reverse(struct list*) ;


which receives a list and returns the reversed list.
But, but, but....this time the reverse should be done in O(1) time.
Ofcourse the rudimentary list maintainence operations, precisely insert
and delete, are also to be designed accordingly (by you), so that the
reversal method agrees
with them.
THIS IS BASED ON A REALLY COOL TRICK!!! I hope you've gone
thru the concerned topics in Tenenbaum.
7/10/2006 7:30 AM

Satyendra head
--B[0]<-B[1]<-B[2]<--......B[n-1]<---|----|-----|-----|-------------|------------|
|----|-----|-----|-------------|------------|
|--v[0]--v[1]---v[2].........v[n-1]------|
|----|-----|-----|-------------|------------|
|----|-----|-----|-------------|------------|
->A[0]->A[1]->A[2]->.......A[n-1]-----------------------------------tail
i maintain 2 linklist always namely A & B
figure above shows it for size n and v r data values

now head points to B[0] and tail points to A[n-1]


and reversal can be done be following code
void reverse(list linklist)
{ linklist->tail=linklist->tail->next;
linklist->head=linklist->head->next;
node*temp=linklist->head;
linklist->head=linklist->tail;
linklist->tail=temp;
}
7/10/2006 7:31 AM

Satyendra my algo is
u hav 2 linklist A & B
now A(i)->next=A(i+1)
B(i)->next=B(i-1)
A(i)->data=B(i)->data=commom data
A(n-1)->next=B(n-1)
B(0)->next=A(0)
head=B(0)
tail=A(n-1)
7/10/2006 7:32 AM

Satyendra insertion code


void insert(list linklist,T val)
{ node*temp1=new node;
node*temp2=new node;
T*data=new T;
*data=val;
temp1->data=data;
temp2->data-data;
if(linklist->head==NULL)
{ temp1->next=temp2;
temp2->next=temp1;
linklist->head=temp1;
linklist->tail=temp2;
return;
}
temp1->next=temp2;
temp2->next=linklist->tail->next;
linklist->tail->next=temp1;
linklist->tail=temp1;
}
7/10/2006 7:40 AM

Shivkumar urachamp!
7/10/2006 10:11 AM

greaaaat solution!!!!!

7/11/2006 8:29 AM

Satyendra sorry for reversal just swap head and tail or do


swap(&(linklist->head),&(linklist->tail));
hi
hey guys can n y one tell me how 2 prove dat for a tree having n nodes of degree 2
has 2n+1 leaf nodes....
Amit
9/13/2006 8:50 AM

@anuprem collage main hi pooch leta na.


Let the number of children as the degree. Assume n0 as the # of nodes with degree 0, n1
as #of ndoes with degree 1 and n2 as ...
we can easily have n1+2*n2 = N-1 since each node except the root has one and only one
parent. Also we have n0 = N-(n1+n2) or (n1+n2) = N-n0. Combining the two equations,
we have (N-n0) + n2 = N-1. Thus n2 +1 = n0.
Kartik
9/14/2006 11:19 AM

we have to prove that if the no. of nodes with degree 2 in a tree is n, then the no. of leaves
is n+1(not 2n+1 as given in the question).
heres a recursive method (its sumthing like induction).
consider the root node. there r 3 possibilities :
1)it has no children. then n=0, and leaves =1. hence the condition is satisfied.
2)it has only one child. in this case, the node isnt a leaf, nor is it a node of degree 2, so its
not a part of n, nor is it part of the no. of leaves. so as long as the subtree satisfies the
condition, it will as well.
3)it has two children. now if we consider that both the subtrees satisfy the condition, and
we let no. of nodes of degree two in left subtree be n1 and that in right subtree as n2,
then no. of leaves = n1 + 1 + n2 + 1 = (n1+n2) + 2.
the total no. of nodes with degree will be n = n1 + n2 + 1 (the node itself). therefore, the
no. of leaves = n+1.
awesum problem by budhrani
how to remove a cycle from link list, ofcourse efficiently.. apparently reversing the link
list twice does nt work.
Satyendra
8/24/2006 12:50 PM

find length of loop=ll(length of loop). let length of linklist=l


step1.now move 1 ptr to ll node ahead of 1st node inclusive.
step2. now after above step move 1 ptr from head of list nad other from where it was left
in step1. the place where they will meet will be the culprit node. once u get cuprit node
then fixing loop is easy.
proof that they will meet at cuplrit node

ptr1 at llth node after step1. now ptr2 at head.


move ptr1 ny (l-ll) node distance then ptr2 will be at (l-ll)th node and ptr1->next=ptr2
here so loop can be fixed
Siddharth
9/1/2006 1:11 PM

Lookup for Next Pointers


Simple Lookup based solution
We can put the next pointers into a BST as we traverse the link list.
As we traverse, we look up for the next pointer in our BST.
If a match is found, we change the next pointer to NULL as that is the loopback node.
Satyendra
9/1/2006 1:13 PM

@siddharth using bst that wont be O(n) worst case


Pradeep
9/10/2006 11:06 AM

styendar
plz can u expalin me how to find da length of linklist if there is an cycle in the
list............plz
Lalit
9/10/2006 11:49 AM

just take two pointers


advance 1 pointer by 1 node and other by 2 nodes at a time ...
if there is a cycle .. the first pointer should be equal to second at some point. set the the
next pointer of node previous to when they meet to be NULL
Siddharth
9/14/2006 10:33 AM

@Lalit and Final Solution


Lalits solution has a flaw.
However, the 2 pointer method will land as at a place inside the loop . Once you are at a
position inside the loop, you can easily calculate loop length. Let it be l.

Then do this
node * p1, * p2
p1 = p2 = start;
for(int i=0:i < l-1; i++)
p2=p2->next;
while(!( p2->next == p1))
{
p1 = p1->next;

p2 = p2->next;
}
p2->next = NULL;
At the end of this, p2 points to the loopback node.
Question#14 [Max occurence]
Given an array of n+1 elements. Each element in the array
lies in the range [1, n]. This ensures that at least one element in the array is repeating.
You have to find out which element is repeating maximum number of times. In case of a
tie, report the one with the lower value.
EFC:
time - O(n)
space - O(1)
This is a perfect question as far as an interview's concerned, a bit of trick and a bit of
experience is required to crack it there and then.
Rudhir
7/10/2006 5:06 AM

my algo is as follows1) find the freq of every element in the array (i will be providing code for this).
the original aaray will be modified to contain freq. time -O(n)
2) now find the largest element in this array in O(n) time.
3) now traverse the array from beginning and stop where a==largest.
note a has freq for element i.
space - O(1).
Shivkumar
7/10/2006 5:38 AM

if you can provide algo for (1) in O(1) space then you are done
Rudhir
7/10/2006 6:12 AM

void freq(int a[],int n)


{
int i,j,cur=0,t=0;
j = 0;
while(j<n)
{
while(a[j]<0) // if the element is processed
j++;
cur = a[j]; // value of current elemnt
8

a[j]=0; // put the flag that this element has been processed
if(cur==a[cur]) // if hoping to same element
a[cur] = -1;
else{ //else
while((t=a[cur]) > 0) // hop to different elements storing value in t
{
a[cur] = -1;
cur = t;
}
a[cur]--;
}
j++;

}
for(i=0;i<n;i++)
//if(a<0)
printf("%d frq %d\n",i,-(a));
}
this is O(n) in O(1) space
meet ashish
7/16/2006 8:36 AM

maintain a bit vector ..update it as number are read ..bt it wil be updated only if
correspnding bit is "0"..if it is 1...hence it is repeated
Anket
7/29/2006 1:11 PM

@ ashish
Yeah... I think thats the correct solution...
Amit
9/2/2006 2:02 PM

How about this


int freq(int a[],int n)
{
for(int i=0;i<n;i++)
{
int elem=a%n;
arr[elem]+=n;
9

}
int max_dup=0;
for(i=0;i<n;i++)
{
if(arr/n==1)
{
}
else
{
int dup=arr/n;
if(max_dup<dup)
max_dup=dup;
}
arr=arr%n;
}
return max_dup;
}
Siddharth
9/4/2006 9:46 AM

Very Elegant Way


This is an extremely elegant way of in place counting:
given a[0..n] and a <= n for all i
Algorithm
for(i=0;i<n;i++)
a[ a % n+1 ] += n+1;
for(i=0;i<n;i++)
a/= n+1;
this gives us Final Count in a such that count of number i is a
How this works
1. Uses fact that no number can be greater than n
2. The counting for a given position is done by adding n+1 each time a number is
encountered to its respective position.
e.g. if a[2] = 3,
then a[3] += n+1;
the trick is that adding n+1 retains original data in a position too which can be obtained
by doing (a % n+1);
This is really cool since we retain original data as well as count.
10

Try it out
and it is O(0) space
prime at primth positions
ur task is to print prime nos at primth positions
for eg, out of these primes: 2,3,5,7,11,13
3,5,11 are at prime position ie, 2,3 and 5 respectively
print first 100 such primes.
try to bring it close to linear runtime.use memory judiciously.
Satyendra
8/24/2006 1:02 AM

int isprime(int n)
{ if(n==2||n==3)
return 1;
if(n<5)
return 0;
if(n%2==0)
return 0;
for(int i=3;i*i<=n;i+=2)
if(n%i==0)
return 0;
return 1;
}
void print()
{ int mem[MAX];//init to 0
int count=0;
mem[2]=1;
int pos=2;
for(int i=3;count<100;i+=2)
{ if(i%6==1||i%6==5)
{ mem(i)=isprime(i);
if(mem(i)==1)
if(mem(pos)==1)
{ pos++;
count++;
cout<<i<<" ";
}
else
pos++;
}
}
}
Question#13 [Second Largest]
Use only N + O(log n) comparisons to find the second largest (or smallest) element in a
list of N elements. This is a question straight from tenenbaum. Though, we guys weren't
11

able to crack it one hundred percent but Nishant (got thru Yahoo) proposed a very lovely
method for doing this. You guys too give it a try...
Rudhir
7/10/2006 6:17 AM

Well this is not my solution but i have heard from others.


1) take pairs of elemnts in array and find the max of each pair. and keep doing this until u
have 1 elemnt which is max.(each iteration reduces the set half.)
2) now move from top to bottom comparing each pair of elemnts.
Shivkumar
7/10/2006 6:18 AM

like a tennis knockout!

nitin
7/16/2006 7:00 AM

i have an alternate solution u guys please check wheather it's correct acc.to complexity
requirment otherwise code is working fine.
logic:1.make a max or min heap using O(N) or only N comparision, this take only O(1) space
2. impement heapsort algo for only 2 iteration result of second iteration is what we want.
Satyendra
7/16/2006 7:12 AM

@nitin
question is not that u hav to find it in
n+O(lgn) comparisons
but u hav to find it in
n+lgn-2 comparisons
so max no of comparisons=n+lgn-2
Nirmal
8/5/2006 10:17 PM

has anybody tried to write a code for this problem? touch difficult but worth trying.
@nitin
to form a heap time complexity is O(N) or nearly 4N, so using heap is not an option since
u can find second largest in 2N time anyway; however it must be done in N+logN steps.
Aamer
8/16/2006 10:42 AM

will this work ?


#define SIZE 9
int main()
{

12

int arr[SIZE] = {1,2,3,12,4,5,16,7,8};


int max,secmax;
max = arr[0];
secmax = arr[1];
int j;
for(j=2;j<SIZE;j++)
{
if(arr[j] > max)
{
secmax = max;
max = arr[j];
}
if(arr[j] > secmax && (arr[j]!=max))
{
secmax = arr[j];
}
}
cout<<"max = "<<max;
cout<<"\nsecmax = "<<secmax;

cin.get();
return 0;
}
time complexity is O(n) ...
Aamer
8/23/2006 10:02 AM

i missed chking between a[0] and a[1] for max/...


so ther needs to be a condition..
if(secmax >max)
{ max =a[1];
secmax =a[0];
}
on 2nd thoughts this algo requires 2n comparisions..
i found a better link for this ques..
en.wikipedia.org/wiki/Selection_algorithm#Linear_general_selection_algorithms
Nirmal
8/23/2006 11:55 PM

13

i think its not possible to do it in N+logN-2 'steps'.


it could be done in N+logN-2 comparisons with some extra memory(2N-1, in my
opinion) or extra data movement.
if u have knuth vol-3 look at sections 'sorting by selection' and 'minimum sortingselection'. u ll gain some gud insights.
Today's Question
I shall try and put one question each day to give you a feel of what companies like
Trilogy, Adobe, Microsoft, Yahoo and Google ask, atleast as far as
Algos/DS/Programming is concerned.
Shivkumar
7/4/2006 12:13 PM

Nearest Common Ancestor


Given the root of a binary tree and any two nodes in it, device an algorithm to find out the
nearest ancestor to the given two nodes. Assume the tree has only left and right child
pointers and no parent pointers.
Satyendra
7/4/2006 12:15 PM

if each node has diff info then preorder and inorder traversal can be used to give content
of lca info.
Satyendra
7/4/2006 12:17 PM

otherwise if we can modify tree then using inorder traversal and changing left and right
pointer to point to fathers node we can reach upto 2 nodes and then traverse back upto
lca.
Satyendra
7/4/2006 11:16 PM

simple

but inefficient implementation

vector<node*>node1t,node2t,trav;
void traverse(node*node1,node*node2,node*root)
{ if(root==null)
return;
trav.push_back(root);
if(root==node1)
node1t=trav;
if(root==node2)
node2t=trav;
traverse(node1,node2,root->left);
traverse(node1,node2,root->right);
trav.pop_back();
}
node* lca(node*node1,node*node2,node*root)
{ traverse(node1,node2,root);
for(int i=node1t.size()-1;i>=0;i--)
for(int j=node2t.size()-1;j>=0;j--)
{ if(node1t(i)==node2t(j))
14

return node1t(i);
}
return null;
}
monika
7/5/2006 1:39 AM

i don think its efficient cos it involves recursion+ a stack(havin two members each nodeone a ponter to the tree node type and a flag); also usin a static var count(static works this
way na satty??)

traverse(r)
{
static count=0;
if(r== NULL) return;
push(r);
if(r==x||r==y)
{count++; pop();
if(count==1){top->flag=1; return;}
if(count==2)return;
}
else
{
traverse(r->left);
traverse(r->right);
do{node=pop();}while(node->flag!=1);
if(count==2){ans=node;exit();}
else{pop();top->flag=1;}
}
}
Rudhir
7/5/2006 4:55 AM

there could many methods of solving this problem but everyone will have the same time
complexity O(n) and space complexity O(n).none better than this can be made
Satyendra
8/20/2006 9:59 AM

node*LCA=NULL;
int lca(node*node1,node*node2,node*root)
{ if(LCA!=NULL)
return 2;
if(root==NULL)
return 0;
if(node1==root||node2==root)
{ int kyaaleftmehai=lca(root->left,node1,node2);
if(kyaaleftmehai==1)
{ LCA=root;
return 2;
15

}
int kyaaritemehai=lca(root->right,node1,node2);
if(kyaaritemehai==1)
{ LCA=root;
return 2;
}
return 1;
}
int kyaaleftmehai=lca(root->left,node1,node2);
int kyaaritemehai=lca(root->rite,node1,node2);
if(kyaaleftmehai==kyaaritemehai&&kyaaleftmehai==1)
{ LCA=root;
return 2;
}
return kyaaleftmehai+kyaaritemehai;
}
2nd Question a probability one
u hav (a) boxes of which u pick any 1 u win
u hav (b) boxes of which u pick any 1 u lose
u hav (c) boxes of which u pick any 1 u will hav to pick a box again and currently picked
box is then out of game.
so in total u hav (a+b+c) boxes
find the probability of u winning.
Anket
8/18/2006 6:41 AM

I guess its quite simple. You might win in the first attempt, or second or third till all the
boxes of c category are removed and you pick the box of category a and then you win. So
the probability of winning would be....
(a/a+b+c)+(c/a+b+c*a/(a+b+c-1))+..........((c/a+b+c)*(c-1/a+b+c-1)*(c-2/a+b+c-2)....
Satyendra
8/18/2006 8:47 AM

q is now to prove that ans is a/(a+b)


3 google questions
after sum R&D i found 3 q of google palcement paper.
plz tell me more efficient solns than mine if mine r correct otherwise plz point out
mistake and tell me the soln

Q.1.Given a number, describe an algorithm to find the next number which is prime.
int nextnum(int n)
{ for(int i=n+1;;)
{ int j=0;
16

for(j=2;j*j<=i;j++)
if(i%j==0)
break;
if(j*j>i)
return i;
}
}

Q.2 # There are a set of 'n' integers. Describe an algorithm to find for each of all its
subsets of n-1 integers the product of its integers. For example, let consider (6, 3, 1, 2).
We need to find these products :
* 6 * 3 * 1 = 18
* 6 * 3 * 2 = 36
*3*1*2=6
* 6 * 1 * 2 = 12

Ans.vector<int> soln(vector<int>a)
{ int prod=1;
for(int i=0;i<a.size();i++)
prod=prod*a(i);
vector<int>soln(a.size());
for(int i=0;i<a.size();i++)
soln(i)=prod/a(i);
return soln;
}
4.Given two sorted postive integer arrays A(n) and B(n) (W.L.O.G, let's
say they are decreasingly sorted), we define a set S = {(a,b) | a \in A
and b \in B}. Obviously there are n^2 elements in S. The value of such
a pair is defined as Val(a,b) = a + b. Now we want to get the n pairs
from S with largest values. The tricky part is that we need an O(n)
algorithm.
vector<vector<int> > soln(vector<int>a,vector<int>b)
{ vector<vector<int> >res(n,2);
res(0)(0)=a(0),res(0)(1)=b(0);
int i=0,j=0;
for(int k=1;i<n;k++)
{ int v1=a(i)+b(j+1),v2=a(i+1)+b(j);
int v3=a(i+1)+b(j+1);
int maxv=max(v1,max(v2,v3));
if(v1==maxv)
j++;

17

else if(v2==maxv)
i++;
else
i++,j++;
res(k)(0)=a(i),res(k)(1)=b(j);
}
return res;
}
Kartik
7/26/2006 4:53 AM

hmm, lets go one by one.


Q1 i dunno if there is a better method around, but ur code can certainly be optimized to
make it 2 to 4 times faster.
firstly, u shud begin with n+2. simple reason being, n+1 cannot be prime. since prime
no.s, except 2, r all odd. so u start with n+2 and increase by 2 each time.
also, applying the same logic to the smaller loop, u shud only check it by dividing it with
3 onwards, n incrementing j by 2. no point in checking by dividing by even no.s.
about Q2, i dont think ur soln can be improved.
about Q3. well, i need to think abt that question abhi...
Anket
7/26/2006 8:13 AM

For question no. 1


Well all prime numbers are found to satisfy 6n +/- 1, but not always the other way
around. So for a given prime number, which is of form 6n +/- 1, we find the initial value
of n, say n1. So we may start our loop with n1+1 which for now we call it n2 and using
the formula 6n +/- 1, we can check further which may reduce the calculations by say 6
times, and checking divisibility by odd integers only, which furthers doubles up the
speed, so the speedup factor of the improved algo would be about 12 times faster than the
proposed one.
Anket
7/26/2006 8:19 AM

For question 2
I dont think that there is any room for improvement here.
Anket
7/26/2006 9:42 AM

For question no 3
I dont think that the proposed algo is a correct one. But despite my concious efforts the
best solution that i can think of is as follows which i am explaining with a diagram.
According to the question the 2 arrays are arranged in non increasing order thus the index
1 of both the arrays will store the greatest integer. The diagram is as follows :

b\a 1 2 3 4 5 6
1XXXXXX
18

2XXXXXX
3XXXXX
4XXXXXX
Lets say that a1>b1. Now without doubt the first greatest value pair will be that of a1,b1
,but now for the next pair to be chosen, we have competition between a1,b2 and a2,b1.
Suppose our choice was a2,b1 then for the next entry we have a competition between
a3,b1 , a2,b2 and a1,b2. So the problem is not that trivial since we have to keep track of
the previous stacks too, so when we reach say a6 column we have to keep track of
previous columns too. So what i propose here is to make a max heap. We put all the
previous column competing pairs into the max heap, so now taking the greatest value pair
is just a matter of comparing 3 values ie the topmost pair of the heap, the competing pair
in current column and the pair in the next column. Whenever we pick a pair from the
heap, we insert the next in the same column from which the choice has just been made,
thus limiting the insertions into heap. So the overall complexity of the above algo would
be O(n + r.t), where r is the number of time the insertion in the heap was done and t is the
time it takes to insert an item into it, so the overall complexity is based on the
comparision between n and t, and which one is bigger.
Now this is the best solution i can think of. If someone thinks of a better one, pls do let
me know by scrapping me.
Vipin
7/26/2006 1:28 PM

think this is a better soln.


if(n==2)
printf("\nNext prime is 3");
else
{
for(i=n+2;;)
{
k=(int)sqrt(i);
for(j=2;j<=k;j++)
{
if(i%j==0)
break;
}
if(j>k)
{
printf("next prime is %d",i);
break;
}
i+=2;
}
}
as one need to check till square root of that no for comparison.
say n=17
to check 17 is prime we need a loop
19

(int)sqrt(17) is 4
for(i=2;i<=4;i++)
{
if((i%2)==0)
break;
}
if(i>4)
printf("\n no is prime");
Rudhir
7/26/2006 11:38 PM

@anket
yaar though i didnt get ur algo 100% but it cant be O(n) as u proposed.
the pairs u r inserting are increasing exponentially so the insertion is not O(n)..and hence
the algo is not O(n).
@vipin
u can increase the efficiency by incrementing either by 4 or 2 alternatively.
Return of the
7/26/2006 11:46 PM

Q2
guys i had solved the problem. did not post as the logic was similar. ddi not go thru the
code thoroughly. i have a soln that takes care of the objection raised by anket.
it is laso order n
#include<conio.h>
#include<iostream.h>

void sort_top_n(int a[10], int b[10], int n)


{
cout<< "\n ( "<<a[0]<<", "<<b[0]<<" ) " <<endl;
int count=1;
int a1=0,b1=0,a2=1,b2=1,a3=1,b3=1,next;
while(count<n)
{
next= a[a2]+b[b2];
if( a[a1]+b[b3] > a[a3]+b[b1])
{
if(a[a1]+b[b3] > next)
{
cout<< "\t ( "<<a[a1]<<", "<<b[b3]<<" ) " ;
count++;
b3++;
}
else
20

{
cout<< "\t ( "<<a[a2]<<", "<<b[b2]<<" ) " ;
a1++;b1++;a2++;b2++;
count++;
}
}
else
{
if(a[a3]+b[b1] > next)
{
cout<< "\t ( "<<a[a3]<<", "<<b[b1]<<" ) " ;
count++;
a3++;
}
else
{
cout<< "\t ( "<<a[a2]<<", "<<b[b2]<<" ) " ;
a1++;b1++;a2++;b2++;
count++;
}
}
}//end while
}//end function
main()
{ int a[10], b[10];int n;clrscr();
cout<<"\n enter the size of the array:";
cin>>n;
cout<<"\n enter the elemeentsof a:"<<endl;
for(int i=0;i<n;i++)
{
cout<<"\n enter the element:" ;
cin>>a;
}
cout<<"\n enter the elemeentsof b:"<<endl;
for( i=0;i<n;i++)
{
cout<<"\n enter the element:";
cin>>b;
}
sort_top_n( a,b,n);

21

getch();
return 0;
}
Return of the
7/26/2006 11:49 PM

Q-2
i have tested the sode on pc also. i think its a good code and suggestions are welcome.
i have used some extra no of variables to keep tarack of things but it lends claerity to the
code
Anket
7/27/2006 1:17 AM

hey klinsman
hi klinsman,
well how do you propose to keep track of the competing pairs by using only constant no.
of variables. The no. of competing pairs would definitely increase, so how are you
keeping track of that. Well the algo itself is quite obscure, unless you give me some
insight as to the kind of logic ur using to solve the problem of keeping track of increasing
no. of competing pairs.
hi
lets for the sake of convenience assume that arrays are sorted in reverse order.( it does not
matter as u all know)
the larget element is a[0]+b[0]
now for the second its a[0]+b[1] or a[1]+b[0]
for the third its either a0+b2( if last was a0+b1) or a1+b1 or a2+b0( same as above)
now if first case is true increment b, for third increment a else increment a1 and b1 so that
they become a2,b2
now continue in this way
Return of the
7/27/2006 11:58 AM

just check with paper pencil


hey ankit, if u still dont understand my logic, try with paper pencil. i am sure u will
appreciate the code
Siddharth
7/28/2006 12:21 AM

how bout changing representation


i suggest we change reprsentation of data into this form
suppose we have,

22

a1, a2, a3, a4, a5 .....


in decreasin order
change rep to
0, a1 - a2, a2 - a3, a3 - a4, a4 - a5 ...
this can be written as
A1, A2, A3, A4 .......
similarly
let
B1, B2, B3, B4 .......
=
0, b1 - b2, b2 - b3, b3 - b4, b4 - b5 ...

Now traverse the two arrays with two pointers


just check the smaller dip in sum that will occur by moving pointer forward on any of the
two arrays, and take the smaller dip.
much simpler than any heaps or anything.
O(n) time and 0(2) memory for two pointers.
:)
Kartik
7/28/2006 4:43 AM

hmm, i dont think some ppl here have completely understood the qn. i dont have an O(n)
soln, but dont think anyone has come up with it yet.
most importantly, ppl r only considering the first few cases. if u continue analyzing, u'll
find that, as u keep moving on, the no. of candidates continuosly increase.
i thot a bit abt taking the differences and then solving, but cudnt come up with a gud soln.
u still need sumthing extra to compare the increasing no. of candidates.
there must be a greedy soln to this. but i dunno. either that or this qn is wrong
Siddharth
7/28/2006 4:50 AM

23

hv u checked my solution
my solution is definitely o(n) and there are only 2 cases at any given time.
Anket
7/29/2006 12:48 PM

@ Kartik
Yeah i agree, most of the solutions that have been circulating around has been taken by
keeping into consideration the first few cases, but its not that easy. As the program goes
on the number of competing pairs increases, and thats what i have been trying to explain
from the start, so we just cant keep track of the growing competing pairs by maintaining
just three set of variables. Try to understand guys that any choice that we make, the next
pair may not be in +/- 1 vicinity. Though the solution i provided is not O(n) but atleast
the logic was correct.
Kartik, i do agree that a greedy solution will ultimately give the answer, but i think that
we would need some advanced data structure to keep track, coz making a greedy choice
itself using simple data structures would not yeild a O(n) solution.
Kartik
7/29/2006 1:59 PM

I got the correct solution finally.


I dunno wht method it is, its certainly not greedy, but its a solution. it required a lot of
utpatang thinking, n its a bit weird, but it'll work, i think.
And its an O(n) solution i am sure.
here it is.
Kartik
7/29/2006 2:03 PM

Lemme try n explain this. Its a bit complex.


hmm, k. lets take the case when i=1, i.e. the first n the largest element.
ja and jb r pointers and form the pairs a(i),b(ja) and b(i),a(jb).
k points to pairs with same index.
Now what is going on in this algorithm is, we compare the pairs formed by the
largest elemnts to the pair formed by by elements of the same index.
suppose for some k, the pair formed by k is greater than the pairs a(i),b(ja)
and b(i),a(jb). then what it means is that all pairs that can be formed by
the elements from a(1) to a(k) and b(1) to b(k) r also greater.
so we keep incrementing these, till we get count=n (n hence the solution) or we
exceed n. This can only happen if we incremented k. So we decrement k, and
increment i, since the pairs formed by i cannot be part of the n pairs anymore.
This loop runs atmost n times. and ofcourse to print the pairs, print() runs n times.
Kartik
7/29/2006 2:17 PM

@anket - i havent used any complex data structure or anything, n its not greedy. so if it is
right (i am not completely sure about that, even tho i think logically its perfect), its very
weird and totally unexpected, i wudnt have believed so myself a day back.
24

so guys, please verify so i can be sure. n if it is correct, someone please solve the chords
in circle question so my mind can be free these two questions have been bothering me
a lot for the last few days.
Kartik
7/29/2006 2:42 PM

a(1...n)
b(1...n)
count = 1;
i = 1;
k = 2;
ja = jb = 2;
print(i,i);
sum_k = a(k)+b(k);
sum_a = a(i) + b(ja);
sum_b = a(j) + b(jb);
while(1)
{
if (!(k<ja && k<jb) || (sum_k<sum_a || sum_k<sum_b))
{
if (sum_a>sum_b)
{
print(i,ja);
ja++;
count++;
sum_a=a(i)+b(ja);
}
else
{
print(i,jb);
jb++;
count++;
sum_b=b(i)+a(jb);
}
}
else
{
count+=k+k-1;
if (count>n)
25

{
count-=k+k-1;
k--;
i++;
ja=k+1;
jb=k+1;
}
else
{
for(p=i to k)
{
print(i,k);
print(k,i);
}
k++;
sum_k=a(k)+b(k);
}
}
if (count==n)
break;
}
sorry
i m very sorry for the immature solution that i suggested.
meet ashish
8/1/2006 3:41 AM

at every point keep check a+b,


a[i+1]+b,a+b[i+1],a[i+1]+b[i+1] , take max three of these , if less than 'n' n keep a
flag whether a[i+1]+b[i+1] is included or nt, if yes than dnt include it next comparison

... Nice question..


U have an array of n integers from 0 to n*n - 1 . Sort the array in O(n) time.
Satyendra
7/27/2006 12:40 PM

we can use radix sort to sort the array in O(n) as range is defined [0,9] for each digit in no
so radix sort with counting sort can sort the array in O(n)
Anket
7/29/2006 12:57 PM

26

Yeah radix sort, bucket sort any will do...


@Abhinav
Try radix sort, which has a complexity of O(d*n), where d is the number of place values,
thus making the overall complexity O(n), since d is always a constant or we suppose it to
be a constant by restricting the values of the keys.
chords in circles
u have n chords in a circle, each with distinct end points (the chords r defined by their
end points). calculate the total no. of pairs of chords that intersect in O(nlogn).
if u need a hint, this qn is in cormen in the chapter of augumenting trees. i cudnt figure it
out, n mujhe irritation ho rahi hai
Adi
7/28/2006 1:23 AM

I don have Cormen but I have thot something.. But I have no idea about the time
complexity !!
for(i=1;i<n;i++)
for(j=i+1;j<n+1;j++)
{
if(one of the 2 chords is vertical or horizontal)
{ we can easily compare x or y values respectively to find if they are intersecting; break;
}
Find the chord with max y coord;
Let that chord be named a and the other b;
If(a.lowery is greater than b.highery)
{ Non-int;}
Else If(a.lowery is less than b.lowery)
{ Int;}
Else
// a.lowery is between b.highery and b.lowery
{
Analyse b; // See its y coords and then see if x coords inc with y or decrease
Check a and see if it follows the same pattern-> If it doesn't then its intersecting;
}
}
I have written English as its easier to understand and in this case it can be easily
converted into code. Also you can understand it by making diagrams of the last case.
P.S: If the solution is very stupid , please dont laugh at it and kindly tell me why it's
stupid as I am kinda beginner at this ! :)
P.S 2 :Also if by chance its correct , please temme the time complexity.I have a feeling its
O(nlogn) only ;)
Kartik
27

7/28/2006 4:30 AM

Adi
u r taking two chords and comparing them. thats the straighforward way, n the simplest,
but its complexity is not O(nlogn) but is O(n^2) since u have two loops and r comparing
each possible pair.
Adi
7/28/2006 5:59 AM

Hmm.. yeah.. First I think i need to search for some code which has O(nlogn) complexity
so that I can figure out how 'log n' came !
saurabh! taylor
7/28/2006 6:00 AM

@ kartik
keep the good work!
i don't have corman but can we devise a mechanism through which for two given points
on the circle we can find pair of points one to left and to right of the two points taken....
then we can device a tree sure, but to find the points is the point .........
Nitin
7/28/2006 9:19 AM

hi i have a solution, but fail to implement it.


logic: we can make a tree acc. to the angles made by them( 0(nlogn) ). then searching for
individual element:-for the end point say first or second that exist btw end points of any
other chords, if no such end point exist then we move to other points,complexity i think is
0(nlogn)
the structure of node can be like:
struct point
{
int x, y;
};
struct node
{
struct node *left, *right;
struct point first,second;
float angle;
};
then angle can be found using tan((first.y-second.y)/(first.x-second.x))
but couldn't implement how to check for search condn somebody help.
Kartik
7/28/2006 10:03 AM

@ nitin. i dont understand how calculating the angle will help in any way.maybe it might,
but how is the question. if u r gonna make the tree according to the angle, then to find
intersections u'll have to look at all nodes anyways becoz a chord of any angle can
intersect the chords of any angle.
anyways, the only way one can divide the chords in two groups is, that if two chords A
and B do not intersect, then B is either on the left of A or the right of A. that way we can

28

construct a tree. chords on one side of the tree wont intersect chords on the other side. but
the problem comes, if a chord intersects A, then it can intersect chords from both sides,
so we dont kno where it'll go.
Kartik
7/28/2006 10:05 AM

n adi, try out quick sort, merge sort, heap sort, binary tree sort
Adi
7/28/2006 11:25 AM

@kartik-Yeah man, had found a good article about complexities..


yahoo problem..
In 1000 wine bottles stack 10 are poisoned.. given 10 rats what is the minimum number
of tries to find the poisoned one. Rat dies once it licks the poisoned wine.
i am not able to find a better algo than brute force...
Rudhir
7/26/2006 11:41 PM

ankit, do we hav to find all 10 bottles(silly quest.)...n wat do u mean by stacked!!!.


Rudhir
7/26/2006 11:42 PM

we hav to make the worst case close to average..


Anket
7/27/2006 1:44 AM

Pls clarify the problem further...


@nkit
7/27/2006 9:30 AM

between stack n 10 there is a gap...


i hv copied the problem as it from a placement site..
i also cant think of any good way of finding all 10 bottles
Printf trivia
Hi!
I encouneterd this very simple ques on some website...
what would be the output when we give the command
printf("%d");
well i ran it and the answer i am getting is 0
don't have a clue why is this...
can anyone explain...
Satyendra
7/21/2006 10:49 PM

when u dont specify required no of arguments then printf will use any garbage value for
that argument of that type and will show that.
shobit
7/21/2006 11:02 PM

29

BUT IT DOESN'T WORK FOR %f .WHY????????


and it shows 0 only not any other value
Manish
7/21/2006 11:44 PM

yeah stydendra even i thought the same..


but why is it using only 0 as grabage value!
Satyendra
7/21/2006 11:51 PM

@ALL
at my compu in gcc it is showing any arbitrary value other than zero also and for any case
either %f or %d
Jagdeep
7/22/2006 12:28 PM

I thinks
i thinks it is very much compiler specific?
I dependes how compiler reactes when it encounters such cases.
saala mai to
7/25/2006 2:45 AM

well, for this ritchie says:


for characters and integers, printf prints a garbage value if value of parameter is not
mentioned.. For all other data types, it gives an error message.
For eg:
printf("%d %c");
wud give garbage values for both. garbage values depend on the compiler.
but printf("%f");
or printf("%lf");
would give errors.
Vipin
7/26/2006 1:36 PM

Ya Jagdeep is right.
Its a rule for C if %d is specified without any variable garbage value is returned. try wid
different compilers
almost complete binary tree
could anybody pls provide the code for proving whether the tree is A.C.B tree or not??
Kartik
7/22/2006 2:20 PM

int isACBT(node *root)


{
int f=0;
Queue Q;

30

node *p=root;
do
{
if (p==NULL) return 1;
if (f==1 && (p.right!=NULL || p.left!=NULL))
return 0;
if (f==0 && (p.right==NULL || p.left==NULL))
{
f=1;
if (p.left==NULL && p.right!=NULL)
return 0;
}
else if (f==0)
{
Q.insert(p.left);
Q.insert(p.right);
}
if (!Q.empty())
p=Q.remove();
else
return 1;
}
while(1);
}
Kartik
7/22/2006 2:22 PM

logic is : visit the nodes level by level(from left to right). if u get a node without 2
children, then set the flag. after the flag is set, no other node can have any child. if it does,
it isnt an ACBT. u can use the queue the way its used in breadth first traversal and
traverse the tree level by level.
Satyendra
7/23/2006 9:39 AM

int getheight(node*root)
{ if(root==NULL)
return -1;
return max(getheight(root->left),getheight(root->right))+1;
}
31

int isACA(node*root,int curh,int h,int allthere)


{ if(curh==h)
return h;
if(curh<h-1)
{ if(root==null||root->left==NULL||root->right==NULL)
return 0;
int v1=isACA(root->right,curh+1,h,allthere);
if(v1==0)
return 0;
int v2=isACA(root->left,curh+1,h,(v1==h)?1:0);
if(v2==0)
return 0;
return curh;
}
else
{ if(allthere==1)
{ if(root==NULL||root->left==NULL||root->right==NULL)
return 0;
return h;
}
else
{ if(root==NULL)
return 0;
if(root->right==NULL)
{ if(root->left==NULL)
return curh;
return curh+1;
}
if(root->left==NULL)
return 0;
return curh+1;
}
}
}
Satyendra
7/23/2006 9:40 AM

calls is cout<<!!isACA(root,0,height);
memory model questions
) char *someFun()
{
char *temp = string constant";
return temp;
}
int main()
{
puts(someFun());
32

}
Answer:
string constant
Explanation:
The program suffers no problem and gives the output correctly because the character
constants are stored in code/data area and not allocated in stack, so this doesnt lead to
dangling pointers.
could anyone tell me is the answer right
Satyendra
7/20/2006 6:47 AM

what i think.....
code data area to nahi pata mujhe but char*p="saty" is equivalent to char*p=new char[5];
and strcpy(p,"saty"); and new allocates memory from heap and heap bond hota hai bhai.
wo kuchh nahi chhodta jab tak khatam naa kar de yaa fir koi khatam naa kar de like.
delete p;//forced khaatma
runtime error."abnormal program termination" khatm kar diya
Kartik
7/20/2006 7:30 AM

i think, whenver u declare a string like "abcdefg" its stored statically. so there is no
problem.
nitin
7/20/2006 8:04 AM

@satyendra
char*p="saty" is equivalent to char*p=new char[5]; and strcpy(p,"saty");
is incorrect. They are completly different.
char* p = "saty" says;- p is pointing to address of "saty"[0] and if u do *p = 'p'; then
behaviour is undefined as specified by K&R
but allocating memory is altogether completely different issue. u can do what u want with
that block.
returning that is offence, if u try to call 2-3 function in between printing value and
retriving then the ans will be different.
Satyendra
7/23/2006 2:18 AM

@NITIN
main kuchh aur bolna chaahta thaa and i said sum thing else which is completely contrary
ry this but donn't use compiler to find o/p to te
this is one of the another question asked to me in microsoft interview.
#include <stdio.h>
int main()

33

{
int a=3, b = 5;

printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);


printf(&a["WHAT%c%c%c %c%c %c !\n"], 1["this"],
2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]);
return 0;
}
Kartik
7/19/2006 11:34 AM

OUTPUT :
Hello! how is this? super
That is C !
shobit
7/20/2006 8:02 AM

Kartik could u pls explain the solution


nitin
7/20/2006 8:08 AM

@shobit
it's very simple
char p[n] ;
and accessing i'th index value is equivalent to i[p], *(p+i), *(n+i), and p so just think in
that way
p is char so &p is char* which is required as first argument of printf()
simple.
Himanshu
7/20/2006 11:36 PM

could anyone plz explain the funda behind using &a......


and how is it working.......
plz
Kartik
7/21/2006 2:20 AM

lemme explain
whenver u write "abcdefg", the value of this expression is the address of the first
character of the string. lets say it is str.
therefore, this expression is like writing a strings name.
now a[str] is equivalent to str[a].
n str[a] is the character at the position a in the string. therefore 1["this"] is the character at
position 1 in the string "this", i.e. 'h'.
also &str[a] wud be the address of the character at position a. therefore in
34

&b["junk/super"], where b=5, the address will be the address of the charcter at position 5,
i.e. the address of 's'.
so, %s will print the string starting from 's' till the end of the string, n hence prints
"super".
i hope its clear now.
kaustubh
7/21/2006 8:05 AM

well kartik!even 5[abcdefgh] will give f as o/p.then why use & operator
Kartik
7/21/2006 10:32 AM

yaar, with the use of &, it is treated as a string n not a single character, n hence the whole
string after f will be printed in ur case, i.e. "fgh"
shobit
7/21/2006 10:32 AM

thanks a lot Kartik


logic and code to traverse binary tree
logic and code to traverse binary tree in post-order using stack non-recursively
Satyendra
7/20/2006 7:33 AM

arre.. koi iska bhi to soln to post karo nahi to main apna post karoon as i dont wanna
leave questions unanswered
nitin
7/20/2006 8:13 AM

logic:
post order is LDR so first push left till null ,push right till null and then print data and thn
pop last pointer saved
loop till !empty(stack)
code: will post soon , running short of time
Satyendra
7/21/2006 1:16 AM

void postorder(node*root)
{ stack st;
node*ptr=root;
while(!st.empty()||ptr!=NULL)
{ int here=0;
while(ptr!=NULL)
{ st.push(ptr);
ptr=ptr->left;
here=1;
}
if(!st.empty()&&here==1)
{ ptr=st.top();
ptr=ptr->right;
}
else if(!st.empty()&&!here)
35

{ ptr=st.pop();
cout<<ptr->info;
while(!st.empty()&&st.top()->right==ptr)
{ ptr=st.pop();
cout<<ptr->info;
}
if(!st.empty())
{ ptr=st.top();
ptr=ptr->right;
}
else
break;
}
}
}
Q.23 -> Memory Allocation
hi to all..,
can anyone tell me in detail what...
char *ptr ;
ptr = (char *)malloc(0) ;
does??
wat malloc(0) does?
will it allocate memory or not is my question
similar doubt with
int*p=new int[0];
int arr[0];
kaustubh
7/16/2006 10:15 AM

malloc returns NULL when it fails to allocate memory.in this case since size of memory
area being allocated is 0 bytes,thus malloc returns a NULL value to ptr.if you print the
value of *p,it will give 0 as answer
Satyendra
7/16/2006 11:22 AM

@kaustubh
int main()
{ int*ptr=(int*)malloc(0);
cout<<ptr;
getch();
}

36

this code gav following output


0x3f38b0 in c++
Rudhir
7/16/2006 11:31 AM

if u give 0 as input to malloc still memory wiil be allocated because malloc works on
blocks of memory.
when u give x as argument it calculates how many blocks need to be given(block size can
b implementation dependant) by (x+block_size-1)/block_size + 1
so even if u give x=0 , 1 block will still be allocated.
Rudhir
7/16/2006 11:33 AM

int a[0] will obviously giv error as here compiler cant allocate memory for 0 size.
Rudhir
7/16/2006 11:41 AM

similar arguments can be made for new as for malloc


Satyendra
7/16/2006 12:35 PM

int a[0] dont give error neither


new int[0]
Rudhir
7/16/2006 9:08 PM

int a[0] gives error


- "cannot allocate an array of constan size 0"
Rudhir
7/16/2006 11:43 PM

I tried visualc, turboc and gcc.


gcc is giving no error though it is giving such results
int a(0);
- sizeof(a) = 0
- printing address for a.
so nothing can be deciphered from it.
but since there is no violation when we access the elemnts that r out of bound from array
e.g a(20) is completely valid for decl int a(2);
it can be infered that we can acces a(0) for decl int a(0) though a(0) is out of bound.
nothing concrete is infered though
nitin
7/18/2006 7:14 AM

@rudhir
hey i tried this on borland c++ and it gives null
what did u say about it?
#include<stdlib.h>

37

#include<stdio.h>
main()
{
int *ptr = (int*)malloc(0);
printf("\n%p",ptr);
getchar();
}
above all if we tried to access *ptr then access voilation at address 0x0000 is reported as
expected.
nitin
7/18/2006 7:24 AM

i tried it on turboc, gcc , cc on solaris buto/p is same NULL


donn know how u guys got address u should check ch version of turbo c ur using , mine
is 3.0
Rudhir
7/18/2006 11:08 PM

sorry for late reply..kinda busy these days..


i have tested on visualc, gcc, turboc ver 3.0 and they r giving same results. they r
allocating space.
Rudhir
7/18/2006 11:12 PM

yaar logically it should allocate space(the reason i gave in my prev post)...


kaustubh
7/19/2006 7:06 AM

well satyendra! when i tried this code on turboc NULL was indeed printed.also i had read
in one of kanetkar's book that malloc returns NULL when it fails to allocate
memory.hence came the conclusion.
char *ptr ;
ptr = (char *)malloc(0) ;
if(ptr==NULL)
printf("NULL");
can't say anything abt c++ compiler
Satyendra
7/19/2006 7:13 AM

i tried it on gcc and it showed sum memory address and not NULL.
Satyendra
7/19/2006 7:15 AM

waise turboc me kaafi kuchh hota hai jo gcc me nahi hota .


for eg
for char*p="test";
p[1]='g';
printf("%s",p);
38

this code on turboc sharafat se printed "tgst" but on gcc it gav runtime error as mentioned
in ritchie so we generally take ritchie as standard one.
nitin
7/19/2006 9:13 AM

@rudhir
if u try using the shift-f1 to go to help of turbo and search for malloc it clearly says null is
returned if malloc fails or given size is 0.
i donn know how u r able to obtain address
calculate 400!
calculate factorial of nos till 300! or even 400!
Kartik
7/18/2006 4:07 AM

#define MAX_DIGITS 10000


int NextZ(int *Num)
{
return !(Num(0) || Num(1) || Num(2));
}
int mult(int *Num, int n, int *Ov)
{
int t=Num(0)*n+Ov(0);
Ov(0)=(t%100)/10 + Ov(1);
Ov(1)=(t%1000)/100 + Ov(2);
Ov(2)=t/1000;
Num(0)=t%10;
return 1;
}

main()
{
clrscr();
int len=4,n,m=2,i=0,f,Ov(3)={0};
int A(MAX_DIGITS)={0};
scanf("%d",&n);
A(0)=1;

39

while(m<=n)
{
i=0;
do
{
f=mult(&A(i),m,Ov);
i++;
}
while(i<=len);
len=i;
while(!NextZ(&A(len++)));
m++;
}
i=len;
printf("\n\t");
f=0;
while(i>=0)
{
if (f==0 && A(i)==0)
{i--; continue;}
else if (f==0 && A(i)!=0)
f=1;
printf("%d",A(i--));
}
//double k = 1;
//for(double d=2; d<=n; d++)
//k*=d;
//printf("\n\t%lf\n",k);
getch();
}
Kartik
7/18/2006 4:10 AM

this is a program i wrote. it works till all 3 digit no.s. it can be expanded easily for even
larger no.s.
u can try this program on ur comp. u'll have to replace the '(' and ')' in arrays with '[' and
']' ofcourse. i tested it for upto 170! by comparing it with the double k (in comments). i
suppose it will give the right answer for all no.s uptill 999 atleast.
Kartik
7/18/2006 4:17 AM

40

my funda - store each digit as a int. when multiplying, multiply each digit starting from
the lowest and store the carries in the array Ov(). keep doing it for the whole length of the
array.(i found it difficult to maintain the proper length of the array. len always exceeds
the actual length here).
i bet the code cud be made more efficient, and space can propably be saved too, firstly by
declaring A as a char array which i didnt do (i dunno y ). we can also probably store
two digits per element. or maybe there is a better algo possible ?
Satyendra
7/18/2006 5:14 AM

i tried uor code with mine and uor code worked till 270!+ but after that our codes answers
r not matching for 280!+. i dunno who is correct.
may if there is some range kaa pangaa with u or mine one i dunno
Satyendra
7/18/2006 5:15 AM

but i m pretty sure that everything is fine with mine one and so u wud too with uor
code .
dunno how to verify.
Satyendra
7/18/2006 5:24 AM

@ KARTIK
uor ans of 300! is not matching microsoft scientific calculator's answer

for most most

significant digits. see to it


nitin
7/18/2006 6:48 AM

Cann't we employ long double??


hey i tried using long double it give me same ans, as given by MS calc
#include<stdio.h>
void main()
{
printf("\n%Lf",fact(300) );
getchar();
}
long double fact(int n)
{
int i;
long double d =1;
for( i=1 ; i<=n ; i++)
{
d *= i;
}

41

return d;
}
Satyendra
7/18/2006 6:53 AM

@nitin
we r asking here for all digits of factorial and not exponential notation
as for 300! uors will giv [n]e[f] in exponential notation but we want ans with all digits

nitin
7/18/2006 6:54 AM

hey it's giving correct o/p even with 999!


excactly same as with MS calc only last 6 digit precession is lost which i think is not of
concern if ans is like e+2524.
if accurate ans is required we implement linked list for very long reprsentation. then it's
siple implementation as given in tenenbaum
above code will work even for 1000! and i hav made sum changes so that it goes with the
flow of logic and many redundant string objects can be removed to give more effective
space utilisation but will decrease clarity so i let it be there
Kartik
7/18/2006 9:06 AM

yaar, my code was faulty. like i told u, i am not able to maintain the length of the string
properly, n hence it give an error.
replace :
len=i;
while(!NextZ(&A(len++)));
with len=i+2;
n we'll get the correct result. but the length stored exceeds the actual length considerably
now, so is a little inefficient.
NO BIRTHDAY
7/18/2006 9:09 AM

k thats boundary cases i think.


logic is more imp so u did well
efficient algo for
sort the array by the no. of occurences and in case of clash the no. preceding in the
original array should precede .
2,2,3,2,1,4,4,3,2,6,7,7
output: 1,6,3,4,7,2
tell the complexity involved!
42

ms interview ( iit chennai)


NO BIRTHDAY
7/18/2006 8:53 AM

array = {2,2,3,2,1,4,4,3,2,6,7,7}
index array={0,1,2,3,4,5,6,7,8,9,10,11}
1.now sort the array "array" and according swap index array values
array = {1,2,2,2,2,3,3,4,4,6,7,7}
index array={4,0,1,3,8,2,7,5,6,9,10,11}
2.create freq array having freq,now index array having min index for that value
array = {1,2,2,2,2,3,3,4,4,6,7,7}
index array={4,0,0,3,3,2,2,5,5,9,10,10}
freq array= {1,4,4,4,4,2,2,2,2,1,2,2}
3.now sort freq array and breaking ties with comparing values to index array so new
values are
freq array= {1,1,2,2,2,2,2,2,4,4,4,4}
index array={4,9,2,2,5,5,10,10,0,0,3,3}
array = {1,6,3,3,4,4,7,7,2,2,2,2}
4. now for array "array" remove duplicate values to get
array = {1,6,3,4,7,2}
T(n)=O(nlgn)(step 1)+O(n)(step 2)+O(nlgn)(step 3)+O(n)(step4)
so T(n)=O(nlgn)
space complexity=O(n)
Q.22 -> Linklist question
Explain how to implement doubly linked lists using only one pointer value np[x] per item
instead of the usual two (next and prev). Assume that all pointer values can be interpreted
as
k-bit integers, and define np[x] to be np[x] = next[x] XOR prev[x], the k-bit "exclusiveor" of
next[x] and prev[x]. (The value NIL is represented by 0.) Be sure to describe what
information
is needed to access the head of the list. Show how to implement the SEARCH, INSERT,
and
DELETE operations on such a list. Also show how to reverse such a list in O(1) time
Rudhir
7/16/2006 11:37 AM

search()
{
for(p = head,q = 0;p != some_node;temp=q,q=p,p = p XOR temp);
}
43

Insert()
{
q = new node;
q->next = 0 XOR head;
head->next=q XOR head->next;
head = q;
}

delete()
{
q = head->next XOR head ;
q->next = q->next XOR head;
head = q;
}
i dont think that arbitrary insertion or deletion is possible so i provided code for deleting
and inserting at head only.
To access head...head pointer is necessary
if we have a tail pointer then just swapping head and tail reverses the list time O(1).
Kartik
7/17/2006 1:44 AM

void insert(node *newnode, int pos)


{
node *prev, *curr, *next;
curr=head;
prev=NULL;
next=curr->np;
if (pos==1)
head=newnode;
while(pos>1 && next!=NULL)
{
prev=curr;
curr=next;
next=next->np^prev;
pos--;
}
if (pos==1)
{
newnode->np=curr^prev;
curr->np^=prev^newnode;
44

if (prev!=NULL)
prev->np^=curr^newnode;
}
else if (pos==2)
{
curr->np=prev^newnode;
newnode->np=curr;
}
else
{
printf("Exceeded linst length");
}
}
void delete(int pos)
{
node *prev, *curr, *next;
curr=head;
prev=NULL;
next=curr->np;
if (pos==1)
head=newnode;
while(pos>1)
{
prev=curr;
curr=next;
next=next->np^prev;
pos--;
}
if (pos>1)
{
printf("Exceeded list length");
}
else
{
newnode->np=curr->np;
if (prev!=NULL)
prev->np^=curr^newnode;
next->np^=curr^newnode;
free(curr);
}
}

45

Insertion and deletion is possible at any location rudhir. I hope i am right this time
C memory model
can somebody please explain C Memory Model
this ques. is generally asked by microsoft and google every time in campus interview, as
told by seniors.
Rudhir
7/16/2006 12:10 AM

if i am wrong please get me to right track.


I think memory model depends on processor..
and there r two segments code and data and two address spaces for each one of them..far
and near....
Rudhir
7/16/2006 12:13 AM

...and there is a huge tooo


tushant
7/16/2006 3:10 AM

ya rudhir said it right i think


on intel 8086 processors there are 2 diffrent ways of storing an adddress, near and far . A
near address requires 16 bits of storage whereas a far address requires 32 bits of storage.
far address is constructed from the sum of a 16 bit segment number and a 16 bit offset.
based on the data objects and the code objects there are 5 differnt memory models
small- near addresses are used for both data objects and code objects (functions). The
data and code spaces are thus restricted to 64 KB each.
medium-Near addresses are used for data but far addresses are used for code.
compact-Far addresses are used for data but near addresses are used for code
large-Far addresses are used for both data and code
hugelarge and compact models calculate addresses within data objects by adding a near offset
to the base address of the object. So data object can only be of 64KB. This restriction is
relaxed in the huge memory model which is otherwise similar to the large model.
Rudhir
7/16/2006 3:12 AM

well.. i forgot abt turboc which has small and large memory models.
so i think in small mem model only near pointers r there while in large far and huge r also

46

there.
nitin
7/16/2006 6:46 AM

u all are correct guys but actually these all are the memory model followed by turbo c
compiler they are divided as:
1. tiny:- implemented by .com or .bat file
2. small :- addressing is done such that 128k is divided into data nd code.
3. medium:- where code segment > 64k but data is less
4. compact:- code is restricted to one segment but data can take several segment
5. large:- code and data for multiple segment but individual size of element is < 64k
6. huge :- does't suffer from wrap around problem , same as large but individual elements
can be > 64k
this is all i know,
what my intention was:-when variable are assigned globally they are in heap or data segment or somewhere else?
what actually goes to code segment:- code of our .obj file or something else?
what excatally is heap??
generally all this covers the compiler and processor independent part of memory model
followed by c.
Rudhir
7/16/2006 12:01 PM

global and static variables r given space in data segment.


code segment contains the code that machine can understand so it may be obj file but not
necessary (becoz obj files contains linking info also).
what is heap?
thats tricky..u can say that when we allocate memory at run time the address space of the
process changes to incorporate the new address added of free space. so heap is a pool of
free space that machine can provide. which segment gets affected i dont know..
a google question
This is the question asked by google in my telephony interview:Given two arrays A and B.
A has integers unsorted.
B has the same length as A and its values are in the set {-1,0,1}
you have to return an array C with the following processing on A.
if B has 0 then C must have A

47

if B has -1 then A must be in C within the sub-array C[0] - C[i-1] ie. left subarray
if B has 1 then A must be in C within the sub array C[i+1] - C[length(A)] ie right
subarray.
If no such solution exists then printf("no solution");
I thought their must be something related to trees as of sets valus given {-1,0,1} : 0 for
leaf, -1 for left child and 1 for right one.
but what happen if all b are -1, 0 or 1 individually.
please explain the logic first than code My eyes fails to understand code without proper
comments.
NO BIRTHDAY
7/15/2006 1:05 PM

i hav thought of sumthing. lets see whether it works or not.


in uor array B, divide it into regions(+ve regions and -ve regions).
ignoring 0 values as they dont affect solution.
so if array B={ 0,0,1,1,-1,1,-1,-1,-1,1,1,0,0,-1};
then ignoring 0 values this arrays has (2,3)+ve region (4,4) -ve region
(5,5) +ve region (6,8) -ve region (9,10) +ve region (13,13) -ve region.
here (c,d) means region from b(c) -> b(d) c & d r indexes.
now see that for a solution to exist.
1st region in array shud be +ve region ignoring 0s and 2nd region shud be -ve region so
as to hav scope of satisfying condition given in q.
so basically +ve and -ve region shud alternate and 1st region shud be +ve and last region
shud be -ve.
if 1st region is not +ve but is -ve then there wont be any scope of these -ve region to hav
their element in array before thir index.
similar reasoning applies with last -ve region.
So, in this way u can logically figure out that whether soln exists or not.
NO BIRTHDAY
7/15/2006 1:16 PM

#include<iostream>
#include<vector>
using namespace std;
vector<int> soln(vector<int>a,vector<int>b)
{ vector<int>c;
int first=-1,last=-1;
for(int i=0;i<b.size();i++)
if(!b(i))
{ if(first==-1)
48

first=i;
if(first!=-1)
last=i;
}
if(last==-1||b(first)==-1||b(first)==b(last))
return c; //empty vector indicating error
vector<int>temp(a.size());
c=a;
for(int i=0;i<b.size();i++)
if(b(i)==0)
c(i)=a(i);
else if(b(i)==-1)
{ c(first)=a(i);
while(!b(first))
first++;
}
for(int i=0;i<b.size();i++)
if(b(i)==1)
{ c(first)=a(i);
while(!b(first))
first++;
}
return c;
}
Kartik
7/15/2006 1:19 PM

int funcABC()
{
int i,j=0,k=n-1;
while(B(j)!=1)
j++;
for(i=0; i<len; i++)
{
if (B(i)==1)
{
continue;
}
else if (B==-1)
{
if (j>=i) return 0;
C(j)=A(i);
while(!B(j))
j++;
49

}
else
{
C(i)=A(i);
}
}
for(i=n-1; i>=j; i--)
{
if (k<j) return 0;
if (B(i)=1)
{
if (k<=i) return 0;
C(k)=A(i);
while(!B(k))
k--;
}
}
}
hmm, this is my code. its not tested, n not in the correct format, but the logic is right i
think.
Kartik
7/15/2006 1:19 PM

lemme explain. satyendra is right.


sabse pehle after a string of zeroes, 1 aana chahiye, n in the end, -1 aana chahiye.
otherwise the array cannot be created.
my logic to create the array is, use three counters, i, j and k.
i is used to scan the array one by one.
j initially points to the first 1.
when B(i)=0, then A(i) is copied onto C(i).
if B(i) is -1, then A(i) is copied onto C(j). then j is incremented to the next non zero
position.
if j is greater or equal to i, then the array cannot be created.
the scanning is completed. unless the first non zero value is -1, it wont have any problem.
now the array is scanned backwards. all elements before j have been filled.
k points to the first -1 from the end.
i goes form n-1 to j
same thing, if we get a 1, then A(i) is copied into C(k) and k then is made to point to the
50

next non zero value.


Rudhir
7/15/2006 11:57 PM

Consider my algoremv all 0's from view


there will be no sol when- -1 is frst elemnt
- 1 is last elemnt
- there r all 1 or -1's
now the sol exists1) traverse the B array from start
2) stop at first -1.
3) exchange this(-1) with the first 1 u seen, now put 0 in first 1's position(in B array) and
put 1 in current -1's position.
4) do this till u get at the end.
5) now traverse the array from end.
6) exchange elemnts with adjacent 1's.
at the end all will be in correct position.
i had run this algo on paper on various input and it seems to give the right answer.
this algo can be very easily coded.
Please reply with ur view on this.
Rudhir
7/16/2006 3:23 AM

for example
B-> 1 -1 1 1 -1 -1
C-> A B C D E F

exchange A and B
0 1 1 1 -1 -1
BACDEF

51

exchange A and E
0 0 1 1 1 -1
BECDAF
echange F and C
000111
BEFDAC
now traverse frm rht end
exchange A and C
000110
BEFDCA
exchange D and C
000100
BEFCDA
and thats the answer
Kartik
7/16/2006 3:56 AM

i think it shud be BEFACD


BEFCDA is an incorret soln
NO BIRTHDAY
7/16/2006 4:41 AM

BEFACD
my soln will giv this as ans which is also correct
Rudhir
7/16/2006 8:41 AM

@kartik
could u please explain why my answer is WRONG....
Question #21 [subarray sum = k]
You are given an array containing negative or positive numbers in unsorted way. You
have to find a subarray whose sum is a given value k.
[Though this problem is easy but this was recently asked in Microsoft interview. So
everybody should try it]
meet ashish
7/16/2006 8:04 AM

reply ....
i hvnt coded it bt i guess logic shld be correct ...
1)maintain a recursive function taking array as input ...
52

2)at each recursion it has decision either to take or not ...


3)from each recursion two recursive call are made first as making decison to take it and
scond as decision not to take it ...as soon as sum is k ...return the i and j value of array ..
i guess dis shld work ...if there is any beter solution ....plz reply
NO BIRTHDAY
7/16/2006 8:17 AM

void subarray(vector<int>a,int k,int&st,int&en)


{ int sum=a[0];
st=-1,en=-1;
int start=0,end=0;
if(sum==k)
{ st=start;
en=end;
}
for(int i=1;<a.size();i++)
{ if(a(i)>k)
{ sum=a(i);
start=i;
end=i;
}
else if(sum+a(i)>k)
{ while(sum+a(i)>k&&start!=i)
sum=sum-a(start++);
sum+=a(i);
end=i;
}
else
{ sum+=a(i);
end++;
}
if(sum==k)
{ st=start;
en=end;
break;
}
}
}//here st contains starting index and en contains end index of sub-array
Rudhir
7/16/2006 8:29 AM

void sum_k(int a[],int n,int k)


{
int i=0,j=0,start=0,end=0,sum=0;
for(;i<n;i++)
{

53

if(a(i)==k)
{
break;
}
sum+=a(i);
if(sum==k)
{
end = i;
break;
}
else
{
if(sum>k) // if sum > k then increase the start but dont increse i
{
sum=sum-a(start); // remv start
start = start+1; // increse start
sum-=a(i); // remv current elemnt so that it is not counted twice in next iteration
i--; // don't increase i
}
}
}
}
pointer to auto variables
hi friends it's said that auto variables are lost as soon as we encounter the right curly
braces of function, but here is code which proves it wrong:
int* fun()
{
int var = 10;
int *iptr = &var;
return iptr;
}
void main()
{
int *i = fun();
printf("%d",*i);
}
now we are able to print 10!! that means the memory allocated to auto variable, on stack,
is not lost after return, not even that, without iptr returning &var has same result
can anybody please tell what is happining.
NO BIRTHDAY
7/15/2006 11:05 AM

54

lost here doesnot mean that memory is lost.


it means that memory location previously assigned to auto variable becomes free after its
scope ends and can be used by OS again for sum diff. purpose like assigning to sum other
auto var or like that. so basically contents r not lost but its only an indication to OS that
that auto var scope is over and mem is free for REUSE.
nitin
7/15/2006 11:25 AM

@rudhir
yha that is what i mean by lost, but i read in bjarne and kernighan that returning pointer to
auto variable is not illegal but logically incorrect and result is undefined, but i run it on 3
os: Windows, Linux, Solaris ans 7 compilers all giving same result!!!
NO BIRTHDAY
7/15/2006 11:32 AM

@nitin
1st of all i m not rudhir
2ndly its incorrect as result is undefined but its working on compilers as OS may be
managing memory freed by stack as FIFO so that memory which was released very early
is utilized for current purpose. and yes data in memory is not destroyed as changing data
values wont provide anything as the thing that is need by OS is that its free thats it.
But even if memory is not managed by FIFO then also if that is assigned to sum other
auto var then data of old var might hav been there due to aforesaid reason. and i no this
much only as far as memory management is concerned.
nitin
7/16/2006 6:52 AM

sorry yar , actually i running short of time just type @ and did saw the name and put enter
the last typed name came.
floating point
here is one question:
void main()
{
float f, *fptr;
printf("\nEnter float");
scanf("%f",&f);
fptr = &f;
int *iptr = (int*)fptr;
printf("%d",*iptr);
}

55

cn u people please how the bit extraction will be carried out when int* will try to read
data from float,
please explain for both cases: sizeof(int) =2 bytes and 4 bytes.
NO BIRTHDAY
7/15/2006 11:01 AM

here suppose f is allocated 4 byte memory with location no 100,101,102,103.so


fptr(pointer) will contain 100 as its contents. when u will assign fptr to iptr thru casting
then iptr will also contain 100.
now when u use %d it will take 1st 2 memory location namely 100,101 and use them to
produce an integer value for sizeint=2
for size=4 it will read 100,101,102,103 and will use data there to create an integere value.
actually float uses 3 byte for mantissa and 1 byte for exponent i think thats why %f and
%d will giv diff. answer as both of them will interpret those locations differently.

nitin
7/15/2006 11:29 AM

yes this is what i think and i convert the numbers to binary representation and found no
permutation of how the iptr fetch the data??
even from the tenenbaum 1.1 (page: starting 4-5 of chap1) show internal representation of
floats but taking that as examples donn't give correct result.
NO BIRTHDAY
7/15/2006 1:18 PM

sorry for GCC and turboc as intel is shayad big enidan meaning most significant byte
comes later so accordingly dekh lo
Rudhir
7/15/2006 10:11 PM

Intel is small endian


NO BIRTHDAY
7/15/2006 10:36 PM

this code will giv u sum insight into how memory is represnted and shows that most
significant byte come later and least significant byte come earlier.
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<vector>
using namespace std;
#include<conio.h>
template <class T>
string showbits(T f)
{
int n=sizeof(T);
unsigned char*t=(unsigned char*)&f;
56

t=t+(n-1);
//t=t-4;
unsigned char temp=1<<7;
string str="";
for(int j=0;j<n;j++)
{ temp=1<<7;
for(int i=0;i<8;i++)
{ unsigned char ch=(((*t)&temp)>>(7-i))+'0';
//cout<<ch<<"here";
str+=ch;
temp=temp>>1;
}
t--;
}
return str;
}
int main()
{ int a=128*128*8,b=128*128*16,c=128*128*32,d=128*128*128;
cout<<showbits(a)<<"\n";
cout<<showbits(b)<<"\n";
cout<<showbits(c)<<"\n";
cout<<showbits(d)<<"\n";
getch();
}
NO BIRTHDAY
7/15/2006 11:35 PM

"Little Endian" means that the low-order byte of the number is stored in memory at the
lowest address, and the high-order byte at the highest address. (The little end comes first.)
For example, a 4 byte LongInt
Byte3 Byte2 Byte1 Byte0
will be arranged in memory as follows:
Base Address+0 Byte0
Base Address+1 Byte1
Base Address+2 Byte2
Base Address+3 Byte3

So intel is little endian as said by rudhir.


nitin
7/16/2006 6:50 AM

@rudhir
yes intel machine are low endian but even that i'm not able to get how int* fetch data

57

from float variable.


shivkumar sir where are u?? show us the way
Question #20 [linked list to tree]
Given a singly linked list, you have to make a minimally skewed Tree such that each
child points to its parent.
nitin
7/14/2006 4:59 AM

@rudhir
is their any boundation on time and space
NO BIRTHDAY
7/14/2006 10:39 AM

node* createtree(list*start)
{ if(head==NULL)
return NULL;
node*fast=start->next,*slow=start,*q=NULL;
while(fast!=NULL)
{ q=slow;
slow=slow->next;
fast=(fast->next==NULL)?NULL:((fast->next)->next);
}
if(q==NULL)
return start;
q->next=NULL;
q=createtree(start);
q->next=slow;
q=createtree(slow->next);
q->next=slow;
return slow;
}
time complexity=O(nlgn) as
T(n)=2*T(n/2)+O(n) approximately
Rudhir
7/15/2006 12:30 AM

complexity of my sol: O(nlogn)


Rudhir
7/15/2006 1:09 AM

list_to_tree(node list1, node rootp)


{
node p;
node q;
node root = list1;
if(list1->next==NULL)

58

{
list1->next = rootp;
return;
}
for(;root;root->next==NULL?break():root=root->next->next,q=p,p = p->next);
root = p,p = root->next;
if(q!=NULL)
q->next = NULL;

root->next = rootp;
list_to_tree(list1,root);
list_to_tree(list2,root);

}
kaustubh
7/15/2006 7:42 AM

modification to the problem


you are given a sorted linked list.how to convert it into a binary tree so that inorder
traversal of the tree will give the same output as the sorted linklist.please also mention
time complexity
Rudhir
7/15/2006 9:05 AM

my above provided sol was untested , here is fully tested version.


void list_to_tree(node list1, node rootp)
{
node p = list1;
node q=NULL,temp=NULL;
node root = list1;
if(list1==NULL)
return;
if(list1->next==NULL)
{
list1->next = rootp;
return;
}
for(;root;root->next==NULL?root=root->next:(root=root->next->next,q=p,p = p->next));

59

temp = p;
p = p->next;
if(q!=NULL)
q->next = NULL;

temp->next = rootp;
list_to_tree(list1,temp);
list_to_tree(p,temp);
}
ofcourse this tree makes the tree such that it produces sorted order. but the tree should be
modified to make it a binary tree
NO BIRTHDAY
7/15/2006 9:39 AM

soln for sorted linklist to norman binary search tree


class <template T>
struct treenode
{ treenode*left;
treenode*right;
T info;
};
class <template T>
treenode* createtree(list*start)
{ if(head==NULL)
return NULL;
node*fast=start->next,*slow=start,*q=NULL;
while(fast!=NULL)
{ q=slow;
slow=slow->next;
fast=(fast->next==NULL)?NULL:((fast->next)->next);
}
treenode*root=new treenode;
root->info=slow->info;
root->left=root->right=NULL;
if(q==NULL)
return root;
q->next=NULL;
treenode*leftchild=createtree(start);
treenode*rightchild=createtree(slow->next);
root->left=leftchild;
root->right=rightchild;
60

return root;
}
time complexity=O(nlgn) as
T(n)=2*T(n/2)+O(n) so by master theorem
T(n)=O(nlgn)
space complexity=O(n)
Rudhir
7/15/2006 10:04 PM

assuming we have a linked list in which we have rht and left pointers, initially the list is
linked with rht pointers and left is null.
node list_to_binary(node list1)
{
node p = list1;
node q=NULL,temp=NULL;
node root = list1;
if(list1==NULL)
return NULL;
if(list1->rht==NULL)
return list1;
for(;root;root->rht==NULL?root=root->rht:(root=root->rht->rht,q=p,p = p->rht));
temp = p; //temp is mid point
p = p->rht; // just next to mid
if(q!=NULL) // q is prev to mid
q->rht = NULL;

temp->left = list_to_binary(list1);
temp->rht = list_to_binary(p);
return temp;
}
Time - O(nlogn)
Code JAM
refer to http://felix-halim.net/story/gicj06/day2-2.php?prob=300
for 300 ptr prob
anyways i m pasting it here too but figure wont appear here.
NO BIRTHDAY
61

7/12/2006 11:33 AM

Vertex w is an ancestor of vertex v if w lies on the shortest path from the root to v.
Vertex w is a parent of vertex v if it is an ancestor of v and is directly connected to v. For
example, vertices 0, 2 and 4 are ancestors of vertex 0, and vertex 4 is a parent of vertex 0.
The lowest common ancestor (LCA) of vertices v and w is the common ancestor of v and
w which is located as far from the root as possible. For example, the LCA of vertices 1
and 3 is vertex 2, and the LCA of vertices 5 and 0 is vertex 4.
You will be given a String[] lca, with each element of lca being a space-separated list of
integers. The i-th integer in the j-th element of lca represents the LCA of vertices i and j
(all indices are 0-based). Using this information, you are to reconstruct the whole rooted
tree. Find parents for all the vertices and return them in a int[]. The i-th element of the
result must represent the parent of vertex i (use -1 for the parent of the root).
NO BIRTHDAY
7/12/2006 11:34 AM

Definition
Class: InverseLca
Method: getParents
Parameters: String[]
Returns: int[]
Method signature: int[] getParents(String[] lca)
(be sure your method is public)
Constraints
* lca will contain between 1 and 25 elements, inclusive.
* Each element of lca will contain between 1 and 50 characters, inclusive.
* Each element of lca will contain exactly K single space separated non-negative
integers, where K is the number of elements in lca.
* Each number in each element of lca will be between 0 and (K - 1) inclusive, where K is
the number of elements in lca.
* Each number in each element of lca will contain no leading zeroes.
* The i-th number in the i-th element of lca will be equal to i.
* The i-th number in the j-th element of lca will be equal to the j-th number in the i-th
element of lca.
* lca will represent a valid tree.
NO BIRTHDAY
7/12/2006 11:34 AM

Examples
0)
{"0 0 0",
"0 1 0",
"0 0 2"}
Returns: {-1, 0, 0 }
62

A simple tree with 3 vertices. Vertex 0 is the parent for both vertices 1 and 2.
1)
{"0 0 0",
"0 1 1",
"0 1 2"}
Returns: {-1, 0, 1 }
2)
{"0 2 2 2 4 4 2",
"2 1 2 2 2 2 6",
"2 2 2 2 2 2 2",
"2 2 2 3 2 2 2",
"4 2 2 2 4 4 2",
"4 2 2 2 4 5 2",
"2 6 2 2 2 2 6"}
Returns: {4, 6, -1, 2, 2, 4, 2 }
The example from the problem statement.
3)
{"0 0 0 0","0 1 0 1","0 0 2 0","0 1 0 3"}
Returns: {-1, 0, 0, 1 }
Rudhir
7/13/2006 2:22 AM

inverse()
{
int a[7][7] =
{{0,2,2,2,4,4,2},{2,1,2,2,2,2,6},{2,2,2,2,2,2,2},{2,2,2,3,2,2,2},{4,2,2,2,4,4,2},{4,2,2,2,4,
5,2},{2,6,2,2,2,2,6}};
int i,j,k,n=7;
static int res[7];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
continue;
if(a[j]==j)
{
for(k=0;k<n;k++)
{
if(k==i || k==j)
continue;

63

if(a[j][k]==j)
{
if(a[k]==k)
break;
}
}
if(k==n)
res = j;
}
}
}
for(i=0;i<n;i++)
printf("%d",res);
}
NO BIRTHDAY
7/13/2006 7:11 AM

@RUDHIR
there r many indexes which hav been removed by orkut like a(i)(j) -> a(j)
so it wil be better to do it like a(i)(j)
so that i can check uor code otherwise code is ambiguos.
NO BIRTHDAY
7/13/2006 7:15 AM

thats why its giving wrong result as i assumed sumthing for uor missing indexes
NO BIRTHDAY
7/13/2006 7:29 AM

also take care of initialization and root so that i can verify directly
Rudhir
7/13/2006 9:00 AM

inverseLCA()
{
int a(7)(7) =
{{0,2,2,2,4,4,2},{2,1,2,2,2,2,6},{2,2,2,2,2,2,2},{2,2,2,3,2,2,2},{4,2,2,2,4,4,2},{4,2,2,2,4,
5,2},{2,6,2,2,2,2,6}};
int i,j,k,n=7;
static int res(7); //initialise this with -1
for(i=0;i<n;i++)
res(i) = -1;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
64

if(i==j)
continue;
if(a(i)(j)==j)
{
for(k=0;k<n;k++)
{
if(k==i || k==j)
continue;
if(a(j)(k)==j)
{
if(a(i)(k)==k)
break;
}
}
if(k==n)
res(i) = j;
}
}
}
for(i=0;i<n;i++)
printf("%d",res(i));
}
hope this helps.
the program is tested with all examples.
NO BIRTHDAY
7/13/2006 10:42 AM

uor logic seems pretty much correct.


so gud work done
no of trees(question # 19)
can you find out no of distinct binary trees possible with n nodes (distinction is done on
the bases of the shape of the tree). for example node=1,tree=1
node=2,tree=2
node=3,tree=5
node=4,tree=14
try for both O(n) and O(1) solution
for O(1) i just need a formula.
Rudhir
7/12/2006 9:01 AM

65

its 1/(n+1)2n(C)n where c is combinations.


I dont know how it is derived.
NO BIRTHDAY
7/12/2006 11:18 AM

the only soln i can make is O(n*n)


int nooftrees(int n)
{ vector<int>soln(n+1);
soln[0]=1,soln[1]=1;
for(int i=2;i<=n;i++)
for(int j=0;j<i;j++)
soln(i)+=soln[j]*soln[i-j-1];
return soln[n];
}
tushant
7/12/2006 11:24 AM

ooops mujhse galti ho gayi dobara.


ya the formula is correct, but this is O(n) solution as it will take 0(n) time to calculate
2nCn.So i think 0(1) solution is not possible.
i too dont no exactly how it is derived , (i thought ki shayad koi kar dega) ,but now i have
made an attempt. please check this
suppose total no of trees of n nodes =T(n)
so we can derive recurrence relation as T(n)= E(r=1ton-1)T(r)T(n-r-1)
where "E" stands for summation
this recurrence can be easily understood using basic probability.
nitin
7/13/2006 12:10 AM

@rudhir
hi, are u sure about the formula coz i found it 2^n - n in one of the books of Y.Kanetkar,
but donn't remember book name, i found it on my note book.
if this formula is correct than we find solution in 0(log n).;)
Rudhir
7/13/2006 12:37 AM

@nitin
the formula i gave is from cormen. and i have seen in many other links.
Question #17
You are given a percentage value, n (0 <= n <= 100) and a number that indicates the
number of significant digits following the decimal point, d.
Your task is to determine the smallest sample that can give you the percentage value
within the required accuracy.
In other words, your task is to determine the smallest integral value of the denominator,
q, the value of p/q (where p is also an integer) is
equal to the percentage value upto the required number of decimal digits.
Rudhir
66

7/12/2006 5:48 AM

shall i give some example????????


Rudhir
7/12/2006 9:03 AM

if n=38.46 and d=2


return q = 13
question#18
you have been given array of size n containing elements (integers) from 0 to n only once
,so one integer is missing find that integer.
space -O(1)
time-O(n)
Nitin
7/12/2006 4:49 AM

*find sum of elements of array=sum1


*find sum of numbers from 0 to n =n*(n+1)/2=sum2
*missing element=sum2-sum1
tushant
7/12/2006 5:24 AM

ooops!! i forgot to tell 2 things you cannot use any arithmatic operator(except for the
loops variables) and you cannot directly access the elements of the array instead you have
a funtion which returns pth bit of the element A(i) in array
Rudhir
7/12/2006 5:37 AM

void missing_int(int a[],int n)


{
int temp=11,i,j;
for(i=0;i<32;i++)
{
int mask = 1;
for(j=0;j<n;j++)
{
temp^=((a[j]>>i)&mask)<<i;
}
}
// temp is no.
printf("%d",temp);
}
tushant
7/12/2006 6:07 AM

@rudhir
i didnt get y have you initialised the value of temp to 11 . and yaar your code is not
giving correct ans.
NO BIRTHDAY
7/12/2006 7:02 AM

67

int missing(int a[],int n)


{ int ans=0;
int mask=1;
for(int i=1;i<=n;i++)
ans=ans^i;
for(int j=0;j<32;j++)
{ for(int i=0;i<n;i++)
ans=ans^(a(i)&mask);
mask=mask<<1;
}
return ans;
}
tushant
7/12/2006 7:21 AM

ya satyendra's ans seems to be correct , i have just seen that a similar question (question 2
) is already posted.
Rudhir
7/12/2006 8:56 AM

in hurry i forgot to change my code.


temp is initialised with the xor of first n no.s. sorrrryyyy....

68

Anda mungkin juga menyukai