# 136 Single Number

## Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

```cpp
  #include <iostream>
  #include <vector>
  #include <algorithm>
  using namespace std;


  int singleNumber(vector<int>& nums) {
      sort(nums.begin(), nums.end());

      for (int i = 0; i < nums.size(); i+=2)
      {
          try
          {
              if (nums.at(i) == nums.at(i + 1))
                  continue;
              else return nums.at(i);
          }
          // element (i+1) appeared to be at the last position
          catch (const std::out_of_range& oor)
          {
              //std::cerr << "Out of Range error: " << oor.what() << '\n';
              return nums.at(i);
          }
      }
  }

  int main()
  {
      vector<int> myvect{ 2,2,1 };
      cout << singleNumber(myvect);
  }
```

* Attempt 2: The above is terrible implementation, and certainly not linear.
  * The trick here is identifying that when we have the same number twice, and xor will reset that particular bit to zero. Anything that xors with zero will return back the original number. Regardless of the combination of bits that come in, the individual bits will become flipped when it repeats.

```cpp
int singleNumber(vector<int>& nums) {
    int sum = 0;
    for (auto i : nums) {
        sum ^= i;
    }
    return sum;
}
```


---

# 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/single_number_136.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.
