How to find the missing number and the repeated number in a sorted array without using any inbuilt functions using C#?

CsharpServer Side ProgrammingProgramming

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
raja
Published on 27-Aug-2021 12:45:49
Advertisements