Find Missing and Repeated Number in Sorted Array



To find the missing number

Create a new array and traverse through the entire array and make the number true in the new array if the number is found Traverse through the entire array and return the first false element as the missing element.

To find the repeating element

The first true element from the new array will be the repeated element.

Example

 Live Demo

using System;
namespace ConsoleApplication{
   public class Arrays{
      public void MissingNumberAndRepeatedNumber(int[] arr){
         bool[] tempArray = new bool[arr.Length + 1];
         int missingelement = -1;
         int repeatingelement = -1;
         for (int i = 0; i < arr.Length; i++){
            int index = arr[i];
            if (!tempArray[index]){
               tempArray[index] = true;
            }
         };
         for (int i = 0; i < tempArray.Length; i++){
            if (!tempArray[i]){
               missingelement = i;
               break;
            }
         }
         int[] tempArray1 = new int[arr.Length + 1];
         for (int i = 0; i < arr.Length; i++){
            int index = arr[i];
            if (tempArray1[index]==0){
               tempArray1[index] = 1;
         }else if (tempArray1[index]==1){
            tempArray1[index] = 2;
      }
   };
   for (int i = 0; i < tempArray1.Length; i++){
         if (tempArray1[i]==2){
            repeatingelement = i;
            break;
         }
      }
      Console.WriteLine(missingelement);
      Console.WriteLine(repeatingelement);
   }
}
class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         int[] arr = { 0, 1, 1, 3, 4 };
         a.MissingNumberAndRepeatedNumber(arr);
         Console.ReadLine();
      }
   }
}

Output

2
1
Updated on: 2021-08-27T12:55:06+05:30

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements