We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Largest Unique Number

Number: 1098

Difficulty: Easy

Paid? Yes

Companies: Amazon


Problem Description

Given an integer array nums, return the largest integer that only occurs once in the array. If no integer occurs once, return -1.


Key Insights

  • Use a hash table (or dictionary) to count the frequency of each number.
  • Iterate over the hash table to find the numbers that appear exactly once.
  • Identify the maximum number among the unique numbers.
  • Return -1 if no unique number exists.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(n), for the hash table storing frequency counts.


Solution

The approach starts by initializing a hash table to keep track of the frequency of each element in the array. Once the frequency count is complete, we traverse the hash table to collect numbers that appear exactly once. Finally, we determine the maximum number among these unique elements. If there is no unique element, we return -1. This method is efficient because the frequency count and the search for the maximum unique element both run in linear time relative to the input size.


Code Solutions

# Define a function to find the largest unique number
def largestUniqueNumber(nums):
    # Create a dictionary to count the frequency of each number
    frequency = {}
    for num in nums:
        if num in frequency:
            frequency[num] += 1  # Increment frequency count if number exists
        else:
            frequency[num] = 1   # Initialize frequency count for new number

    # Initialize the variable for the maximum unique number
    max_unique = -1
    # Iterate over the frequency dictionary
    for num, count in frequency.items():
        # Check if the number is unique and greater than the current maximum unique
        if count == 1 and num > max_unique:
            max_unique = num

    return max_unique

# Example usage:
print(largestUniqueNumber([5,7,3,9,4,9,8,3,1]))  # Output: 8
← Back to All Questions