Google Interview Question
SDE1sCountry: United States
not sure how this design will scale, but anyway, I understood we have:
- enum integer values that are hirarchical, e.g. each decimal place represents a hirarchy
- there is a way to lookup the textual representation of the enum value e.g. there is a hashtable with integer key and text representation value
- you want the parent-key of a key? that is integer division by 10
- I wonder what you do if there are more then 10 children .. but anyway, here the code
unordered_map<int, string> enums_{{1, "car"}, {11, "toyota"}, {111, "prius"} /*, ... */ };
pair<int, string> get_parent(int value) {
if(value >= 10) {
auto it = enumns_.find(value/10);
if(it != enums.end()) {
return it->second;
}
}
throw "error, has no parent (?)";
}
Its a composite design pattern, we are supposed to reuse the parent value.
/**
* give an enum, where each element has a parent-children relationship, and children's expression is the value of parent append an index, such as
* enum vehicle {
* car = 1
* toyota = 11
* camry = 111
* corolla = 112
* honda = 12
* truck = 2
* GMC = 21
* }
*
*/
public class ParentChild {
public enum Vehicle {
CAR("1",null),
TOYATA("1",CAR),
CAMERY("1",TOYATA),
CORALLA("2",TOYATA),
HONDA("2",CAR),
TRUCK("2",null),
GMC("1",TRUCK)
;
String value;
Vehicle(String val, Vehicle parent) {
if(parent!=null) {
this.value = parent.value+val;
} else {
this.value = val;
}
}
@Override
public String toString() {
return name()+":"+value;
}
}
public static void main(String[] args) {
System.out.println(Vehicle.TOYATA);
System.out.println(Vehicle.CORALLA);
System.out.println(Vehicle.GMC);
}
}
Hierarchical data structure:
Output:
- ProTechMulti November 01, 2017GMC 21
track 2