Meta interview question

Permutations of a string.

Interview Answer

Anonymous

31 Oct 2019

-(void)helpPer:(NSMutableString*)str res:(NSMutableArray*)res tmpStr:(NSMutableString*)tmpStr{ if (str.length == 0){ [res addObject:[tmpStr copy]]; } for (NSInteger i = 0 ; i < str.length ; i++){ NSString *ch = [NSString stringWithFormat:@"%c",[str characterAtIndex:i]]; [str deleteCharactersInRange:NSMakeRange(i, 1)]; [tmpStr appendString:ch]; [self helpPer:str res:res tmpStr:tmpStr]; [tmpStr deleteCharactersInRange:NSMakeRange(tmpStr.length - 1, 1)]; [str insertString:ch atIndex:i]; } } - (NSArray*)per:(NSString*)str{ NSMutableArray *res = [NSMutableArray new]; [self helpPer:[str mutableCopy] res:res tmpStr:[@"" mutableCopy]]; return res; } - (void)viewDidLoad { [super viewDidLoad]; NSArray *res = [self per:@"abc"]; NSLog(@"%@",res); }