An outline of google phone interview:
Question 1
// Create a function that takes int numbers[1000] and sorts it into ascending order (lowest to highest)
I asked an interviewer if bubble sort is ok, or does he wants something more complex. He said that bubble sort is good enough. I also talked about the complexity, the worst is n squared.
-(NSArray*)sortArray:(NSArray*)arr{
NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:arr];
for (int j = 0; j<[temp count]; j++){
for (int i=0; i<[temp count] - 1; i++){
if([temp[i] intValue] > [temp[i+1] intValue]){
int x = [temp[i] intValue];
temp[i]= [NSNumber numberWithInt:[temp[i+1] intValue]];
temp[i+1] = [NSNumber numberWithInt:x];
}
}
}
return temp;
}
Question 2
// Returns an array of NSDates with the contents of unsortedDates sorted
// in ascending order (oldest in the past to furthest in the future)
+ (NSArray *)sortDates:(NSArray *)unsortedDates {
if(!unsortedDates)
return nil;
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey"@"self" ascending:YES];
NSArray *results = [unsortedArray sortedArrayUsingDescriptor:descriptor];
return results;
}
Question 3
// Implement recursiveHierarchy on a UIView hierarchy.
The first version of the question was to simply log it one after another and a second version was to output with a little spaces in the beginning that show the deepness of the recursive function. I suggested that using Categories would be a good solution.
Code below is for the second version.
@interface UIView (ViewLogAddition)
-(void)logHierarchy;
@end
@implementation UIView (ViewLogAddition)
- (void)logHierarchy:(int)deepness {
NSMutableString *mutString = [NSMutableString new];
for (int i=0; i< deepness; i++){
[mutString appendString:@" "];
}
if (deepness > 0)
[mutString appendString:@"|"];
NSLog(@"%@ %@",mutString, [self class]);
for (UIView* subview in self.subviews){
[subview logHierarchy:++deepness];
}
}
@end
//To call the function from the main program
UIView* view; [view logHierarchy:0];
Initial output
<UIView> <MDCFlexibleHeaderView> <UIView> <UIScrollView> <UIView>
Output (Mk2)
<UIView> | <UIScrollView> | | <UIView> | | <UIView> | | <UIImageView> | | <UIImageView> | <_UILayoutGuide> | <_UILayoutGuide> | <MDCFlexibleHeaderView> | <UIView>