Question
This time I want to concider an exercise which Amazon gave on interviews several years ago. I have no proof links on this information, so let’s imagine that previous sentence is truth. Are you ready for the logical task? Let’s start.

You must find a missing number in an array. The array consists of numbers from 1 to 10 in random sequence. But this is not all… One of the numbers in the array is absent and you must find it. So, you can start solving the problem… But, no! Wait a minute. There is one more important constraint – you can use not more then one loop. Good luck =)

Here are some examples:

  • 5,6,9,4,1,2,8,3,10 – the result will be: 7
  • 2,10,4,5,6,7,8,9,3 – the result will be: 1
  • 1,3,2,6,5,7,8,10,9 – the result will be: 4

Here is my solution:

...
	public static void main(String[] args) {
		
		int[] arr = {10,9,3,6,4,7,8,1,2};
		int length = arr.length;
		
		int indexes = 10;
		int values = 0;
		
		for (int i = 0; i < length; i++) {
			indexes += i+1;
			values += arr[i];
		}
		
		int result = indexes - values;
		
		System.out.println("Missing number is: "+result);
	}
...

Try to solve this exercise by yourself. It will be great to see more efficient solution in the comments.
Don't forget to like my blog on FaceBook.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

Close