Apple Interview Question
Staff EngineersCountry: United States
If you want the output in the same string format as the input:
def sort_giant_string(giant, col, col_type=(str, str, int)):
data = [row.split(" ") for row in giant.split("\n")]
data.sort(key=lambda x: col_type[col - 1](x[col - 1]))
return "\n".join([" ".join([str(cell) for cell in row]) for row in data])
-(NSArray *) sortedArrayWithColumn:(NSUInteger) column {
return [self sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2){
NSArray *components1 = [obj1 componentsSeparatedByString:@","];
NSArray *components2 = [obj2 componentsSeparatedByString:@","];
if (column >= components1.count && column >= components2.count) {
return NSOrderedSame;
}
if (column >= components1.count) {
return NSOrderedDescending;
}
if (column >= components2.count) {
return NSOrderedAscending;
}
NSString *component1 = components1[column];
NSString *component2 = components2[column];
return [component1 caseInsensitiveCompare:component2];
}];
}
Elegant 4 line solution in Python (for small strings of course):
Test Code:
However, in a distributed setting, when we have large amounts of strings to process, we can divide up the column that we are trying to sort by and process per chunks. We would create multiple chunks and use a sorting algorithm such as quicksort or mergesort to combine the data into a sorted order.
- prudent_programmer March 19, 2018