Coding problem
Compact a sorted list in place
The task
A small sensor hub keeps the IDs it has seen in one sorted array. It has no room for a second array, so before each upload it squeezes the repeats out of that array where it is.
Complete CompactSorted(int[] values). values is sorted in ascending order and may hold repeats. Rearrange it in place so that each distinct value appears once at the front, still in ascending order, and return how many distinct values there are. The slots after that count may hold anything. The array is never null.
Signature
public static int CompactSorted(int[] values)
Examples
[1, 1, 2, 3, 3, 3, 4]→4, and the array starts [1, 2, 3, 4]. The four distinct values move to the front in order.[2, 2, 2]→1, and the array starts [2]. One distinct value.
Limits: Up to 1,000,000 values; a value can be any int.
The tests check: an empty array, one value, values with no repeats, negative values, int.MinValue as a real value, the last value kept, and 1,000,000 values in time.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public static class Solution
{
// Moves each distinct value of the sorted array to the front once, in order, and returns how many there are.
public static int CompactSorted(int[] values)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.