> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Single Number II Python Solution with Tests

> Tested Python solution for LeetCode 137 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 137, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Bit Manipulation](/catalog/topics/bit-manipulation). [View on LeetCode](https://leetcode.com/problems/single-number-ii/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 137   # by problem number
lcpy gen -s single_number_ii   # by problem name
```

## Problem

Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. *Find the single element and return it*.

You must implement a solution with a linear runtime complexity and use only constant extra space.

### Examples

```
Input: nums = [2,2,3,2]
Output: 3
```

```
Input: nums = [0,1,0,1,0,1,99]
Output: 99
```

### Constraints

* 1 \<= nums.length \<= 3 \* 10^4
* -2^31 \<= nums\[i] \<= 2^31 - 1
* Each element in nums appears exactly three times except for one element which appears once.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/single_number_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/single_number_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def single_number(self, nums: list[int]) -> int:
        ones = 0
        twos = 0
        for num in nums:
            ones = (ones ^ num) & ~twos
            twos = (twos ^ num) & ~ones
        return ones
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.