Microsoft interview question(2023)

213
Feb 06, 2024
Feb 19, 2024

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.

#include<bits/stdc++.h>
using namespace std;
struct Node{
    vector<Node*>child;
    int data;
    Node(int data){
        this->data = data;
    }
};

int findMaxi(Node* node,int &res,vector<char> &s){
    if(!node)
        return 0;
    
    int fl=0,sl=0;
    for(auto &c:node->child){
         int childRes = findMaxi(c,res,s);
        if(s[node->data] != s[c->data]){
            if(fl<childRes){
				sl = fl;
                fl = childRes;
            }
            else if(sl<childRes){
                sl=childRes;
            }
        }   
    }
 
    res = max(res,fl+sl+1);
    return fl+1;
}

int main(){
    Node* root = new Node(0);
    Node* root2 = new Node(2);
    root->child.push_back(new Node(1));
    root->child.push_back(root2);
    root2->child.push_back(new Node(3));
    vector<char>s={'a','a','b','a'};
    int res=INT_MIN;
    findMaxi(root,res,s);
    cout<<res;
   
}
Comments (2)