#2441
Largest Positive Integer That Exists With Its Negative
EasyArrayHash TableTwo PointersSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a HashSet allows us to efficiently check for the existence of negative counterparts in constant time. This significantly reduces the number of comparisons needed.
⚙️
Algorithm
5 steps- 1Step 1: Create a HashSet to store all elements from the array.
- 2Step 2: Initialize a variable 'max_k' to -1.
- 3Step 3: Loop through each element 'num' in the array.
- 4Step 4: If 'num' is positive and '-num' exists in the HashSet, update 'max_k' to the maximum of 'max_k' and 'num'.
- 5Step 5: After checking all elements, return 'max_k'. If 'max_k' is still -1, return -1.
solution.py9 lines
1# Full working Python code
2
3def largest_positive_integer(nums):
4 num_set = set(nums)
5 max_k = -1
6 for num in nums:
7 if num > 0 and -num in num_set:
8 max_k = max(max_k, num)
9 return max_kℹ
Complexity note: The time complexity is O(n) because we only traverse the array a couple of times. The space complexity is O(n) due to the HashSet storing all elements.
- 1Using a HashSet allows for O(1) average time complexity for lookups, making the solution efficient.
- 2The largest positive integer is always the focus, so we only need to track positive numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.