write a Java program to Find the first non-repeating element in the array using a queue


The Java code finds the first non-repeating element from an array using a queue and a frequency map (implemented as a HashMap).

  • An array nums containing integers is provided.
  • A Queue of integers is created using the LinkedList class, named queue.
  • A Map named frequencyMap is created using the HashMap class to store the frequency of each element in the array.
  • The code iterates through the elements of the nums array, updating the frequencyMap and adding each element to the queue.
  • After the queue and frequencyMap are populated, the code starts dequeuing elements from the queue one by one.
  • For each dequeued element, the code checks its frequency in the frequencyMap. If the frequency is equal to 1, it means that the element is non-repeating, and the code returns that element.
  • If no non-repeating element is found in the array, the code returns -1.
  • In the main method, an example array nums containing integers is provided.
  • The findFirstNonRepeating method is called with the array nums, and the result is printed.

Source Code

import java.util.*;
public class FirstNonRepeatingElement
{
	public static int findFirstNonRepeating(int[] nums)
	{
		Queue<Integer> queue = new LinkedList<>();
		Map<Integer, Integer> frequencyMap = new HashMap<>();
 
		for (int num : nums)
		{
			frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
			queue.offer(num);
		}
 
		while (!queue.isEmpty())
		{
			int num = queue.poll();
			if (frequencyMap.get(num) == 1)
			{
				return num;
			}
		}
 
		return -1; // If no non-repeating element found
        }
 
	public static void main(String[] args)
	{
		int[] nums = {10, 20, 20, 30, 40, 40, 50};
 
		int result = findFirstNonRepeating(nums);
		System.out.println("First Non-repeating Element : " + result);
	}
}
 

Output

First Non-repeating Element : 10

Example Programs