The Wayback Machine - https://web.archive.org/web/20240928070500/https://www.geeksforgeeks.org/find-first-repeating-element-array-integers/
Open In App

Find the first repeating element in an array of integers

Last Updated : 06 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
32.57%
2.6L

Given an array of integers arr[], The task is to find the index of first repeating element in it i.e. the element that occurs more than once and whose index of the first occurrence is the smallest. 

Examples: 

Input: arr[] = {10, 5, 3, 4, 3, 5, 6}
Output: 5 
Explanation: 5 is the first element that repeats

Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}
Output: 6 
Explanation: 6 is the first element that repeats

Run two nested loops, the outer loop picks an element one by one, and the inner loop checks whether the element is repeated or not. Once a repeating element is found, break the loops and print the element.

C++




// Including necessary header files
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the index of first repeating element in
// an array
int firstRepeatingElement(int arr[], int n)
{
    // Nested loop to check for repeating elements
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            // If a repeating element is found, return its
            // index
            if (arr[i] == arr[j]) {
                return i;
            }
        }
    }
    // If no repeating element is found, return -1
    return -1;
}
 
// Driver code
int main()
{
    // Initializing an array and its size
    int arr[] = { 10, 5, 3, 4, 3, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // Finding the index of first repeating element
    int index = firstRepeatingElement(arr, n);
 
    // Checking if any repeating element is found or not
    if (index == -1) {
        cout << "No repeating element found!" << endl;
    }
    else {
        // Printing the first repeating element and its
        // index
        cout << "First repeating element is " << arr[index]
             << endl;
    }
 
    return 0;
}


Java




// Java code for the approach
 
import java.util.*;
 
public class GFG {
    // Function to find the index of first repeating element in an array
    public static int firstRepeatingElement(int[] arr, int n) {
        // Nested loop to check for repeating elements
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // If a repeating element is found, return its index
                if (arr[i] == arr[j]) {
                    return i;
                }
            }
        }
        // If no repeating element is found, return -1
        return -1;
    }
 
    // Driver code
    public static void main(String[] args) {
        // Initializing an array and its size
        int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
        int n = arr.length;
        // Finding the index of first repeating element
        int index = firstRepeatingElement(arr, n);
 
        // Checking if any repeating element is found or not
        if (index == -1) {
            System.out.println("No repeating element found!");
        }
        else {
            // Printing the first repeating element and its index
            System.out.println("First repeating element is " + arr[index]);
        }
    }
}


Python3




# Python3 code for the approach
 
# Function to find the index of first repeating element in an array
def firstRepeatingElement(arr, n):
  # Nested loop to check for repeating elements
  for i in range(n):
    for j in range(i+1, n):
      # If a repeating element is found, return its index
      if arr[i] == arr[j]:
        return i
       
  # If no repeating element is found, return -1
  return -1
 
# Driver code
if __name__ == '__main__':
  # Initializing an array and its size
  arr = [10, 5, 3, 4, 3, 5, 6]
  n = len(arr)
   
  # Finding the index of first repeating element
  index = firstRepeatingElement(arr, n)
   
  # Checking if any repeating element is found or not
  if index == -1:
      print("No repeating element found!")
  else:
      # Printing the first repeating element and its index
      print("First repeating element is", arr[index])


C#




using System;
 
public class Program
{
    public static void Main()
    {
        // Initializing an array and its size
        int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
        int n = arr.Length;
 
        // Initializing variables to keep track of the minimum index and
        // minimum value of the repeating element
        int minIndex = n;
        int minValue = int.MaxValue;
 
        // Creating a dictionary to store the last seen index of each element
        var dict = new System.Collections.Generic.Dictionary<int, int>();
 
        // Iterating over the array from left to right
        for (int i = 0; i < n; i++)
        {
            int val = arr[i];
 
            // If the element is not in the dictionary, add it with its index
            if (!dict.ContainsKey(val))
            {
                dict[val] = i;
            }
            // If the element is already in the dictionary, update the minimum index
            // and minimum value if necessary
            else
            {
                int index = dict[val];
                if (index < minIndex || (index == minIndex && val < minValue))
                {
                    minIndex = index;
                    minValue = val;
                }
            }
        }
 
        // Checking if any repeating element is found or not
        if (minIndex == n)
        {
            Console.WriteLine("No repeating element found!");
        }
        else
        {
            // Printing the first repeating element and its index
            Console.WriteLine("First repeating element is " + minValue + " at index " + minIndex);
        }
    }
}


Javascript




function firstRepeatingElement(arr) {
    // Nested loop to check for repeating elements
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            // If a repeating element is found, return its index
            if (arr[i] === arr[j]) {
                return i;
            }
        }
    }
    // If no repeating element is found, return -1
    return -1;
}
 
// Driver code
const arr = [10, 5, 3, 4, 3, 5, 6];
// Finding the index of first repeating element
const index = firstRepeatingElement(arr);
 
// Checking if any repeating element is found or not
if (index === -1) {
    console.log("No repeating element found!");
} else {
    // Printing the first repeating element and its index
    console.log("First repeating element is", arr[index]);
}


Output

First repeating element is 5

Time Complexity: O(N2)
Auxiliary Space: O(1)

Find the first repeating element in an array of integers using sorting:

Below is the idea to solve the problem.

Store the elements of arr[] in a duplicate array temp[], sort temp[] and traverse arr[] from 0 to N – 1, Simultaneously check the count of this element in temp[] and if the current element arr[i] has more than one occurrence then return arr[i].

Follow the steps below to Implement the idea: 

  • Copy the given array to an auxiliary array temp[] and sort temp array. 
  • Traverse the input array arr[] from 0 to N – 1. 
  • If no repeating element is found print “No Repeating Number Found”.

Time complexity: O(NlogN).
Auxiliary Space: O(N)

Find the first repeating element in an array of integers using Hashset

Below is the idea to solve the problem

The idea is to traverse the given array arr[] from right to left and update the minimum index whenever, an already visited element has been found. To check if the element was already visited Hashset can be used. 

Follow the steps below to implement the idea:

  • Initialize an empty Hashset myset and a variable min with -1.  
  • Run a for loop for each index of array arr[] from N – 1 to 0.
    • If the current element is present in myset then update min with i.
    • Else insert arr[i] in myset. 
  • Return min.

Below is the implementation of the above approach.

C++




/* C++ program to find first repeating element in arr[] */
#include <bits/stdc++.h>
using namespace std;
 
// This function prints the first repeating element in arr[]
void printFirstRepeating(int arr[], int n)
{
    // Initialize index of first repeating element
    int min = -1;
 
    // Creates an empty hashset
    set<int> myset;
 
    // Traverse the input array from right to left
    for (int i = n - 1; i >= 0; i--) {
        // If element is already in hash set, update min
        if (myset.find(arr[i]) != myset.end())
            min = i;
 
        else // Else add element to hash set
            myset.insert(arr[i]);
    }
 
    // Print the result
    if (min != -1)
        cout << "The first repeating element is "
             << arr[min];
    else
        cout << "There are no repeating elements";
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 5, 3, 4, 3, 5, 6 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
    printFirstRepeating(arr, n);
}
// This article is contributed by Chhavi


Java




/* Java program to find first repeating element in arr[] */
import java.util.*;
 
class Main {
    // This function prints the first repeating element in
    // arr[]
    static void printFirstRepeating(int arr[])
    {
        // Initialize index of first repeating element
        int min = -1;
 
        // Creates an empty hashset
        HashSet<Integer> set = new HashSet<>();
 
        // Traverse the input array from right to left
        for (int i = arr.length - 1; i >= 0; i--) {
            // If element is already in hash set, update min
            if (set.contains(arr[i]))
                min = i;
 
            else // Else add element to hash set
                set.add(arr[i]);
        }
 
        // Print the result
        if (min != -1)
            System.out.println(
                "The first repeating element is "
                + arr[min]);
        else
            System.out.println(
                "There are no repeating elements");
    }
 
    // Driver method to test above method
    public static void main(String[] args)
        throws java.lang.Exception
    {
        int arr[] = { 10, 5, 3, 4, 3, 5, 6 };
        printFirstRepeating(arr);
    }
}


Python3




# Python3 program to find first repeating
# element in arr[]
 
# This function prints the first repeating
# element in arr[]
 
 
def printFirstRepeating(arr, n):
 
    # Initialize index of first repeating element
    Min = -1
 
    # Creates an empty hashset
    myset = dict()
 
    # Traverse the input array from right to left
    for i in range(n - 1, -1, -1):
 
        # If element is already in hash set,
        # update Min
        if arr[i] in myset.keys():
            Min = i
 
        else:  # Else add element to hash set
            myset[arr[i]] = 1
 
    # Print the result
    if (Min != -1):
        print("The first repeating element is",
              arr[Min])
    else:
        print("There are no repeating elements")
 
 
# Driver Code
arr = [10, 5, 3, 4, 3, 5, 6]
 
n = len(arr)
printFirstRepeating(arr, n)
 
# This code is contributed by Mohit kumar 29


C#




using System;
using System.Collections.Generic;
 
/* C# program to find first repeating element in arr[] */
 
public class GFG {
    // This function prints the first repeating element in
    // arr[]
    public static void printFirstRepeating(int[] arr)
    {
        // Initialize index of first repeating element
        int min = -1;
 
        // Creates an empty hashset
        HashSet<int> set = new HashSet<int>();
 
        // Traverse the input array from right to left
        for (int i = arr.Length - 1; i >= 0; i--) {
            // If element is already in hash set, update min
            if (set.Contains(arr[i])) {
                min = i;
            }
 
            else // Else add element to hash set
            {
                set.Add(arr[i]);
            }
        }
 
        // Print the result
        if (min != -1) {
            Console.WriteLine(
                "The first repeating element is "
                + arr[min]);
        }
        else {
            Console.WriteLine(
                "There are no repeating elements");
        }
    }
 
    // Driver method to test above method
 
    public static void Main(string[] args)
    {
        int[] arr = new int[] { 10, 5, 3, 4, 3, 5, 6 };
        printFirstRepeating(arr);
    }
}
 
// This code is contributed by Shrikant13


Javascript




<script>
 
// Javascript program to find first
// repeating element in arr[]
     
// This function prints the first
// repeating element in arr[]
function  printFirstRepeating(arr)
{
     
    // Initialize index of first
    // repeating element
    let min = -1;
 
    // Creates an empty hashset
    let set = new Set();
 
    // Traverse the input array from right to left
    for(let i = arr.length - 1; i >= 0; i--)
    {
         
        // If element is already in
        // hash set, update min
        if (set.has(arr[i]))
            min = i;
             
        // Else add element to hash set
        else 
            set.add(arr[i]);
    }
 
    // Print the result
    if (min != -1)
      document.write("The first repeating element is " +
                     arr[min]);
    else
      document.write("There are no repeating elements");
}
 
// Driver code
let arr = [ 10, 5, 3, 4, 3, 5, 6 ];
 
printFirstRepeating(arr);
 
// This code is contributed by unknown2108
     
</script>


Output

The first repeating element is 5

Time Complexity: O(n).
Auxiliary Space: O(n).

Thanks to Mohammad Shahid for suggesting this solution.

Find the first repeating element in an array of integers using Hashing 

The idea is to use Hash array to store the occurrence of elements. Then traverse the array from left to right and return the first element with occurrence more than 1.

Follow the below steps to implement the idea:

  • Initialize variables k with 0, max with -1 and min with max + 1 and iterate over all values of arr[] to store the largest value in max.
  • Initialize a Hash arrays a[] and b[] of size max + 1.
  • Run a for loop from 0 to N – 1
    • If a[arr[i]] is 0 put i+1 in place of a[arr[i]].
    • Else assign 1 to b[arrr[i]] and k.
  • If k is 0 print “No repeating element found”.
  • Else iterate from 0 to max 
    • If a[i] is not zero and b[i] is not zero and min is greater than a[i] then update min a[i].
  • Print min.

Below is the Implementation of above approach 

C++




/* C++ program to find first
repeating element in arr[] */
#include <bits/stdc++.h>
using namespace std;
 
// This function prints the
// first repeating element in arr[]
void printFirstRepeating(int arr[], int n)
{
 
    // This will set k=1, if any
    // repeating element found
    int k = 0;
 
    // max = maximum from (all elements & n)
    int max = n;
    for (int i = 0; i < n; i++)
        if (max < arr[i])
            max = arr[i];
 
    // Array a is for storing
    // 1st time occurrence of element
    // initialized by 0
    int a[max + 1] = {};
 
    // Store 1 in array b
    // if element is duplicate
    // initialized by 0
    int b[max + 1] = {};
 
    for (int i = 0; i < n; i++) {
 
        // Duplicate element found
        if (a[arr[i]]) {
            b[arr[i]] = 1;
            k = 1;
            continue;
        }
        else
            // storing 1st occurrence of arr[i]
            a[arr[i]] = i + 1;
    }
 
    if (k == 0)
        cout << "No repeating element found" << endl;
    else {
        int min = max + 1;
 
        // trace array a & find repeating element
        // with min index
        for (int i = 0; i < max + 1; i++)
            if (a[i] && min > a[i] && b[i])
                min = a[i];
        cout << arr[min - 1];
    }
    cout << endl;
}
 
// Driver method to test above method
int main()
{
    int arr[] = { 10, 5, 3, 4, 3, 5, 6 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
    printFirstRepeating(arr, N);
}


Java




/* Java program to find first
repeating element in arr[] */
public class GFG {
 
    // This function prints the
    // first repeating element in arr[]
    static void printFirstRepeating(int[] arr, int n)
    {
 
        // This will set k=1, if any
        // repeating element found
        int k = 0;
 
        // max = maximum from (all elements & n)
        int max = n;
        for (int i = 0; i < n; i++)
            if (max < arr[i])
                max = arr[i];
 
        // Array a is for storing
        // 1st time occurrence of element
        // initialized by 0
        int[] a = new int[max + 1];
 
        // Store 1 in array b
        // if element is duplicate
        // initialized by 0
        int[] b = new int[max + 1];
        for (int i = 0; i < n; i++) {
 
            // Duplicate element found
            if (a[arr[i]] != 0) {
                b[arr[i]] = 1;
                k = 1;
                continue;
            }
            else
                // storing 1st occurrence of arr[i]
                a[arr[i]] = i + 1;
        }
 
        if (k == 0)
            System.out.println(
                "No repeating element found");
        else {
            int min = max + 1;
 
            // trace array a & find repeating element
            // with min index
            for (int i = 0; i < max + 1; i++)
                if (a[i] != 0 && min > a[i] && b[i] != 0)
                    min = a[i];
            System.out.print(arr[min - 1]);
        }
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
 
        int N = arr.length;
        printFirstRepeating(arr, N);
    }
}
 
// This code is contributed by divyesh072019


Python3




# Python3 program to find first
# repeating element in arr[]
 
# This function prints the
# first repeating element in arr[]
 
 
def printFirstRepeating(arr, n):
 
    # This will set k=1, if any
    # repeating element found
    k = 0
 
    # max = maximum from (all elements & n)
    max = n
 
    for i in range(n):
        if (max < arr[i]):
            max = arr[i]
 
    # Array a is for storing
    # 1st time occurrence of element
    # initialized by 0
    a = [0 for i in range(max + 1)]
 
    # Store 1 in array b
    # if element is duplicate
    # initialized by 0
    b = [0 for i in range(max + 1)]
 
    for i in range(n):
 
        # Duplicate element found
        if (a[arr[i]]):
            b[arr[i]] = 1
            k = 1
            continue
        else:
 
            # Storing 1st occurrence of arr[i]
            a[arr[i]] = i+1
 
    if (k == 0):
        print("No repeating element found")
    else:
        min = max + 1
 
        for i in range(max + 1):
 
            # Trace array a & find repeating
            # element with min index
            if (a[i] and (min > (a[i])) and b[i]):
                min = a[i]
 
        print(arr[min-1])
 
 
# Driver code
arr = [10, 5, 3, 4, 3, 5, 6]
N = len(arr)
 
printFirstRepeating(arr, N)
 
# This code is contributed by avanitrachhadiya2155


C#




/* C# program to find first
repeating element in arr[] */
using System;
class GFG {
 
    // This function prints the
    // first repeating element in arr[]
    static void printFirstRepeating(int[] arr, int n)
    {
 
        // This will set k=1, if any
        // repeating element found
        int k = 0;
 
        // max = maximum from (all elements & n)
        int max = n;
        for (int i = 0; i < n; i++)
            if (max < arr[i])
                max = arr[i];
 
        // Array a is for storing
        // 1st time occurrence of element
        // initialized by 0
        int[] a = new int[max + 1];
 
        // Store 1 in array b
        // if element is duplicate
        // initialized by 0
        int[] b = new int[max + 1];
 
        for (int i = 0; i < n; i++) {
 
            // Duplicate element found
            if (a[arr[i]] != 0) {
                b[arr[i]] = 1;
                k = 1;
                continue;
            }
            else
                // storing 1st occurrence of arr[i]
                a[arr[i]] = i + 1;
        }
 
        if (k == 0)
            Console.WriteLine("No repeating element found");
        else {
            int min = max + 1;
 
            // trace array a & find repeating element
            // with min index
            for (int i = 0; i < max + 1; i++)
                if ((a[i] != 0) && min > a[i]
                    && (b[i] != 0))
                    min = a[i];
            Console.Write(arr[min - 1]);
        }
        Console.WriteLine();
    }
 
    // Driver code
    static void Main()
    {
        int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
 
        int N = arr.Length;
        printFirstRepeating(arr, N);
    }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




<script>
/* javascript program to find first
repeating element in arr */
  
 
    // This function prints the
    // first repeating element in arr
    function printFirstRepeating(arr , n) {
 
        // This will set k=1, if any
        // repeating element found
        var k = 0;
 
        // max = maximum from (all elements & n)
        var max = n;
        for (i = 0; i < n; i++)
            if (max < arr[i])
                max = arr[i];
 
        // Array a is for storing
        // 1st time occurrence of element
        // initialized by 0
        var a = Array(max + 1).fill(0);
 
        // Store 1 in array b
        // if element is duplicate
        // initialized by 0
        var b = Array(max + 1).fill(0);
        for (var i = 0; i < n; i++) {
 
            // Duplicate element found
            if (a[arr[i]] != 0) {
                b[arr[i]] = 1;
                k = 1;
                continue;
            } else
                // storing 1st occurrence of arr[i]
                a[arr[i]] = i+1;
        }
 
        if (k == 0)
            document.write("No repeating element found");
        else {
            var min = max + 1;
 
            // trace array a & find repeating element
            // with min index
            for (i = 0; i < max + 1; i++)
                if (a[i] != 0 && min > a[i] && b[i] != 0)
                    min = a[i];
            document.write(arr[min-1]);
        }
        document.write("<br/>");
    }
 
    // Driver code
     
        var arr = [ 10, 5, 3, 4, 3, 5, 6 ];
 
        var N = arr.length;
        printFirstRepeating(arr, N);
 
// This code is contributed by todaysgaurav
</script>


Output

5

Time Complexity: O(N).
Auxiliary Space: O(N).

Another approach using single hash array

Follow the below steps to implement the idea:

  • Initialize a variable max to -1 to keep track of the maximum value in the array.
  • Iterate over all values of arr[] to store the largest value in max.
  • Declare an integer array hash of size max+1 and initialize all its elements to 0. This array will be used as a hash table to store the count of occurrences of each element in the input array.
  • Traverse the input array again from index 0 to n-1, and increment the count of the corresponding element in the hash table.
  • Traverse the input array again from index 0 to n-1, and for each element in the input array, check if the count of the corresponding element in the hash table is greater than 1. If it is, return the index of that element in the input array (i.e., i+1, since the function is expected to return a 1-based index). If no repeated element is found, the function returns -1.

Below is the Implementation of above approach 

C++




/* C++ program to find first
repeating element in arr[] */
#include <bits/stdc++.h>
using namespace std;
 
// This function prints the
// first repeating element in arr[]
void firstRepeating(int arr[], int n) {
     
        int max = -1;
          //Finding max
        for(int i = 0 ; i<n;i++){
           if(max<arr[i]){
               max = arr[i];
           }
        }
         
        //Creating array
        int hash[max+1]={0};
         
        //Mapping/counting
        for(int i =0;i<n; i++){
            hash[arr[i]]++;
        }
        //Variable for storing ans
          int repeating=INT_MIN;
        //Checking repeatibng element
        for(int i =0;i<n; i++){
            if(hash[arr[i]]>1){
                repeating=arr[i];
                  break;
            }
        }
          if(repeating==INT_MIN){
          cout << "There are no repeating elements";
        }
          else{
          cout << "The first repeating element is : "
             <<repeating;
        }
    }
 
// Driver method to test above method
int main()
{
    int arr[] = { 10, 5, 3, 4, 3, 5, 6 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
    firstRepeating(arr, N);
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
      static void firstRepeating(int[] arr, int n) {
        int max = -1;
        // Finding max
        for (int i = 0; i < n; i++) {
            if (max < arr[i]) {
                max = arr[i];
            }
        }
 
        // Creating array
        int[] hash = new int[max + 1];
 
        // Mapping/counting
        for (int i = 0; i < n; i++) {
            hash[arr[i]]++;
        }
 
        // Checking for repeating element
        int repeating = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            if (hash[arr[i]] > 1) {
                repeating = arr[i];
                break;
            }
        }
 
        if (repeating == Integer.MIN_VALUE) {
            System.out.println("There are no repeating elements");
        } else {
            System.out.println("The first repeating element is : " + repeating);
        }
    }
    public static void main (String[] args) {
        int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
        int N = arr.length;
        firstRepeating(arr, N);
    }
}


Python3




# Python program to find first repeating element in arr[]
def firstRepeating(arr, n):
    # Finding max
    max_val = max(arr)
     
    # Creating array
    hash = [0] * (max_val+1)
     
    # Mapping/counting
    for i in range(n):
        hash[arr[i]] += 1
     
    # Variable for storing ans
    repeating = float('inf')
     
    # Checking repeating element
    for i in range(n):
        if hash[arr[i]] > 1:
            repeating = arr[i]
            break
     
    if repeating == float('inf'):
        print("There are no repeating elements")
    else:
        print("The first repeating element is:", repeating)
 
# Driver method to test above method
arr = [10, 5, 3, 4, 3, 5, 6]
N = len(arr)
firstRepeating(arr, N)


C#




// C# program to find first
// repeating element in arr[]
using System;
 
public class Program
{
 
  // This function prints the
  // first repeating element in arr[]
  public static void FirstRepeating(int[] arr, int n)
  {
    int max = -1;
     
    // Finding max
    for (int i = 0; i < n; i++) {
      if (max < arr[i]) {
        max = arr[i];
      }
    }
 
    // Creating array
    int[] hash = new int[max + 1];
 
    // Mapping/counting
    for (int i = 0; i < n; i++) {
      hash[arr[i]]++;
    }
 
    // Variable for storing ans
    int repeating = int.MinValue;
 
    // Checking repeating element
    for (int i = 0; i < n; i++) {
      if (hash[arr[i]] > 1) {
        repeating = arr[i];
        break;
      }
    }
 
    if (repeating == int.MinValue) {
      Console.WriteLine(
        "There are no repeating elements");
    }
    else {
      Console.WriteLine(
        "The first repeating element is: "
        + repeating);
    }
  }
 
  // Driver method to test above method
  public static void Main()
  {
    int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
    int n = arr.Length;
    FirstRepeating(arr, n);
  }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




function firstRepeating(arr, n) {
    // Finding max
    let max_val = Math.max(...arr);
 
    // Creating array
    let hash = new Array(max_val + 1).fill(0);
 
    // Mapping/counting
    for (let i = 0; i < n; i++) {
        hash[arr[i]] += 1;
    }
 
    // Variable for storing ans
    let repeating = Infinity;
 
    // Checking repeating element
    for (let i = 0; i < n; i++) {
        if (hash[arr[i]] > 1) {
            repeating = arr[i];
            break;
        }
    }
 
    if (repeating == Infinity) {
        console.log("There are no repeating elements");
    } else {
        console.log("The first repeating element is:", repeating);
    }
}
 
// Driver method to test above method
let arr = [10, 5, 3, 4, 3, 5, 6];
let N = arr.length;
firstRepeating(arr,N);


Output

The first repeating element is : 5

Time Complexity: O(N).
Auxiliary Space: O(N).

The first for loop that finds the maximum element in the array has a time complexity of O(n). The second for loop that creates a hash array has a time complexity of O(n). The third for loop that checks for the first repeating element also has a time complexity of O(n). The array named ‘hash’ is created with max+1 elements so space O(max+1).

Since all three loops run sequentially, the total time complexity of the code is O(n).



Previous Article
Next Article

Similar Reads

Find first non-repeating element in a given Array of integers
Given an array of integers of size N, the task is to find the first non-repeating element in this array. Examples: Input: {-1, 2, -1, 3, 0}Output: 2Explanation: The first number that does not repeat is : 2 Input: {9, 4, 9, 6, 7, 4}Output: 6 Recommended ProblemNon-Repeating ElementSolve Problem Simple Solution is to use two loops. The outer loop pic
9 min read
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Find the repeating element in an Array of size N consisting of first M natural numbers
Given an array arr[] of size N, which contains a permutation of numbers from 1 to M, as well as an element that is repeated(one or more times), the task is to find the repeating element. Examples: Input: arr[]={2, 6, 4, 3, 1, 5, 2}, N=7Output:2Explanation: In arr[], all elements from 0 to 6 occurs once, except 2 which is repeated once. Input: arr[]
8 min read
Design a structure which supports insertion and first non-repeating element in O(1) time
Design a Data structure which supports insertion and first non-repeating element in O(1) time. Operations that are supported by the data structure: Insertion: Insert a element into the data structure.First non-repeating Element: First non-repeating element into the array. Note: If there is no non-repeating element in the array then print -1. Consid
12 min read
Maximize first element of Array by deleting first or adding a previously deleted element
Given an array arr[] of size N, and an integer K, the task is to maximize the first element of the array in K operations where in each operation: If the array is not empty, remove the topmost element of the array.Add any one of the previously removed element back at the starting of the array. Examples: Input: arr[] = [5, 2, 2, 4, 0, 6], K = 4Output
7 min read
Find the only non-repeating element in a given array
Given an array A[] consisting of N (1 ? N ? 105) positive integers, the task is to find the only array element with a single occurrence. Note: It is guaranteed that only one such element exists in the array. Examples: Input: A[] = {1, 1, 2, 3, 3}Output: 2Explanation: Distinct array elements are {1, 2, 3}. Frequency of these elements are {2, 1, 2} r
11 min read
Find the only repeating element in a sorted array of size n
Given a sorted array of n elements containing elements in range from 1 to n-1 i.e. one element occurs twice, the task is to find the repeating element in an array. Examples : Input : arr[] = { 1, 2 , 3 , 4 , 4}Output : 4Input : arr[] = { 1 , 1 , 2 , 3 , 4}Output : 1Brute Force: Traverse the input array using a for a loop.For each element in the arr
8 min read
Find last element after deleting every second element in array of n integers
Given a circular array of size n containing integers from 1 to n. Find the last element that would remain in the list after erasing every second element starting from the first element. Example: Input: 5 Output: 3 Explanation Element in circular array are: 1 2 3 4 5 Starting from first element i.e, '1' delete every second element like this, 1 0 3 4
7 min read
Find the first non-repeating character from a stream of characters
Given a stream of characters, find the first non-repeating character from the stream. You need to tell the first non-repeating character in O(1) time at any moment. If we follow the first approach discussed here, then we need to store the stream so that we can traverse it one more time to find the first non-repeating character at any moment. If we
15+ min read
Find first non-repeating character of given String
Given a string S of lowercase English letters, the task is to find the index of the first non-repeating character. If there is no such character, return -1. Examples: Input: S = "geeksforgeeks"Output: 5Explanation: 'f' is the first character in the string which does not repeat. Input: "aabbccc"Output: -1Explanation: All the characters in the given
12 min read
Count all distinct pairs of repeating elements from the array for every array element
Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i < j and arr[i] = arr[j]. Examples: Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excluding current element are [1, 2, 1, 2]. So the count
7 min read
Find just strictly greater element from first array for each element in second array
Given two arrays A[] and B[] containing N elements, the task is to find, for every element in the array B[], the element which is just strictly greater than that element which is present in the array A[]. If no value is present, then print 'null'. Note: The value from the array A[] can only be used once. Examples: Input: A[] = {0, 1, 2, 3, 4}, B[]
10 min read
Find integers such that A contains exactly X distinct integers greater than A{i]
Given an array A[] of N integers, the task is to print the number of integers i from 1 to N, for which A contains exactly X distinct integers (for X = 0 to N-1) greater than Ai Examples: Input: N = 6, A[] = {2, 7, 1, 8, 2, 8}Output: {2, 1, 2, 1, 0, 0}Explanation: Let us consider X = 2.A[1] = 2: A contains 2 distinct integers greater than 2 (7 and 8
6 min read
k-th distinct (or non-repeating) element among unique elements in an array.
Given an integer array, print k-th distinct element in an array. The given array may contain duplicates and the output should print k-th element among all unique elements. If k is more than number of distinct elements, print -1.Examples : Input : arr[] = {1, 2, 1, 3, 4, 2}, k = 2 Output : 4 First non-repeating element is 3 Second non-repeating elem
9 min read
Queries to check if any non-repeating element exists within range [L, R] of an Array
Given an array arr[] consisting of integers and queries Q of the form (L, R), the task is to check whether any non-repeating element is present within indices [L, R](1 based indexing) or not. If there is at least one non-repeating element, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 1, 2, 3, 4}, Queries[][] = {{1, 4}, {
15+ min read
Maximize sum of selected integers from an Array of pair of integers as per given condition
Given an array arr[] having N pair of integers of the form (x, y), the task is to maximize the sum y values in selected pairs such that if a pair (xi, yi) is selected, the next xi pairs cannot be selected. Examples: Input: arr[]= {{1, 5}, {2, 7}, {1, 4}, {1, 5}, {1, 10}}Output: 19Explanation: Choose the pair at the index i = 0 i.e, (1, 5). Hence th
15+ min read
Minimum product of k integers in an array of positive Integers
Given an array of n positive integers. We are required to write a program to print the minimum product of k integers of the given array. Examples:  Input : 198 76 544 123 154 675 k = 2Output : 9348We get minimum product after multiplying76 and 123.Input : 11 8 5 7 5 100 k = 4Output : 1400Recommended PracticeMinimum Product of k IntegersTry It!An ap
6 min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
First non-repeating in a linked list
Given a linked list, find its first non-repeating integer element. Examples: Input : 10->20->30->10->20->40->30->NULLOutput :First Non-repeating element is 40.Input :1->1->2->2->3->4->3->4->5->NULLOutput :First Non-repeating element is 5.Input :1->1->2->2->3->4->3->4->NULLOutpu
12 min read
Lexicographically smallest string of maximum length made up of first K alphabets that does not contain any repeating substring
Given a positive integer K, the task is to find lexicographically the smallest string that can be generated by using the first K lowercase alphabets such that no substring of length at least 2 is repeated in the generated string. Examples: Input: K = 3Output: aabacbbccaExplanation:In the string "aabacbbcca", all possible substrings of length at lea
5 min read
First non-repeating character using one traversal of string | Set 2
Given a string, find the first non-repeating character in it. For example, if the input string is "GeeksforGeeks", then output should be 'f' and if input string is "GeeksQuiz", then output should be 'G'. Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed two solutions in Given a string, find its f
15+ min read
Queue based approach for first non-repeating character in a stream
Given a stream of characters and we have to find first non repeating character each time a character is inserted to the stream. Examples: Input : a a b c Output : a -1 b b Input : a a c Output : a -1 cRecommended PracticeFirst non-repeating character in a streamTry It! We have already discussed a Doubly linked list based approach in the previous po
5 min read
Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times
Given an array arr[] consisting of N integers and a positive integer K, the task is to find the last element present in the array obtained by repeatedly removing the first element of the array and appending it twice to the end of the array K times. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 5Output: 5Explanation:Initially, the array is {1, 2, 3,
7 min read
Find any one of the multiple repeating elements in read only array | Set 2
Given a read-only array arr[] of size N + 1, find one of the multiple repeating elements in the array where the array contains integers only between 1 and N. Note: Read-only array means that the contents of the array can't be modified. Examples: Input: N = 5, arr[] = {1, 1, 2, 3, 5, 4} Output: 1 Explanation: 1 is the only number repeated in the arr
6 min read
Find the Suffix Array of given String with no repeating character
Given a string str of size N, the task is to find the suffix array of the given string. Note: A suffix array is a sorted array of all suffixes of a given string. Examples: Input: str = "prince"Output: 4 5 2 3 0 1Explanation: The suffixes are0 prince 4 ce1 rince Sort the suffixes 5 e 2 ince ----------------> 2 ince 3 nce alphabetically 3 nce 4 ce
6 min read
Find the two repeating elements in a given array
Given an array arr[] of N+2 elements. All elements of the array are in the range of 1 to N. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. Examples: Input: arr = [4, 2, 4, 5, 2, 3, 1], N = 5Output: 4 2Explanation: The above array has n + 2 = 7 elements with all elements occurring once except 2 and
15+ min read
Find sum of non-repeating (distinct) elements in an array
Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};Output : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4};Output : 71Recommended PracticeSum of distinct el
14 min read
Find any one of the multiple repeating elements in read only array
Given a read-only array of size ( n+1 ), find one of the multiple repeating elements in the array where the array contains integers only between 1 and n. A read-only array means that the contents of the array can’t be modified.Examples: Input : n = 5 arr[] = {1, 1, 2, 3, 5, 4} Output : One of the numbers repeated in the array is: 1 Input : n = 10 a
15 min read
Find the absolute difference between the nearest powers of two given integers for every array element
Given an array arr[] consisting of N positive integers and two positive integers A and B, the task is to replace each array element with the absolute difference of the nearest powers of A and B. If there exists two nearest powers, then choose the maximum of the two. Examples: Input: arr[] = {5, 12, 25}, A = 2, B = 3Output: 1 7 5Explanation: For ele
8 min read
Find the missing element in an array of integers represented in binary format
Given N strings which represents all integers from 0 to N in binary format except any one. The task is to find the missing number. Input consists of an array of strings where array elements are represented in binary format. Examples: Input: arr[] = {"0000", "0001", "0010", "0100"} Output: 3 Input: arr[] = {"0000", "0001", "0010", "0011", "0100", "0
15+ min read
Article Tags :
Practice Tags :