DevPath

← All problems

Remove Duplicates From Sorted Array

Easy arrays · two-pointers

Description

Given a sorted array, return the length of the unique sequence (each distinct value counted once).

Constraints

0 <= n <= 100000

Examples

Input: nums = [1,1,2]

Output: 2

Hints (1)
  • Walk with a write pointer that only advances on a new value.

Solutions

Count transitions between neighbours. · Time O(n) · Space O(1)

func countUnique(nums []int) int {
    if len(nums) == 0 {
        return 0
    }
    count := 1
    for i := 1; i < len(nums); i++ {
        if nums[i] != nums[i-1] {
            count++
        }
    }
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account