Skip to content

Commit 991f4b0

Browse files
committed
'Single Number' soln
1 parent a878450 commit 991f4b0

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

leetcode/single_number.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
///
2+
/// Problem: Single Number
3+
///
4+
/// Given a non-empty array of integers nums, every element appears twice except for one.
5+
/// Find that single one.
6+
///
7+
/// You must implement a solution with a linear runtime complexity and use only constant
8+
/// extra space.
9+
///
10+
/// Example 1:
11+
/// Input: nums = [2,2,1]
12+
/// Output: 1
13+
///
14+
/// Example 2:
15+
/// Input: nums = [4,1,2,1,2]
16+
/// Output: 4
17+
///
18+
/// Example 3:
19+
/// Input: nums = [1]
20+
/// Output: 1
21+
///
22+
/// Constraints:
23+
/// 1 <= nums.length <= 3 * 10^4
24+
/// -3 * 10^4 <= nums[i] <= 3 * 10^4
25+
/// Each element in the array appears twice except for one element which appears only once.
26+
///
27+
28+
// # Solution 1: XOR approach
29+
// Time complexity: O(n) where n is the length of the array
30+
// Space complexity: O(1) - We only use a single variable
31+
32+
impl Solution {
33+
pub fn single_number(nums: Vec<i32>) -> i32 {
34+
let mut result = 0;
35+
36+
for num in nums {
37+
result ^= num;
38+
}
39+
40+
result
41+
}
42+
}

0 commit comments

Comments
 (0)