The Largest Positive Integer That Exists With Its Negative coding problem gives you an array of integers that does not contain zeros. You need to find the largest positive integer k such that both k and -k are present in the array. If no such integer exists, the function should return -1.
This "Easy" level question is popular at Microsoft and Amazon because it offers multiple ways to solve it, allowing interviewers to judge a candidate's ability to choose the most appropriate data structure. Whether you use a Hash Set, Sorting, or Two Pointers, the problem reveals your understanding of time-space trade-offs. It's a quick way to gauge basic coding fluency and efficiency.
This problem can be solved using several patterns: Hash Table, Sorting, or Two Pointers interview pattern. The Hash Table approach involves storing all numbers in a set for O(1) lookups. Then, iterate through the set to find the maximum k where -k is also in the set. Alternatively, you can sort the array and use two pointers (one at each end) to find the largest matching pair.
Array: [-1, 10, 6, 7, -7, 1].
Method: Hash Set.
{-1, 1, 6, 7, -7, 10}.The most common mistake is not keeping track of the "largest" value and simply returning the first pair found. Another error is not handling the case where no such pair exists, which should return -1. Some candidates might also use a nested loop, resulting in O(N²) complexity, which is unnecessary when O(N) is achievable.
For "Hash Table, Two Pointers interview pattern" questions, always mention the trade-off. A Hash Set gives O(N) time and O(N) space, while Sorting + Two Pointers gives O(N log N) time but O(1) space. Showing you understand these nuances is what distinguishes a senior candidate.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Distinct Averages | Easy | Solve | |
| Max Number of K-Sum Pairs | Medium | Solve | |
| Divide Players Into Teams of Equal Skill | Medium | Solve | |
| Check If N and Its Double Exist | Easy | Solve | |
| Intersection of Two Arrays II | Easy | Solve |