The problem is extended from Finding a single number in a list
If I extend the problem to this: What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly k times?
Does anyone have good answer?
for example, A = { 1, 2, 3, 4, 2, 3, 1, 2, 1, 3 }, in this case, k = 3. How can I get the single number "4" in O(n) time and the space complexity is O(1)?
count() It returns the occurrence count of element in the list. Here we are iterating over all the elements of list and check count of each element in the list. If count > 1 then it means this element has duplicate entries.
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).
Expert-verified answer List objects needn't be unique, a given object can appear in a list multiple times.
If every element in the array is less n and greater than 0.
Let the array be a, traverse the array for each a[i]
add n
to a[(a[i])%(n)]
.
Now traverse the array again, the position at which a[i]
is less than 2*n
and greater than n
(assuming 1 based index) is the answer.
This method won't work if at least on element is greater than n. In that case you have to use method suggested by Jayram
EDIT:
To retrieve the array just apply mod n
to every element in the array
This can be solved in given with your constraints if the numbers other than lonely number
are occurring exactly in even count (i.e. 2, 4, 6, 8...) by doing the XOR
operation on all the numbers.
But other than this in space complexity O(1)
its just teasing me.
If other than your given constraints you could use these approaches to solve this.
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