Sponsored
Sponsored
This approach utilizes a HashSet to keep track of the numbers we have encountered. As we iterate through the list, we check both the presence of a number and its negative in the HashSet. We update the largest number that satisfies the condition.
Time Complexity: O(n), since we iterate through the array once.
Space Complexity: O(1), since the hash set array size is always constant and independent of input size.
1def largest_equal_positive_negative(nums):
2 num_set = set()
3 largest = -1
4 for num in nums:
5 if -num in num_set:
6 largest = max(largest, abs(num))
7 num_set.add(num)
8 return largest
9
10nums = [-1, 2, -3, 3]
11print(largest_equal_positive_negative(nums)) # Output: 3
Uses a set to track numbers. For each number, checks if its negative is in the set, updating the largest absolute value if a pair is found.
In this approach, we first sort the array so that we can efficiently find pairs of positive and negative numbers. Once sorted, we use two pointers: one starting from the beginning (for negative numbers) and one from the end (for positive numbers) to find the largest integer pair where both a positive and its negative exist.
Time Complexity: O(n log n) for the sorting operation.
Space Complexity: O(1) additional space beyond input storing.
By sorting, the array leverages two pointers to find matching number pairs with opposite signs effectively. We examine pairs equating to zero to decide the largest possible valid integer.