I was asked this question in an interview once and I grew curious as to what the best answer is. I primarily got stuck with providing a solution that traces a 2-d array in a time that's better than O(n^2). Here's the question:
/*
Here's a helper class that can efficiently return the smallest
object it contains. Assume it magically knows how to sort your
objects correctly.
*/
@interface MinHeap : NSObject
@property (readonly) NSUInteger count;
// Adds an object
- (void)addObject:(id)object;
// Returns (but does not remove) the smallest object, or nil if empty
- (id)minObject;
// Removes and returns the smallest object, or nil if empty
- (id)popMinObject;
// Removes all objects
- (void)removeAllObjects;
// **Implement this method**
- (NSArray*)process:(NSArray*)incomingArray
@end
/*
Sample input:
[
[ @2, @4, @6 ],
[ @1, @5, @10 ],
[ @3, @7, @8, @98, @99 ],
[],
[ @4, @4 ]
]
Expected output:
[ @1, @2, @3, @4, @4, @4, @5, @6, @7, @8, @10, @98, @99 ]
*/
Here's the answer I gave:
- (NSArray*)process:(NSArray*)incomingArray
{
// n squared
for (int i=0; i<incomingArray.count; i++)
{
NSArray* row = incomingArray[i];
for (int j=0; j<row.count; j++)
[self addObject:row[j]];
}
NSMutableArray* returnArray = [NSMutableArray new];
// n
for (int i=0; i<self.count; i++)
[returnArray addObject:[self minObject]];
return [NSArray arrayWithArray:returnArray];
}
Apparently (if I were to have given his expected solution) I would have taken advantage of the assumption that the individual arrays inside the 2-d array are already sorted. The above solution did not convince my interviewer.
So, how can I use the above class in an efficient-than-O(n^2) way to produce the expected output?
P.S: A) Note that the individual arrays inside the sample input are always sorted. B) The input can have duplicates and the output should take contain duplicates.