Return unique of duplicate values array

Mike Sun
2 min readJun 12, 2020

Given a sorted array, return n unique counts of elements in it, while also rearranging the array such that the first n element is unique. Diagram illustration as below

If you think the problem is confusing, you haven’t seen its crude form. Initially the problem was phrased as removing duplicates which is hella confusing.

Here is my code to this problem.

First we check if the nums array is empty, if it is, terminate the function by returning 0. If not, we initialize 2 variables, i and j. We then loop through the length of nums array. Let’s go over an example with our given array [0,0,1,1,2]. Here is what happens in the for loop:

i=0, j=1. Check if nums[0] is equal to nums[1]. True.

nums = [0,0,1,1,2]

i=0,j=2. Check if nums[0] is equal to nums[2]. False. =>increment i by 1. nums[1] = nums[2]. Note lists are mutable.

nums = [0,1,1,1,2]

i=1,j=3. Check if nums[1] is equal to nums[3]. True.

nums = [0,1,1,1,2]

i=1,j=4. Check if nums[1] is equal to nums[4]. False. =>increment i by 1. nums[2] = nums[4].

nums = [0,1,2,1,2]

We then return the count of i+1, since i started from 0. This is how we return the number of unique elements while reordering the array with no added memory.

Learn together, happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Mike Sun
Mike Sun

Written by Mike Sun

Random tech blog for my fellow peers troubleshooting stuff. Things I wished I knew without needing to spend hours/days digging...

No responses yet

Write a response