Loading

LeetCode problem#3158

Find the XOR of Numbers Which Appear Twice

Solved in 2 languagesRustJava

Solve it on LeetCode(opens in a new tab)

Solution

18 lines
1impl Solution {
2    pub fn duplicate_numbers_xor(nums: Vec<i32>) -> i32 {
3        let mut seenArr: [i32; 50] = [0; 50];
4        let mut result: i32 = 0;
5
6        for num in nums {
7            let index: usize = (num - 1) as usize;
8            if seenArr[index] > 0 {
9                result ^= num;
10            }
11            else {
12                seenArr[index] += 1;
13            }
14        }
15
16        return result;
17    }
18}
1class Solution {
2    // time O(n)
3    // space O(1)
4    public int duplicateNumbersXOR(int[] nums) {
5        // Using constraints of elements being between 1 and 50 inclusive
6        int[] seenArr = new int[50];
7        int result = 0;
8
9        for (int i = 0; i < nums.length; i++) {
10            if (seenArr[nums[i] - 1] > 0) {
11                result ^= nums[i];
12            }
13            else {
14                seenArr[nums[i] - 1]++;
15            }
16        }
17
18        return result;
19    }
20}

Want a walkthrough of this Rust solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.