Learner Level

Implement the removeDuplicatesSortedArrayLength method that returns the length after removing duplicates from a sorted array.

The input contains a sorted integer array nums and its length size. Your task is to remove duplicate values logically and return the number of unique values.

Because the array is sorted, duplicate values appear next to each other. The returned length represents how many positions would remain after keeping each value only once.

For example, [1,1,2] contains the unique values 1 and 2, so the answer is 2.

Example 1

Input
nums (int[]) = [1,1,2]
size (int) = 3
Returns (int) 2

Example 2

Input
nums (int[]) = [0,0,1,1,1,2,2,3,3,4]
size (int) = 10
Returns (int) 5

Example 3

Input
nums (int[]) = [1,2,3]
size (int) = 3
Returns (int) 3

Use a write pointer to track the position where the next unique value should be placed.

Start with the first value as unique. Then scan the array from the second value onward. Whenever the current value is different from the previous value, write it at the current write position and move the write pointer forward.

At the end, the write pointer value is the count of unique elements.

Pseudocode:

function removeDuplicatesSortedArrayLength(nums, size):
    if size == 0:
        return 0
    write = 1
    for read from 1 to size - 1:
        if nums[read] != nums[read - 1]:
            nums[write] = nums[read]
            write++
    return write
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.