Created
December 27, 2018 06:27
-
-
Save PulkitAgg/4a64f49ad4125ca8a634c484917678c7 to your computer and use it in GitHub Desktop.
Find Duplicate number problem asked by GOOGLE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Problem Statement: You are given an array of length n + 1 whose elements belong to the set {1, 2, ..., n}. By the pigeonhole principle, there must be a duplicate. Find it in linear time and space. | |
Solution: | |
// XOR operator will return 0 if it is applied even times on same number And return number itself when it is applied odd times on the same number. | |
function findDuplicate(Arr) { | |
let len = Arr.length; | |
let acutalXORResult = 0; // contains the XOR operation result for the actual values from 1 to n. | |
let arrayXORResult = 0; // contains the XOR operation result on the array values. | |
for(let count=0; count<len; count++) { | |
acutalXORResult = acutalXORResult^count; | |
} | |
for(let count=0; count<len; count++) { | |
arrayXORResult = arrayXORResult^Arr[count]; | |
} | |
// XOR b/w two result will calculate the duplicate value because XOR operation will occur for every value twice except duplicate value which will comes three times. | |
console.log('Result = ', acutalXORResult^arrayXORResult); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment