Goldman Sachs Interview Question
Software Engineer / DevelopersCountry: United States
Assumption - An employee can report to only 1 manager
It can be implemented as a tree
P = Immediate Parent (Immediate manager)
R = Root of the tree (main boss)
E = Employee to search or add
P searchChildElementInTree(R ,E) - gives manager of the employee
R addEmployeeInTree(R, P, E) - assuming employee can have maximum of 5 immediate subordinates
displayTreeWithRootAs(P) - all nodes under P and its children should be displayed
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Employee
{
public:
Employee(unsigned id, string fName, string lName, Employee* manager = nullptr);
void showSubOrdinates() const;
void addSubordinate(Employee* mySubordinate);
private:
unsigned id;
string firstName;
string lastName;
Employee * myManager;
std::vector<Employee*> mySubordinates;
void showMyInfo() const;
};
Employee::Employee(unsigned id, string fName, string lName, Employee* manager)
:id(id), firstName(fName), lastName(lName), myManager(manager)
{
if (myManager != nullptr)
{
myManager->addSubordinate(this);
}
}
void Employee::addSubordinate(Employee* mySubordinate)
{
mySubordinates.push_back(mySubordinate);
}
void Employee::showMyInfo() const
{
std::cout << firstName << " " << lastName << endl;
}
void Employee::showSubOrdinates() const
{
for (vector<Employee*>::const_iterator it = mySubordinates.begin(); it != mySubordinates.end(); ++it)
{
(*it)->showMyInfo();
}
}
int main()
{
unsigned id = 0;
Employee philip(id++, "Philip", "Smith");
Employee joe(id++, "Joseph", "Davis", &philip);
Employee rebecca(id++, "Rebecca", "Hall");
joe.addSubordinate(&rebecca);
philip.showSubOrdinates();
joe.showSubOrdinates();
}
#include<stdio.h>
#include<stdlib.h>
#include <string>
using namespace std;
class employee
{
int ID;
string LName;
string FName;
employee* M;
employee* Sub;
public:
employee():ID(-1),LName(NULL),FName(NULL),M(NULL),Sub(NULL)
{
;
}
employee(int n,string fn,string ln,employee* manager=NULL,employee* subor=NULL)
{
ID = n;
LName = ln;
FName = fn;
M = manager;
Sub = subor;
}
void set_sub(employee * s)
{
this->Sub = s;
}
void Print_Infor()
{
printf("\n%d\n",this->ID);
}
employee * get_sub()
{
return this->Sub;
}
void get_subor()
{
this->Print_Infor();
employee* p;
for(p=this;p->get_sub()!=NULL;)
{
p=this->get_sub();
p->Print_Infor();
}
}
};
int main()
{
employee b(1,"hua","jun");
employee VP(2,"He","pin",&b);
b.set_sub(&VP);
b.get_subor();
getchar();
}
- Anonymous March 03, 2013