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;
}
}
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). Thus, the below solution find out result in the given time complexity.
METHOD 2:
class Solution {
public int singleNonDuplicate(int[] nums) {
int left = 0, right = nums.length-1;
while(left < right){
int mid = (left + right)/2;
if( (mid % 2 == 0 && nums[mid] == nums[mid +1]) ||
(mid %2 == 1 && nums[mid] == nums[mid - 1]) )
left = mid + 1;
else
right = mid;
}
return nums[left];
}
}
Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation
Please let us know your views in comment section
Subscribe us to receive updates instantly..
Happy Coding..!!
Comments
Post a Comment