> For the complete documentation index, see [llms.txt](https://coding-9.gitbook.io/untitled/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coding-9.gitbook.io/untitled/binary-search/bs-on-1d-array/540.-single-element-in-a-sorted-array.md).

# 540. Single Element in a Sorted Array

## Problem Statement

<br>

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.

Return *the single element that appears only once*.

Your solution must run in `O(log n)` time and `O(1)` space.

&#x20;

**Example 1:**

<pre><code><strong>Input: nums = [1,1,2,3,3,4,4,8,8]
</strong><strong>Output: 2
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: nums = [3,3,7,7,10,11,11]
</strong><strong>Output: 10
</strong></code></pre>

&#x20;

**Constraints:**

* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 105`

## Intuition

```
Approach:

Note that,

When a single element appears ordering of indexes is changes

1 1 2 2 3 4 4
0 1 2 3 4 5 6

Note at odd index, second repeat comes at odd
But then after the single element appears, second repeat comes at even

take advantage of  that
```

### Links

<https://leetcode.com/problems/single-element-in-a-sorted-array/description/>

### Video Links

### Approach 1:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        if(nums.size() == 1)
            return nums[0];

        int low=0, high=nums.size()-1;
        while(low<high){
            int mid = low+(high-low)/2;
            if(mid % 2 != 0){
                if(nums[mid] == nums[mid-1])
                    low = mid+1;
                else if(nums[mid] == nums[mid+1])
                    high= mid-1;
                else
                    return nums[mid];
            }
            else{
                if(nums[mid] == nums[mid+1])
                    low = mid+2;
                else if(nums[mid] == nums[mid-1])
                    high = mid-2;
                else
                    return nums[mid];
            }
        }

        return nums[low];
    }
};
```

{% endcode %}

### Approach 2:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

###
