




Sponsored
Sponsored
This approach uses bit manipulation to solve the problem with constant space and linear runtime. The idea is to count the number of times each bit is set in the given numbers modulo 3 using two integers. This effectively filters out the bits that appear in numbers repeated thrice and leaves the bits of the unique number.
Time Complexity: O(n) - where n is the number of elements in the array.
Space Complexity: O(1) - as only a fixed amount of space is used regardless of the input size.
1
In Python, the problem is addressed with the same principle: ones and twos track the appearance of bits, and compatibility is ensured through logical operations to simulate three-bit counters for each position in the binary representation of numbers.
This approach involves using a data structure to count occurrences of each number. Although this uses linear time complexity, it requires additional memory to store frequencies, which violates the constant space constraint.
Time Complexity: O(n log n) - primarily due to the sorting step.
Space Complexity: O(1) - if in-place sort is assumed.
1#include <vector>
2#include <unordered_map>
3using namespace std;
4
5int singleNumber(vector<int>& nums) {
6    unordered_map<int, int> count;
7    for (int num : nums) {
8        count[num]++;
9    }
10    for (auto &pair : count) {
11        if (pair.second == 1) {
12            return pair.first;
13        }
14    }
15    return -1;
16}
17
18int main() {
19    vector<int> nums = {0, 1, 0, 1, 0, 1, 99};
20    return singleNumber(nums);
21}In this approach, we use a hash map to count the frequency of each number, iterating through the array twice—first to populate the map and second to find the number appearing once. This requires additional space for the hash table.
Solve with full IDE support and test cases