# 26 Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

```
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 
It doesn't matter what you leave beyond the new length.
```

## Naive Approach

**The Idea:** Erase the element if an adjacent duplicate is found from the array.

**Complexity:** O(n^2) time and O(1) space

```cpp
int removeDuplicates(vector<int>& nums) {
    if (nums.empty()) return 0;
    else if (nums.size() == 1) return 1;

    for (int i = 1; i < nums.size(); i++) {
        if (nums.at(i - 1) == nums.at(i)) {
            nums.erase(nums.begin() + i);
            i--;
        }
    }

    return nums.size();
}
```

## Optimal Approach

**The Idea:** Add every unique occurrence in the array to the start, and ignore duplicates. That way the start of the array will only populate with unique elements.

**Complexity:** O(n) time and O(1) space

```python
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 1:
            return len(nums)

        i2 = 1
        for i in range(1, len(nums)):
            if nums[i] != nums[i-1]:
                nums[i2] = nums[i]
                i2 += 1

        return i2
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/26_remove_duplicates_from_sorted_array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
