/ CPP program to find the only repeating // element in an array where elements…
2025
/ CPP program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
int findRepeating(int arr[], int n)
{
// Find array sum and subtract sum
// first n-1 natural numbers from it
// to find the result.
return accumulate(arr , arr+n , 0) -
((n - 1) * n/2);
}
// driver code
int main()
{
int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findRepeating(arr, n);
return 0;
}
Answer: A. 8 — To find the only repeating element in an array where elements are from 1 to n-1, we use the following approach: Step 1: Calculate the sum of all elements in…
- A.
8
- B.
0
- C.
10
- D.
9
Attempted by 182 students.
Show answer & explanation
Correct answer: A
To find the only repeating element in an array where elements are from 1 to n-1, we use the following approach:
Step 1: Calculate the sum of all elements in the array.
Step 2: Calculate the sum of the first (n-1) natural numbers using the formula: (n-1) * n / 2.
Step 3: Subtract the sum of first (n-1) natural numbers from the array sum. The result is the repeating element.
In the given array: {9, 8, 2, 6, 1, 8, 5, 3, 4, 7}, n = 10.
Array sum = 9 + 8 + 2 + 6 + 1 + 8 + 5 + 3 + 4 + 7 = 53.
Sum of first 9 natural numbers = (9 * 10) / 2 = 45.
Repeating element = 53 - 45 = 8.
हिन्दी उत्तर:
एक ऐसे अर्रे में जहाँ तत्व 1 से n-1 तक हैं और एक तत्व दोहराया गया है, दोहराए गए तत्व को खोजने के लिए निम्नलिखित तरीका उपयोग किया जाता है:
चरण 1: अर्रे में सभी तत्वों का योग निकालें।
चरण 2: (n-1) प्राकृतिक संख्याओं के योग की गणना करें, जिसका सूत्र है: (n-1) * n / 2।
चरण 3: प्राकृतिक संख्याओं के योग को अर्रे के योग से घटाएं। परिणाम दोहराए गए तत्व है।
दिए गए अर्रे में: {9, 8, 2, 6, 1, 8, 5, 3, 4, 7}, n = 10।
अर्रे का योग = 9 + 8 + 2 + 6 + 1 + 8 + 5 + 3 + 4 + 7 = 53।
पहले 9 प्राकृतिक संख्याओं का योग = (9 * 10) / 2 = 45।
दोहराए गए तत्व = 53 - 45 = 8।