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:
Count the Occurrences of Each Integer: We can use a dictionary to keep track of the occurrence count for each integer in the array.
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.
Handle the Case When No Integer Occurs Once: If no integer occurs once, return -1.
Here’s the code:
|
|
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)).