Array Missing Number

Problem

Given an array of n-1 unique integers. Each element in the array is an integer between 1 and n. Write a program to print the missing number in the array

Solution

To clarify this problem let us take a simple example. Assume n = 3 so the array consists from two elements only. Here are some possible values of the array in the range 1 .. 3

Let us solve this problem using brute force first. We need two nested loops. The outer loop goes through all numbers between 1 and n while the inner loop searches the array for the outer loop current index. If it is found then you continue. If you do not find it then it is the missing number

Code

Here is the code in Perl

Solution

The brute force solution runs in O(nxn) but we can do better and solve this problem in linear time if we hash the array elements

Code

Here is we are going to do it in Perl

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *