[go: up one dir, main page]

Open In App

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

Last Updated : 11 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Problem

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.


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>


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
?>


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(n), 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



Previous Article
Next Article

Similar Reads

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 first repeating element in an array of integers
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}
9 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 first non-repeating character of given string
Given a string s of lowercase English letters, the task is to find the first non-repeating character. If there is no such character, return '$'. Examples: Input: s = "geeksforgeeks"Output: 'f'Explanation: 'f' is the first character in the string which does not repeat. Input: s = "racecar"Output: 'e'Explanation: 'e' is the only character in the stri
15 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
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 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
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
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
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
Queries to find the last non-repeating character in the sub-string of a given string
Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}, {0, 12}} Output: G k r Sub-string for the querie
11 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
Non-Repeating Elements of a given array using Multithreaded program
Given an array arr[] of size N and an integer T representing the count of threads, the task is to find all non-repeating array elements using multithreading. Examples: Input: arr[] = { 1, 0, 5, 5, 2}, T = 3 Output: 0 1 2 Explanation: The frequency of 0 in the array arr[] is 1. The frequency of 1 in the array arr[] is 1. The frequency of 2 in the ar
13 min read
Largest Non-Repeating Element
Given an array arr[] of size N, the task is to find the largest non-repeating element present in the given array. If no such element exists, then print -1. Examples: Input: arr[] = { 3, 1, 8, 8, 4 } Output: 4 Explanation: Non-repeating elements of the given array are { 1, 3, 4 } Therefore, the largest non-repeating element of the given array is 4.
11 min read
Count of integers up to N which are non divisors and non coprime with N
Given an integer N, the task is to find the count of all possible integers less than N satisfying the following properties: The number is not coprime with N i.e their GCD is greater than 1.The number is not a divisor of N. Examples: Input: N = 10 Output: 3 Explanation: All possible integers which are less than 10 and are neither divisors nor coprim
5 min read
Find the last non repeating character in string
Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is "GeeksForGeeks", then the output should be 'r' and if the input string is "GeeksQuiz" then the output should be 'z'. if there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks" Output: r 'r' is the firs
5 min read
Subsequences of given string consisting of non-repeating characters
Given a string str of length N, the task is to print all possible distinct subsequences of the string str which consists of non-repeating characters only. Examples: Input: str = "abac" Output: a ab abc ac b ba bac bc c Explanation: All possible distinct subsequences of the strings are { a, aa, aac, ab, aba, abac, abc, ac, b, ba, bac, bc, c } Theref
7 min read
Find the next non-zero Array element to the right of each array element
Given an array arr[] of N integers, the task is to find the next non-zero array element to the right of every array element. If there doesn't exist any non-zero element, then print that element itself. Examples: Input: arr[] = {1, 2, 0}Output: {2, 2, 0}Explanation:For each array element the next non-zero elements are:arr[0] = 1 -> 2arr[1] = 2 -
6 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
Product of all non repeating Subarrays of an Array
Given an array containing distinct integers arr[] of size N, the task is to print the product of all non-repeating subarrays of the array. Examples: Input: arr[] = {2, 4} Output: 64 Explanation: The possible subarrays for the given array are {2}, {2, 4}, {4} The products are 2, 8, 4 respectively. Therefore, the overall product of all the subarrays
5 min read
Count Non-Repeating array elements after inserting absolute difference between all possible pairs
Given an array arr[] of size N, the task is to maximize the count of distinct array elements by repeatedly inserting the absolute difference between all possible pairs of the given array. Examples: Input: arr[] = { 2, 4, 16 }Output: 9 Explanation: Inserting (arr[2] - arr[1]) modifies arr[] to { 2, 4, 12, 16 } Inserting (arr[2] - arr[1]) modifies ar
7 min read
Highest powers of 2 not exceeding non-repeating array elements
Given an array arr[] of size N, the task is for every non-repeating array element is to find the highest power of 2 that does not exceed that element. Print the powers of 2 in ascending order. If the array does not contain any non-repeating element, print "0". Examples: Input: arr[ ] = { 4, 5, 4, 3, 3, 4 } Output: 4 Explanation: The only non-repeat
12 min read
Nearest power of 2 of nearest perfect squares of non-repeating array elements
Given an array arr[] consisting of N positive integers, the task is to find the nearest perfect power of 2 of the nearest perfect squares of unique array elements. If the array does not contain any unique element, then print -1. Examples: Input: arr[] = {4, 11, 4, 3, 4}Output: 4 8Explanation:The unique elements in the given array are 11 and 3.The n
9 min read
Product of non-repeating (distinct) elements in an Array
Given an integer array with duplicate elements. The task is to find the product of all distinct elements in the given array. Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10}; Output : 97200 Here we take 12, 10, 9, 45, 2 for product because these are the only distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4}; Output : 324
15 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
Sum of consecutive bit differences of first N non-negative integers
Given a positive integer N, the task is to find out the sum of all consecutive bit differences from 0 to N. Note: If the bit length is different for two numbers like(3, 4) then append 0 at the beginning (011, 100). Examples: Input: N = 3 Output: 4 Explanation: Bit differences of (0, 1) + (1, 2) + (2, 3) = 1 + 2 + 1 = 4.Input: N = 7 Output: 11 Naive
8 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
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
three90RightbarBannerImg