If I have an randomly shuffled array with the numbers 1 to n, what is a good way to find that the array contains the range 1 to n (no repeats)? For example,
n = 6; [1, 3, 6, 2, 4, 5] => true
n = 6; [1, 1, 2, 4, 5, 6] => false
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.
Make an array of size n, pass through your array and increment the position in the array with that as an index. If at any time the counts array has non 0 or non 1 value, you can stop. If you can’t find the index, you can stop now since you know you don’t have it.
Here’s a quick Java example. In this example, you do not need to count at the end because anything that would cause a non-1 value would cause a failure during the middle.