Edit Problem
Title
Problem URL
Difficulty
Easy
Medium
Hard
Tags
Two Pointers
×
Add tag
Go file path (optional)
Notes (optional)
## What It Does This function counts the number of **unique elements** in a sorted array. The `index` pointer tracks the start of the current group of duplicate values, while `cursor` scans forward. When a new distinct value is found, `ans` increments and `index` jumps to `cursor`. The `+ 1` at the end accounts for the final group, which never triggers a mismatch to count itself. For example, `[1, 1, 2, 3, 3, 3, 4]` → returns `4`. --- ## Complexity Analysis **Time Complexity: O(n)** `cursor` advances by 1 on every iteration and never backtracks, so the loop runs exactly `n` times — a single linear pass through the array. **Space Complexity: O(1)** Only three integer variables (`cursor`, `ans`, `index`) are used regardless of input size. No additional data structures are allocated. --- ## A Few Notes **It assumes a sorted array.** The duplicate-detection logic only works because identical values are guaranteed to be adjacent. On an unsorted array it would produce incorrect results. **The variable naming could be clearer.** `index` and `cursor` are both just integer indices, making the code a bit harder to read at a glance. Something like `left`/`right` or `groupStart`/`scanner` would better convey their roles. **`ans` is slightly misleading** since it's an intermediate count, not the final answer — it holds `uniqueCount - 1` until the return statement corrects it.
First solved
Mar 2, 2026
Clear
Save Changes
Cancel