Remove Duplicates from Sorted Array

Practice this coding question on Coding Gurukul.

Problem statement

A sorted attendance export contains repeated student numbers because a learner may scan a pass several times. The export must be compacted within its existing array so that the front of the array lists each learner once, while keeping the numeric order. Your task Remove duplicate values from a nondecreasing array in place. Return the number k of distinct values and print the first k entries of the compacted array. Use O(1) auxiliary space and O(n) time. Important details Only the first k array positions matter after compaction; the unused suffix is ignored. Do not count repeated scans as different learners. Values may be negative identifiers, and an array containing one repeated number produces one retained entry. Worked example For the scans -2, -2, 4, 4, 7, retain -2, 4 and 7. Print 3 on the first line and -2 4 7 on the second.

Input format

The first line contains n. The next line contains n space-separated integers; for n = 0 this line may be empty.

Output format

Print k, then the k retained values on the next line.

Constraints

1 <= n <= 30000; -100 <= values <= 100; the array is sorted.

Sample input

5
-2 -2 4 4 7

Sample output

3
-2 4 7

Sign in to run or submit a solution in C++, Java or Python.