How to find the missing number and the repeated number in a sorted array without using any inbuilt functions using C#?
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.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 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(); } } } |