What I can think of is:
Algo:
Can you guys think of solution better than this. With O(n) runtime and using no extra space
Multiply the array element at that given value (index) with a negative number say -1. If a number have appeared once then the value in the array at that index will be negative else it will be positive if it has appeared twice (-1 * -1 = 1).
The best solution is to use XOR. XOR of all array elements gives us the number with a single occurrence.
To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff. Now increment the diff as the difference is increased now. Repeat from step 2 until all the missing numbers are not found.
Finding the non repeating element in an array can be done in 2 different ways. Method 1: Use two loops, one for the current element and the other to check if the element is already present in the array or not. Method 2: Traverse the array and insert the array elements and their number of occurences in the hash table.
Assuming you can XOR
the numbers, that is the key here, I believe, because of the following properties:
XOR
is commutative and associative (so the order in which it's done is irrelevant).XOR
ed with itself will always be zero.XOR
ed with a number will be that number.So, if you simply XOR
all the values together, all of the ones that occur twice will cancel each other out (giving 0) and the one remaining number (n
) will XOR
with that result (0) to give n
.
r = 0
for i = 1 to n.size:
r = r xor n[i]
print "number is " + r
No hash table needed, this has O(n) performance and O(1) extra space (just one tiny little integer).
An answer in Ruby, assuming one singleton, and all others exactly two appearances:
def singleton(array)
number = 0
array.each{|n| number = number ^ n}
number
end
irb(main):017:0> singleton([1, 2, 2, 3, 1])
=> 3
^ is the bitwise XOR operator, by the way. XOR everything! HAHAHAH!
Rampion has reminded me of the inject method, so you can do this in one line:
def singleton(array) array.inject(0) { |accum,number| accum ^ number }; end
"Parse the array and increment the count for number."
You could change this to "Parse the array and if the number already exists in the hash table, remove the number from the hash table". Then step 3 is just "get the only number that remains in the hash table"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With