Interview Questions

Given the following prototype:int compact(int * p, int size) ...

Microsoft Interview Questions and Answers


(Continued from previous question...)

18. Given the following prototype:int compact(int * p, int size) ...

Question: Given the following prototype:
int compact(int * p, int size);
write a function that will take a sorted array, possibly with duplicates, and compact the array, returning the new length of the array. That is, if p points to an array containing: 1, 3, 7, 7, 8, 9, 9, 9, 10, when the function returns, the contents of p should be: 1, 3, 7, 8, 9, 10, with a length of 5 returned.

Answer: A single loop will accomplish this.
int compact(int * p, int size)
{
int current, insert = 1;
for (current=1; current < size; current++)
if (p[current] != p[insert-1])
{
p[insert] = p[current];
current++;
insert++;
} else
current++;
}

(Continued on next question...)

Other Interview Questions