Posts

Showing posts with the label XOR

XOR Operation in an Array

Given an integer n and an integer start . Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length . Return the bitwise XOR of all elements of nums . Example 1: Input: n = 5, start = 0 Output: 8 Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. Where "^" corresponds to bitwise XOR operator. Example 2: Input: n = 4, start = 3 Output: 8 Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8. Example 3: Input: n = 1, start = 7 Output: 7 Example 4: Input: n = 10, start = 5 Output: 2   Constraints: 1 <= n <= 1000 0 <= start <= 1000 n == nums.length   class Solution {     public int xorOperation(int n, int start) {         int i = 1, result = 0;         while(i<=n){             result ^= start;             start+=2;             i++;         }         return result;     } } Here, we are going to solve using using XOR operator. In the problem,

Single Element in Sorted Array

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. Example 1: Input: [1,1,2,3,3,4,4,8,8] Output: 2 Example 2: Input: [3,3,7,7,10,11,11] Output: 10 Note: Your solution should run in O(log n) time and O(1) space. METHOD 1:   class Solution {     public int singleNonDuplicate(int[] nums) {         int result = 0;         for(int num:nums)             result ^= num;         return result;     } } Try it on Leetcode Here we are going to do XOR operation. Because, in the problem itself they mentioned that each number in array repeated twice and only one number occurs once. Also XOR of same number is 0 and if continue doing with all numbers the final result contains that non repeating number. Time Complexity: O(N) But in the question note, they mention that we have to finish the iteration in O(logN). Th

Single Number - Leetcode

Given a non-empty  array of integers, every element appears twice except for one. Find that single one. Example 1: Input: [2,2,1] Output: 1   Example 2: Input: [4,1,2,1,2] Output: 4     class Solution { public int singleNumber(int[] nums) { int result = 0 ; for ( int i : nums) { result ^= i; } return result;   } }  Here we are going to do XOR operation. Because each number in array is repeated twice. So, XOR of same number is always 0 and  number which is not repeated will be stored in result.