Facebook Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
class my_exception: public exception {
std::string reason;
public:
my_exception(string s) : reason(s) {}
virtual const char* what() const throw() {
return reason.c_str();
}
};
class cb {
private:
int sz;
int *buffer;
int count;
int rindex, windex;
public:
cb(int mz) : sz(mz+1), count(0), rindex(0), windex(0) {
buffer = new int[sz];
bzero(buffer, sizeof(int)*(sz));
}
bool full() {
return ((windex + 1)%sz == rindex)? true: false;
}
bool empty() {
return rindex == windex? true: false;
}
bool add(int v) {
if (rindex == windex) {
return false;
// assert on count == sz;
}
buffer[windex] = v;
windex = (windex+1)%(sz);
if (full()) {
cout << " the CR is full \n";
}
return true;
}
int get() {
if (empty()) {
throw my_exception("Empty");
}
int v = buffer[rindex];
rindex = (rindex+1)%sz;
if (empty()) {
cout << " the buffer is empty\n";
}
return v;
}
};
int main() {
// your code goes here
cb cr(3);
try {
cr.add(1);
cr.add(2);
cr.add(3);
if(!cr.add(4)) {
cout << "4 cant be added\n";
}
cout << cr.get() <<"\t" << cr.get() << "\t" << cr.get() <<"\n";
cout <<"Getting the 4th element \n";
cr.get();
} catch(const exception &e) {
cout << "Exception caught at addng " << e.what() <<"\n";
}
}
Looking for interview experience sharing and coaching?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
- aonecoding June 06, 2017