Skip to content
Related Articles

Related Articles

Find first non-repeating element in a given Array of integers

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 17 Aug, 2022
View Discussion
Improve Article
Save Article

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: 2
Explanation: The first number that does not repeat is : 2

Input: {9, 4, 9, 6, 7, 4}
Output: 6

Recommended Practice

Find first non-repeating element in a given Array of integers using Nested Loops:

This approach is based on the following idea:

Simple Solution is to use two loops. The outer loop picks elements one by one and the inner loop checks if the element is present more than once or not..

Illustration:

Given arr[] = {-1, 2, -1, 3, 0}

For element at i = 0

  • The value of element at index 2 is same, then this can’t be first non-repeating element

For element at i = 1:

  • After traversing the array arr[1] is not present is not present in the array except at 1.

Hence, element is index 1 is the first non-repeating element which is 2

Follow the steps below to solve the given problem: 

  • Loop over the array from the left.
  • Check for each element if its presence is present in the array for more than 1 time.
  • Use a nested loop to check the presence.

Below is the implementation of the above idea:

C++




// Simple CPP program to find first non-
// repeating element.
#include <bits/stdc++.h>
using namespace std;
 
int firstNonRepeating(int arr[], int n)
{
    // Loop for checking each element
    for (int i = 0; i < n; i++) {
        int j;
        // Checking if ith element is present in array
        for (j = 0; j < n; j++)
            if (i != j && arr[i] == arr[j])
                break;
        // if ith element is not present in array
        // except at ith index then return element
        if (j == n)
            return arr[i];
    }
    return -1;
}
 
// Driver code
int main()
{
    int arr[] = { 9, 4, 9, 6, 7, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << firstNonRepeating(arr, n);
    return 0;
}


Java




// Java program to find first non-repeating
// element.
class GFG {
 
    static int firstNonRepeating(int arr[], int n)
    {
        // Loop for checking each element
        for (int i = 0; i < n; i++) {
            int j;
            // Checking if ith element is present in array
            for (j = 0; j < n; j++)
                if (i != j && arr[i] == arr[j])
                    break;
            // if ith element is not present in array
            // except at ith index then return element
            if (j == n)
                return arr[i];
        }
 
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        int arr[] = { 9, 4, 9, 6, 7, 4 };
        int n = arr.length;
 
        System.out.print(firstNonRepeating(arr, n));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python3 program to find first
# non-repeating element.
 
 
def firstNonRepeating(arr, n):
 
    # Loop for checking each element
    for i in range(n):
        j = 0
        # Checking if ith element is present in array
        while(j < n):
            if (i != j and arr[i] == arr[j]):
                break
            j += 1
        # if ith element is not present in array
        # except at ith index then return element
        if (j == n):
            return arr[i]
 
    return -1
 
 
# Driver code
arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))
 
# This code is contributed by Anant Agarwal.


C#




// C# program to find first non-
// repeating element.
using System;
 
class GFG {
    static int firstNonRepeating(int[] arr, int n)
    {
        // Loop for checking each element
        for (int i = 0; i < n; i++) {
            int j;
            // Checking if ith element is present in array
            for (j = 0; j < n; j++)
                if (i != j && arr[i] == arr[j])
                    break;
            // if ith element is not present in array
            // except at ith index then return element
            if (j == n)
                return arr[i];
        }
        return -1;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 9, 4, 9, 6, 7, 4 };
        int n = arr.Length;
        Console.Write(firstNonRepeating(arr, n));
    }
}
// This code is contributed by Anant Agarwal.


PHP




<?php
// Simple PHP program to find first non-
// repeating element.
 
function firstNonRepeating($arr, $n)
{
    // Loop for checking each element
    for ($i = 0; $i < $n; $i++)
    {
        $j;
        // Checking if ith element is present in array
        for ($j = 0; $j< $n; $j++)
            if ($i != $j && $arr[$i] == $arr[$j])
                break;
          // if ith element is not present in array
        // except at ith index then return element
        if ($j == $n)
            return $arr[$i];
    }
    return -1;
}
 
    // Driver code
    $arr = array(9, 4, 9, 6, 7, 4);
    $n = sizeof($arr) ;
    echo firstNonRepeating($arr, $n);
     
// This code is contributed by ajit
?>


JavaScript




<script>
        // JavaScript code for the above approach
        function firstNonRepeating(arr, n) {
            // Loop for checking each element
            for (let i = 0; i < n; i++) {
                let j;
                // Checking if ith element is present in array
                for (j = 0; j < n; j++)
                    if (i != j && arr[i] == arr[j])
                        break;
                // if ith element is not present in array
                // except at ith index then return element       
                if (j == n)
                    return arr[i];
            }
            return -1;
        }
 
        // Driver code
 
        let arr = [9, 4, 9, 6, 7, 4];
        let n = arr.length;
        document.write(firstNonRepeating(arr, n));
 
 
 
  // This code is contributed by Potta Lokesh
    </script>


Output

6

Time Complexity: O(n*n), Checking for each element n times
Auxiliary Space: O(1)

Find first non-repeating element in a given Array of integers using Hashing:

This approach is based on the following idea:

  • The idea is to store the frequency of every element in the hashmap.
  • Then check the first element whose frequency is 1 in the hashmap.
  • This can be achieved using hashing

Illustration:

arr[] = {-1, 2, -1, 3, 0}

Frequency map for arr:

  • -1 -> 2
  • 2 -> 1
  • 3 -> 1
  • 0 -> 1

Traverse arr[] from left:

At i = 0:

  • Frequency of arr[0] is 2, therefore it can’t be first non-repeating element

At i = 1:

  • Frequency of arr[1] is 1, therefore it will be the first non-repeating element.

Hence, 2 is the first non-repeating element.

Follow the steps below to solve the given problem: 

  • Traverse array and insert elements and their counts in the hash table.
  • Traverse array again and print the first element with a count equal to 1.

Below is the implementation of the above idea:

C++




// Efficient CPP program to find first non-
// repeating element.
#include <bits/stdc++.h>
using namespace std;
 
int firstNonRepeating(int arr[], int n)
{
    // Insert all array elements in hash
    // table
    unordered_map<int, int> mp;
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Traverse array again and return
    // first element with count 1.
    for (int i = 0; i < n; i++)
        if (mp[arr[i]] == 1)
            return arr[i];
    return -1;
}
 
// Driver code
int main()
{
    int arr[] = { 9, 4, 9, 6, 7, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << firstNonRepeating(arr, n);
    return 0;
}


Java




// Efficient Java program to find first non-
// repeating element.
import java.util.*;
 
class GFG {
 
    static int firstNonRepeating(int arr[], int n)
    {
        // Insert all array elements in hash
        // table
 
        Map<Integer, Integer> m = new HashMap<>();
        for (int i = 0; i < n; i++) {
            if (m.containsKey(arr[i])) {
                m.put(arr[i], m.get(arr[i]) + 1);
            }
            else {
                m.put(arr[i], 1);
            }
        }
        // Traverse array again and return
        // first element with count 1.
        for (int i = 0; i < n; i++)
            if (m.get(arr[i]) == 1)
                return arr[i];
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 9, 4, 9, 6, 7, 4 };
        int n = arr.length;
        System.out.println(firstNonRepeating(arr, n));
    }
}
 
// This code contributed by Rajput-Ji


Python3




# Efficient Python3 program to find first
# non-repeating element.
from collections import defaultdict
 
 
def firstNonRepeating(arr, n):
    mp = defaultdict(lambda: 0)
 
    # Insert all array elements in hash table
    for i in range(n):
        mp[arr[i]] += 1
 
    # Traverse array again and return
    # first element with count 1.
    for i in range(n):
        if mp[arr[i]] == 1:
            return arr[i]
    return -1
 
 
# Driver Code
arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))
 
# This code is contributed by Shrikant13


C#




// Efficient C# program to find first non-
// repeating element.
using System;
using System.Collections.Generic;
 
class GFG {
 
    static int firstNonRepeating(int[] arr, int n)
    {
        // Insert all array elements in hash
        // table
 
        Dictionary<int, int> m = new Dictionary<int, int>();
        for (int i = 0; i < n; i++) {
            if (m.ContainsKey(arr[i])) {
                var val = m[arr[i]];
                m.Remove(arr[i]);
                m.Add(arr[i], val + 1);
            }
            else {
                m.Add(arr[i], 1);
            }
        }
 
        // Traverse array again and return
        // first element with count 1.
        for (int i = 0; i < n; i++)
            if (m[arr[i]] == 1)
                return arr[i];
        return -1;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 9, 4, 9, 6, 7, 4 };
        int n = arr.Length;
        Console.WriteLine(firstNonRepeating(arr, n));
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
// Efficient javascript program to find first non-
// repeating element.
 
function firstNonRepeating(arr , n)
{
    // Insert all array elements in hash
    // table
 
    const m = new Map();
    for (var i = 0; i < n; i++) {
        if (m.has(arr[i])) {
            m.set(arr[i], m.get(arr[i]) + 1);
        }
        else {
            m.set(arr[i], 1);
        }
    }
    // Traverse array again and return
    // first element with count 1.
    for (var i = 0; i < n; i++)
        if (m.get(arr[i]) == 1)
            return arr[i];
    return -1;
}
 
// Driver code
var arr = [ 9, 4, 9, 6, 7, 4 ];
var n = arr.length;
document.write(firstNonRepeating(arr, n));
 
// This code contributed by shikhasingrajput
</script>


Output

6

Time Complexity: O(2n), Traverse over the array to map the frequency and again traverse over the array to check for frequency.
Auxiliary Space: O(n), Create a hash table for storing frequency


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!