Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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
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
struct node
{
void *data ;
struct node *next ;
};
struct list
{
struct node *head, *tail ;
};
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
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
Shivkumar urachamp!
7/10/2006 10:11 AM
greaaaat solution!!!!!
7/11/2006 8:29 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
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
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
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
}
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
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
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
12
cin.get();
return 0;
}
time complexity is O(n) ...
Aamer
8/23/2006 10:02 AM
13
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
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.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
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
(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>
{
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
22
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
@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
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
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
@ 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
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
@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
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
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
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;
OUTPUT :
Hello! how is this? super
That is C !
shobit
7/20/2006 8:02 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
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
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
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
@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
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
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
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
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
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
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
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
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
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
#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
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
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
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
@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
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
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
@rudhir
yes intel machine are low endian but even that i'm not able to get how int* fetch data
57
@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
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
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
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
65
@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
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
@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
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
68