Problem Description
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 k if found; otherwise, return -1.
Key Insights
- Use a hash set for quick look-up of elements.
- Iterate through each number in the array; if the number is positive and its negative is also present, it is a candidate.
- Keep track of the maximum valid candidate found.
- The array does not contain zero, which simplifies the checks.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array (using a set for O(1) look-ups). Space Complexity: O(n), for storing elements in the hash set.
Solution
We start by putting all the numbers in a hash set for O(1) look-up time. Then, we iterate through the array and for each positive number k, we check if -k exists in the set. If it does, we update our answer with the maximum value between the current answer and k. Finally, if no valid k is found, we return -1.