Largest Positive Integer That Exists With Its Negative — LeetCode 2441 Python Solution
EasyArrayHash TableTwo PointersSorting
- Problem
- #2441
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array. Return the positive integer k.
Example
- Input
- nums = [-1,2,-3,3]
- Output
- 3
- Explanation
- 3 is the only valid k we can find in the array.
Python solution
Python
class Solution:
def findMaxK(self, nums: List[int]) -> int:
s = set(nums)
return max((x for x in s if -x in s), default=-1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 2441. Largest Positive Integer That Exists With Its Negative is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2441. Largest Positive Integer That Exists With Its Negative?
- LeetCode 2441. Largest Positive Integer That Exists With Its Negative is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2441. Largest Positive Integer That Exists With Its Negative?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2441. Largest Positive Integer That Exists With Its Negative?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2441. Largest Positive Integer That Exists With Its Negative cover?
- LeetCode 2441. Largest Positive Integer That Exists With Its Negative is tagged Array, Hash Table, Two Pointers and Sorting on LeetCode.