Microsoft Corporation Question:

Download Job Interview Questions and Answers PDF

write a function that will take a sorted array, possibly with duplicates, and compact the array, returning the new length of the array?

Microsoft Interview Question
Microsoft Interview Question

Answer:

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.


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++;
}

Download Microsoft Interview Questions And Answers PDF

Previous QuestionNext Question
How could you determine if a linked list contains a cycle in it, and, at what node the cycle starts?Assume you have an array that contains a number of strings (perhaps char * a[100]). Each string is a word from the dictionary. Your task is as under?