LeetCode 1429: First Unique Number Solution

Master LeetCode problem 1429 (First Unique Number), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1429. First Unique Number

Problem Explanation

Explanation:

To solve this problem, we can use a combination of a queue and a hashmap. The queue will store the order of appearance of each unique number, while the hashmap will store the frequency of each number.

  1. Initialize a queue and a hashmap.
  2. Iterate over the given array:
    • If the number is not in the hashmap, add it to the queue and set its frequency to 1 in the hashmap.
    • If the number is already in the hashmap, increment its frequency.
    • While the queue is not empty and the front element's frequency is more than 1, remove it from the queue.
  3. If the queue is not empty, return the front element as the first unique number. Otherwise, return -1.

Time complexity: O(n) where n is the number of elements in the array. Space complexity: O(n) for the hashmap and the queue.

:

Solution Code

import java.util.*;

class FirstUnique {
    Queue<Integer> queue;
    Map<Integer, Integer> frequency;

    public FirstUnique(int[] nums) {
        queue = new LinkedList<>();
        frequency = new HashMap<>();

        for (int num : nums) {
            add(num);
        }
    }

    public int showFirstUnique() {
        while (!queue.isEmpty() && frequency.get(queue.peek()) > 1) {
            queue.poll();
        }
        return queue.isEmpty() ? -1 : queue.peek();
    }

    public void add(int value) {
        frequency.put(value, frequency.getOrDefault(value, 0) + 1);
        if (frequency.get(value) == 1) {
            queue.offer(value);
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1429 (First Unique Number)?

This page provides optimized solutions for LeetCode problem 1429 (First Unique Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1429 (First Unique Number)?

The time complexity for LeetCode 1429 (First Unique Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1429 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1429 in Java, C++, or Python.

Back to LeetCode Solutions