Microsoft Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
3
of 3 vote

O(logN) instead of O(N)

NodeType* getSecondMax(NodeType* root)
{
    if(root == NULL)
    {
         return NULL;
    }
    NodeType* pre = NULL;
    NodeType* max = root;
    while(max->r)
    {
        pre = max;
        max = max->r;
    }
    if(pre == NULL)
    {
        if(root->l == NULL)
        {
            return NULL;
        }
        else
        {
            return rightMostNode(root->l);
        }
    }
    else if(pre->l == NULL)
    {
         return pre;
    }
    else
    {
        return rightMostNode(pre);
    }
}

- wangxuyang October 08, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Use a inverted inorder tranversal.that is go to right child first instead of left child. recursively this can be obtained as follows: The most important issue that a global count must be used when considering recursive solution.

where n=2;

void NthMax(Node *root, int n){
if(root == NULL){
return;
}
max(root->right, n);
if(--n == 0){
cout<<"Number is: "<<root->value<<endl;
}
max(root->left, n);
}
}
}

- neeraj.goyal90 November 05, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

just do reverse inorder traversal, and return when count=2

- Andy July 10, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

did you meant post order traversal??

- Somebody July 10, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Find the max element by going right in O(lgn) time. Then find its predecessor.

- Kuldeep July 10, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

no, Anonymous coded what I was trying to say.

- Andy July 10, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

<pre lang="" line="1" title="CodeMonkey2475" class="run-this">
int count=0;
BNode sMax;
public BNode secondMax()
{
secondMax(root);
return sMax;
}

private void secondMax(BNode root)
{
if(root == null)
return;
else
{

secondMax(root.right);
count++;
if(count==2)
{
sMax = root;
return;
}
secondMax(root.left);
}

}



</pre><pre title="CodeMonkey2475" input="yes">to use,
1. place code into your BinaryTree class.
2. in the main() method, call the class by calling secondMax().

i.e. BNode node = secondMax();</pre>

- Anonymous July 10, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anonymous
Solution looks good but your code will visit all the nodes in the tree even if it found the second largest element much earlier.

- AK July 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

i think d line secondMax(root.left); is not required

- hoho July 10, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Is absolutely needed. Try to find out why.

- Anonymous July 11, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

can u pl give me an insertion sequence for which without the line secondMax(root.left) gives wrong output?

- hoho July 11, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It doesn't take much, the following is a tree that will fail if you just follow the right links.

10
       \
        20
        /
      15

- Developer August 16, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct bst * bst;
struct bst
{
    int ele;
    bst left;
    bst right;
};

bst root=NULL;
bst insert(bst root,int x)
{

    if(root==NULL)
    {
        root=(bst)malloc(sizeof(struct bst));
        root->ele=x;
        root->left=root->right=NULL;
    }
    else if(x<root->ele)
    {
        root->left=insert(root->left,x);
    }
    else
    root->right=insert(root->right,x);
    return root;
}
void inorder(bst root)
{
    if(root)
    {
        inorder(root->left);
        printf("%d ",root->ele);
        inorder(root->right);

    }

}
int max(bst root)
{
    if(root->right==NULL)
    return root->ele;
    else
    return max(root->right);


}
int secondlargest(bst root)
{
    if(root->right==NULL)
    return max(root->left);
    if(root->right&&root->right->right==NULL&&root->right->left==NULL)//checking if right child is leaf node or not
    return root->ele;
    else
    return secondlargest(root->right);
}
int main()
{
    int x;
    int i=0;
    for(;i<6;i++)
    {
        scanf("%d",&x);
        root=insert(root,x);
    }
    //inorder(root);
    printf("\n%d\n",secondlargest(root));
    return 0;
}

- pinku July 11, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1) O(lg N)
- Find maximum O(lg N)
- Find predecessor O(lg N)

2) You could also use in-order traversation. But this would be O(N).

- max July 11, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

first method costs O(n) too in worst case. What if tree is skewed to right, i.e. height = n-1.

- anon July 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Use AVL, or RB tree. In real programs we usually use some kind of balanced bs tree.

- max July 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int secondMaxInBST(node* root)
{
    int max=0, secondMax=0;
    getSecondMaxInBST(root,max,secondMax);
    return secondMax;
}
void getSecondMaxInBST(node* root, int& max, int& secondMax)
{
    if(root)
    {
        getSecondMaxInBST(root->left, max, secondMax);
        secondMax=max;
        max=root->data;
        getSecondMaxInBST(root->right, max, secondMax);
    }
}

- socrates July 12, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

nice...

- Anonymous July 12, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

What if there are duplicates? In that case max and secondMax could be duplicates!

- Anonymous July 14, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anonymous
Good point. In case of duplicates we can have following three implementation of BST:
1. Each node contains a count variable. So when there is a duplicate value then no need to add new node just increase count.
2. Add new node at right.
3. Add new node at left.

Above implementation works correctly for 1 but need to add check

if(secondMax < max) 
           seconMax=max;

to work with 2 and 3.

- Socrates July 14, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

node *secondmax(node *root)
{
node* par;
node* right;
if (root==NULL)
{
return(0);
}
par=root;
if(root->rchild==NULL)
return(root);
else
right=root->rchild;
while(par->rchild->rchild!=NULL)
{
par=par->rchild;
right=right->rchild;
}
return(par)
}

- Anonymous July 13, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int secondmax(struct node *r)
{
int x;
static int count=0;
if(!r)
return INT_MIN;
x=secondmax(r->right);
if(x!=INT_MIN)
return x;
count++;
if(count==2)
return (r->info);
x=secondmax(r->left);
}}

- geeks July 13, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

can't it be that simple ?
from root go to right most child.
traverse to rightmost to the left sibling of this right most child (if any) else return value of parent.

- mrn July 13, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's the pseudo-code for my approach

Node Helper(node)
  if(node is leaf)
    return null
  else if(only left subtree exists)
    return FindMax(root->left)
  else
    tempNode = helper(root->right)
    if(tempNode is null)
      return node
    else return node

Node Find2ndLargest(root)
  if(root is null)
    error()
  node = Helper(root)
  if(node is null)
    error()
  else return node

I Guess its easy to write the FindMax(node) function, so i'll not write it here. In case of a balanced BST, this should have a complexity of O(log(N))

- Kaustubh July 13, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about this one?
Node secondMax(Node root) {
While (root != NULL) {
Node right = root.getRight();
If (right != NULL && right.getRight() == NULL)return root;
Root = right;
}
}

- Anonymous July 14, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This version corrected a small error.
Node secondMax(Node root) {
While (root != NULL) {
Node right = root.getRight();
If (right != NULL && right.getRight() == NULL)return root;
Root = right;
}
Return NULL;
}

- rw July 14, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

this is different::::
#include<stdio.h>
#include <conio.h>
#include<malloc.h>
#include<ctype.h>
struct node{
int data;
struct node* lchild;
struct node* rchild;
}*root;
int inorder(struct node* ptr){
int j;
static int i=0,a=0;
if(root->lchild == NULL && root->rchild == NULL)
{
printf("\nonly largest or ");
return root->data;
}
if(ptr){
inorder(ptr->lchild);
i++;
if(i==2)
a=ptr->data;
inorder(ptr->rchild);
}
return a;
}
struct node * makenode()
{
struct node * root;
int data;
printf("\n Enter the node data : ");
scanf("%d",&data);
root = (struct node *) malloc (sizeof(struct node));
root->data=data;
root->lchild=NULL;
root->rchild=NULL;
return (root);
}
void maketree(struct node * root)
{
char ans;
printf("\n Do you want to create the left subtree of %d (y/n)? ",root->data);
fflush(stdin);
ans=toupper(getche());
if (ans=='Y')
{
root->lchild=makenode();
maketree(root->lchild);
}
printf("\n Do you want to create the Right subtree %d (y/n)? ",root->data );
fflush(stdin);
ans=toupper(getche());
if (ans=='Y')
{
root->rchild=makenode();
maketree(root->rchild);
}
}
void main(){
int b;
root=NULL;
root=makenode();
maketree(root);
b=inorder(root);
printf("\nthe second largest data %d",b);
}

- sonal July 18, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include <conio.h>
#include<malloc.h>
#include<ctype.h>
struct node{
int data;
struct node* lchild;
struct node* rchild;
}*root;
int inorder(struct node* ptr){
int j;
static int i=0,a=0;
if(root->lchild == NULL && root->rchild == NULL)
{
printf("\nonly largest or ");
return root->data;
}
if(ptr){
inorder(ptr->rchild);
i++;
if(i==2)
a=ptr->data;
inorder(ptr->lchild);
}
return a;
}
struct node * makenode()
{
struct node * root;
int data;
printf("\n Enter the node data : ");
scanf("%d",&data);
root = (struct node *) malloc (sizeof(struct node));
root->data=data;
root->lchild=NULL;
root->rchild=NULL;
return (root);
}
void maketree(struct node * root)
{
char ans;
printf("\n Do you want to create the left subtree of %d (y/n)? ",root->data);
fflush(stdin);
ans=toupper(getche());
if (ans=='Y')
{
root->lchild=makenode();
maketree(root->lchild);
}
printf("\n Do you want to create the Right subtree %d (y/n)? ",root->data );
fflush(stdin);
ans=toupper(getche());
if (ans=='Y')
{
root->rchild=makenode();
maketree(root->rchild);
}
}
void main(){
int b;
root=NULL;
root=makenode();
maketree(root);
b=inorder(root);
printf("\nthe second largest data %d",b);
}

- saurav July 19, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Node* Find2ndLargest(Node& tree)
{
if (!tree.RC)
{
if (!tree.LC)
return NULL;
return tree.LC;
}

Node* temp = Find2ndLargest(*tree.RC);
if (!temp)
return &tree;
return temp;
}

- QingS July 19, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Check for the highest node

A) If its left is NUll then its parent is 2nd highest.
B)else find the maximum in its left sub tree.


struct node *second_highest(struct node *p)
{
struct node *k;
while(p->right!=NULL)
{
k=p;
p=p->right;
}

if(p->left!=NULL)
{
k=p->left;
while(k->right!=NULL)
{
k=k->right;
}
return(k);
}
else
return(k);

}

- rahuloberoi2918 July 23, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

node *max(node *root)
{
if(root==NULL)
return NULL;
else if(root->right==NULL)
return root;
else
return max(root->right);
}
node *secondmax(node *root,node *temp)
{
if(root==NULL) return root;
else if(root->left==NULL && root->right==NULL) return temp;
else if(root->right==NULL)
return max(root->left);
else
return secondmax(root->right,root);
}

- anonymous August 23, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

it is actually to find the in-order predecessor of the last node, say N.

simple two cases.

1. N has no left child, then the parent of N is the return. (no need to traverse, use an additional point to the parent while doing recursive)

2. N does have a left child. the rightmost left child of N is the return.

both cases are O(lgN) since it is BST, not binary tree.

- Anonymous September 05, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

a typo
not left child, but right

- Anonymous September 05, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
What about this simple code: {{{ static int static_var = 0; public static void kLargest(Node node, int k){ if(node == null) return; kLargest(node.right,k);} if(static_var++ < k){ System.out.print(node.value + "->"); }else{ return; } kLargest(node.left,k); } }} please comment, this also can apply to get the N Largest elements on a BST {{{ if( static_var++ < k){ print(node.value); }else return; }}} - .·´¯`·.´¯`·.¸¸.·´¯`·.¸><(((º> March 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

there is a bug in carrercup.com.. why It did not encoded my code?

- .·´¯`·.´¯`·.¸¸.·´¯`·.¸><(((º> March 07, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote
What about this simple code: {{{ static int static_var = 0; public static void kLargest(Node node, int k){ if(node == null) return; kLargest(node.right,k);} if(static_var++ < k){ System.out.print(node.value + "->"); }else{ return; } kLargest(node.left,k); } }} please comment, this also can apply to get the N Largest elements on a BST {{{ if( static_var++ < k){ print(node.value); }else return; }}} - .·´¯`·.´¯`·.¸¸.·´¯`·.¸><(((º> March 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public TreeNode secondLargest(TreeNode root){
		if(root == null || root.left==null && root.right==null)
			return null;
		if(root.right != null){
			while(root.right.right != null){
				root = root.right;
			}
		}
		else{
			root = root.left;
			while(root.right != null){
				root = root.right;
			}
		}
		return root;
	}

- tural.ferhadov January 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The second largest element is in the right subtree + root , if there is at least 1 node on right subtree,
Otherwise it is the rightmost element of left child...
Am I missing something?

- tural.ferhadov January 22, 2016 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More