
Sponsored
Sponsored
This approach leverages the properties of XOR bitwise operation. The XOR of a number with itself is 0, and the XOR of a number with 0 is the number itself. Thus, XORing all elements in the array results in getting the single number because all other numbers cancel themselves out.
Time Complexity: O(n) - We go through the array once.
Space Complexity: O(1) - We only use a single integer to store the result.
1using System;
2
3public class SingleNumberSolution {
4 public static int SingleNumber(int[] nums) {
5 int result = 0;
6 foreach (int num in nums) {
7 result ^= num;
8 }
9 return result;
10 }
11
12 public static void Main() {
13 int[] nums = {2, 2, 1};
14 Console.WriteLine(SingleNumber(nums)); // Output: 1
15 }
16}The C# solution uses a foreach loop for the XOR operation over the array resulting in the remaining single number after duplicates are canceled.
In this approach, we use a hash map (or dictionary) to count occurrences of each number. The single number will have a count of 1. This isn't the optimal solution in terms of extra space but is valid if space was not constrained.
Time Complexity: O(n) - We traverse the array twice (once for filling the map, once for checking the counts).
Space Complexity: O(n) - Extra space proportional to the input range.
1#
This C solution uses an array to simulate a hash map, where each index corresponds to a potential value of nums[i]. It maps numbers from -30000 to +30000 to indices 0 to 60000 to handle negative numbers.