Microsoft interview question(2023)
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-02-06Added By Anonymous
Source: Link
Given a tree having N nodes, numbered from 0 to N-1. Each node can contain only one of the letters ‘a’ or ‘b’. An array A of length N is used to represent the tree. A[k] (for K from 0 to N-1) represents the parent of the kth node. Letters are represented as a string S[k]. You need to find the number of vertices on the longest path in the tree, such that no pair of adjacent vertices on the path would contain the same letter.
1#include<bits/stdc++.h>
2using namespace std;
3struct Node{
4 vector<Node*>child;
5 int data;
6 Node(int data){
7 this->data = data;
8 }
9};
10
11int findMaxi(Node* node,int &res,vector<char> &s){
12 if(!node)
13 return 0;
14
15 int fl=0,sl=0;
16 for(auto &c:node->child){
17 int childRes = findMaxi(c,res,s);
18 if(s[node->data] != s[c->data]){
19 if(fl<childRes){
20 sl = fl;
21 fl = childRes;
22 }
23 else if(sl<childRes){
24 sl=childRes;
25 }
26 }
27 }
28
29 res = max(res,fl+sl+1);
30 return fl+1;
31}
32
33int main(){
34 Node* root = new Node(0);
35 Node* root2 = new Node(2);
36 root->child.push_back(new Node(1));
37 root->child.push_back(root2);
38 root2->child.push_back(new Node(3));
39 vector<char>s={'a','a','b','a'};
40 int res=INT_MIN;
41 findMaxi(root,res,s);
42 cout<<res;
43
44}