What is the best way to check that all numbers in the array (or list) are equal?
I think the solution as a loop that seek for the first unequal element ist maybe efficient, but not so elegant or readable. Any solutions in one line?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Any solution to this problem must run in Ω(n) time and make Ω(n) comparisons, since if this isn’t the case for some sufficiently large array you wouldn’t be able to look at all the elements to check that they have the same value.
Doing a linear scan of the array looking for any values different from the first one is perhaps the absolute best way to solve this problem. It makes a total of (n – 1) comparisons, which asymptotically matches the lower bound, and is both elegant and easy to implement.