Find Missing And Repeating(Amazon D-E-Shaw Goldman Sachs MAQ Software Samsung)

Suman Barik
0
// C++ program to find the missing
// and repeating element
#include <bits/stdc++.h>
using namespace std;

void getTwoElements(int arr[], int n)
{
int repeating(0), missing(0);

int i = 0;

// Traverse on the array
while (i < n)
{
// If the element is on its correct position
if (arr[i] == arr[arr[i] - 1])
i++;
// If it is not at its correct position
// then palce it to its correct position
else
swap(arr[i], arr[arr[i] - 1]);
}

// Find repeating and missing
for (int i = 0; i < n; i++) {
// If any element is not in its correct position
if (arr[i] != i + 1) {
repeating = arr[i];
missing = i + 1;
break;
}
}

// Print answer
cout << "Repeating: " << repeating << endl
<< "Missing: " << missing << endl;
}

// Driver code
int main()
{
int arr[] = { 2, 3, 1, 5, 1 };
int n = sizeof(arr) / sizeof(int);

getTwoElements(arr, n);

return 0;
}

// This code is contributed by Tapesh (tapeshdua420)

Tags

Post a Comment

0Comments
Post a Comment (0)