Yahoo Interview Question
Software Engineer / DevelopersTeam: Ad
Country: United States
Interview Type: In-Person
a = [1,2,34,545,334,53,534,56,7,4,3,1]
def findDup():
d = {}
for i in a:
print d
try:
d[i] = d[i] + 1
if d[i] > 1:
return True
else:
continue
except:
d[i] = 1
continue
else:
continue
return False
print findDup()
If you are doing it in Python, might as well do it in Pythonic way :P
(Use collections.Counter)
import collections
def findDup(a):
d = collections.Counter(a)
for key, value in d.items():
if value > 1:
return True
return False
a = [1, 2, 34, 545, 334, 53, 534, 56, 7, 4, 3, 1]
print findDup(a)
var findDuplicatedItems = (function() {
var obj = {}, result = [],
len = 0;
return {
getDup: function(arrData) {
len = arrData.length;
for(var i = 0; i < len; i++) {
if (obj[arrData[i]]) result.push(arrData[i]);
else obj[arrData[i]] = true;
}
console.log(result);
}
};
})();
var arr = [1, 2, 3, 4, 77, 54, 3, 57, 2, 99, 54];
findDuplicatedItems.getDup(arr);
If the array has exactly 0 or 1 duplicate then it can be found in O(N) time and O(1) space complexity if it is an array of char or int.
Step1 : Sum the array .If it is char array convert to ascii no and sum the array up.
Step 2: XOR the array and compare this value with sum from step 1.
if (sum from step1 == sum from step2) {
return no duplicates
}
else {
return ascii (step1 - step2)/2;
}
This can be done using a Set. We will put one element from the array at a time in the Set. If the add operation returns false then it means that element was already present in the Set and thus is a duplicate.
- SumitGaur March 20, 2014