February 8, 2016 Andrey

Recursively revert an array in Objective C

It’s a question that my fried received on a phone interview with one of the tech companies from West Coast
Let’s do it! We will create a function reverseAnArray that takes a NSMutableArray and return void.
+(void) reverseAnArray:(NSMutableArray *)input;

1. Set up a base – once we reach the end of the array we will return;

2. Temporary save first object and remove it from array

3. Call recursion again on a smaller array

4. Return from recursive call and put the saved object back in the array.

Final code:

+(void) reverseAnArray:(NSMutableArray *)input {

    if ([input count] == 0)
        return;
    
    NSObject *temp = [input objectAtIndex:0];
    [input removeObjectAtIndex:0];
    
    [self reverseAnArray:input];
    [input addObject:temp];
    
    return ;
}

Testing results

 NSMutableArray *input = [[NSMutableArray alloc] initWithArray:@[@2,@1,@3,@4,@6,@7,@8,@9]];
        NSLog(@"input is: %@", input);
        [Solution reverseAnArray:input];
        NSLog(@"output is: %@", input);

2016-02-08 14:06:41.944 UniqueElements[34000:2143133] input is: (
2,
1,
3,
4,
6,
7,
8,
9
)
2016-02-08 14:06:41.946 UniqueElements[34000:2143133] input is: (
9,
8,
7,
6,
4,
3,
1,
2
)

Done