That "return -1" in my solution is really just a last ditch effort to return something. If the array meets the specified condition of having exactly one value which is different, then it'll always end up returning that one value.
The key thing is what happens if someone used the function with the wrong array, e.g. an array with only zeros. In that case, the function would give you -1 rather than something else, but what it really should be doing is probably throwing an exception saying that the array doesn't have any different values in it.
So thinking again about it, I'd probably change my solution to have it throw an IllegalArgumentException complaining that the array doesn't have that one different value. Then either you get a value if the array meets the expected condition of having exactly one different value, or you get an exception complaining that you gave it a bad array.
ammm i saw your solution but what if there are an array with -1 as the unique number. you would have -1 either ways so how would you know if the -1 represent no unique number or actually the unique number?
You don't need to sort - that's O(n log n) at best. A single linear scan will give you the unique number.
really ? hahaha, ok if massive will be 1000000?
I like how you multiply the result by 256 before adding the parsed value.
I shifted my parsed value and then added it to the result.
Your solution looks way nicer :)
This is a bad solution, it only looks nice. performance wise this is below PAR. Why the hell we need to sort while we can go through the array only once up untill we get the unique.
After i spent a while programming my own solution, I am astonished about these two lines. I think this is near to the optimal solution.
Venkat Subramaniam has many excellent videos on Java streams on YouTube.
Watching him build from simple examples really helped me understand Streams API.
It is not actually. It is more my stupid mistake for saying that in the end of my comment ;P. As you can see the first reply to my comment explains that I am wrong in a funny way :D.
Again sorry for the last part of my comment and thanks for the reply.
How is this O(n/2) if you're still doing ~n comparisons? The loop runs n/2 times but you do 2 comparisons per loop. O(n) is still great though, better than sorting
that's the ternary operator EDIT: note that the second option is a recursive call (!)
Can someone explain what is happening after the return statement? with the question mark?
This solution is mind blowing for me. Smart!
I mean no matter how many times you run the test, there will be still a marginal chance that the code fails to identify whether the number is prime or composite. That is just the nature of probabilistic prime checking.