VOOZH about

URL: https://www.geeksforgeeks.org/dsa/non-repeating-element/

⇱ First Non-Repeating in an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

First Non-Repeating in an Array

Last Updated : 28 May, 2026

Given an array arr[] of integers of size n, find the first non-repeating element in this array.  if no such element exists return 0.

Examples:

Input: arr[] = [-1, 2, -1, 3, 2]
Output: 3
Explanation: -1 and 2 are repeating whereas 3 is the only number occuring once. Hence, the output is 3.

Input: arr[] = [1, 1, 1]
Output: 0
Explanation: There is not present any non-repeating element so answer should be 0.

[Naive Approach] Using Nested Loops - O(n * n) Time and O(1) Space

A non-repeating element appears only once, so iterate through the array from left to right, and for each element, scan the array to check if it appears again at any other index. If you find a duplicate, skip it, if you don’t find any, return that element as the first non-repeating one. If every element has a duplicate, return 0.


Output
3

[Expected Approach] Using Hash Map - O(n) Time and O(n) Space

  • 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.

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.


Output
3
Comment
Article Tags: