Microsoft SDE2
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2022-04-24Added By Anonymous
Source: Link
Microsoft | SDE2
1. Given a BST and a rank number. Return the tree node value associated with that rank in O(logn) TC.
PS: rank is nothing but tree node index value in InOrder traversal array of bst.
```
class Node{
public:
int data;
int childTreeLen; // no of nodes in Left subtree under the node
Node* left;
Node* right;
};
Node util(Node root, int rank){
if(root == NULL) return NULL;
int leftTreeDepth = root.left.childTreeLen;
if(leftTreeDepth > rank){
return util(root.left, rank);
} else if(leftTreeDepth < rank){
return util(root.right, rank-leftTreeDepth-1);
} else
return root;
}
int size(Node root){
return root.childTreeLen;
}
int findValue(int rank){
if(rank<0)
return -1;
if(rank > size(root))
return -1;
Node ans = util(root, rank)
return ans.data;
}
int main() {
cout<<findValue(rank-1);
return 0;
}
```
2. Print the difference string.
Two strings given S1, S2. Remove all occurances chars in S1 which are present in S2 inplace.
s1-s2 e.g. “hello world” – “Chop” = “Cell wrld”
Need in O(n) time complexity without using any library methods in C++.
In my below code, I've tried to use extra char array. So that with null character we can do the trimming of string.
Please suggest any novel approach to solve inplace.
```
int main()
{
string s1 = "hello world";
string s2 = "hop";
map<char, int> m;
for(char c: s2)
m[c]++;
for(int i=0;i<s1.length();i++){
if(m.find(s1[i]) != m.end()){
s1[i] = '*';
}
}
char* char_arr;
char_arr = &s1[0];
int j, n = strlen(char_arr);
for (int i = j = 0; i < n; i++)
if (char_arr[i] != '*')
char_arr[j++] = char_arr[i];
char_arr[j] = '\0';
cout << char_arr;
return 0;
}
```