Program to find the first repeating element in an array of integers in C++

C++ program to find the first repeating element in an array of integers

Example:

Input: {5, 15, 20, 5, 6, 10, 15, 10}

Output: 5

# Algorithm

  1. Take an array as input and store its size in a variable n.
  2. Start a loop from i = 0 to i < n, which will select each element from the array.
  3. Inside the loop, start a second loop from j = i + 1 to j < n to traverse ahead and check for duplicates.
  4. If a duplicate is found (i.e., array[i] is equal to array[j]), print the first repeating integer and return 0.
  5. Else, print "No integer repeated".

Code:

#include <bits/stdc++.h>
using namespace std;

int main() {
   int array[100], n, i;
   cout << "Enter number of elements: ";
   cin >> n;
   cout << "\nEnter elements: ";
   for (i = 0; i < n; i++)
      cin >> array[i];

   cout << "Original array: ";

   for (int i = 0; i < n; i++)
      cout << array[i] << " ";

   // selecting an element

   for (int i = 0; i < n; i++)
      // traversing to check repetition
      for (int j = i + 1; j < n; j++)
         if (array[i] == array[j]) {
            cout << "\nFirst repeating integer is " << array[i];
            return 0;
         }

   cout << "No integer repeated\n";
   return 0;
}

Output

Enter number of elements: 5

Enter elements: 1 2 3 4 5
Original array: 1 2 3 4 5
No integer repeated

Time Complexity: O(N2)

Program to find the first repeating element in an array of integers in C++