Saturday, September 24, 2022

Missing number in array

Problem:

Given an array of size N-1 such that it only contains distinct integers in the range of 1 to N. Find the missing element.

Example 1:

Input:
N = 5
A[] = {1,2,3,5}
Output: 4

My Answer:

    int MissingNumber(int array[], int n) {
        // Your Code Here
        int sumN = 0;
        int sumArr = 0;
        
        for(int i=1 ; i <= n ; i++) {
            sumN = sumN + i;
        }
        
        for (int j=0 ; j < n-1 ; j++ ) {
            sumArr = sumArr + array[j];
        }
        
        return sumN - sumArr;
    }

No comments:

Post a Comment

Search in a matrix

  Problem: Given a matrix  mat [][] of size  N  x  M , where every row and column is sorted in increasing order, and a number  X  is given. ...