Largest Unique Number

The problem asks for the largest integer that only occurs once in the given array. If no integer occurs once, we have to return -1.

Here’s a step-by-step explanation of how we can solve this problem:

  1. Count the Occurrences of Each Integer: We can use a dictionary to keep track of the occurrence count for each integer in the array.

  2. Find the Largest Integer that Occurs Once: Iterate through the keys of the dictionary in descending order and return the first integer that has an occurrence count of 1.

  3. Handle the Case When No Integer Occurs Once: If no integer occurs once, return -1.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def largestUniqueNumber(self, nums: List[int]) -> int:
        # Use a dictionary to store the count of each integer
        count_dict = {}
        for num in nums:
            if num in count_dict:
                count_dict[num] += 1
            else:
                count_dict[num] = 1

        # Iterate through the keys of the dictionary in descending order
        for num in sorted(count_dict.keys(), reverse=True):
            # If an integer occurs only once, return it
            if count_dict[num] == 1:
                return num

        # If no integer occurs once, return -1
        return -1

Explanation:

  • The dictionary count_dict is used to store the count of occurrences for each integer in the array.
  • We iterate through the keys of the dictionary in descending order, so we are effectively checking the integers in descending order of their values.
  • When we find an integer that occurs only once, we return it.
  • If we don’t find any integer that occurs once, we return -1.

The time complexity of this solution is (O(n \log n)), where (n) is the length of the input array, and the space complexity is (O(n)).