Sobes.tech
Senior

//Find the first non-repeating element in an array of integers int[] arr = {9, 4, 9, 6, 7, 4, 5}; int n = ...;

sobes.tech AI

Answer from AI

To find the first non-repeating element in an array of integers, you can use two passes:

  1. In the first pass, count the occurrences of each number using a HashMap.
  2. In the second pass, iterate through the array and return the first element whose count is 1.

Example in Java:

import java.util.*;

public class Solution {
    public static Integer firstNonRepeating(int[] arr) {
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int num : arr) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }
        for (int num : arr) {
            if (countMap.get(num) == 1) {
                return num;
            }
        }
        return null; // if there are no non-repeating elements
    }

    public static void main(String[] args) {
        int[] arr = {9, 4, 9, 6, 7, 4, 5};
        Integer n = firstNonRepeating(arr);
        System.out.println(n); // Outputs 6
    }
}

This approach is efficient in terms of time complexity — O(n), where n is the length of the array.