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.
1function largestEqualPositiveNegative(nums) {
2 const numSet = new Set();
3 let largest = -1;
4 for (const num of nums) {
5 if (numSet.has(-num)) {
6 largest = Math.max(largest, Math.abs(num));
7 }
8 numSet.add(num);
9 }
10 return largest;
11}
12
13const nums = [-1, 2, -3, 3];
14console.log(largestEqualPositiveNegative(nums)); // Output: 3
Uses a Set to enable fast look-up of numeric presence. For each number, the approach checks if its negative counterpart is in the Set, and updates the largest valid integer if both exist.
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.
Implementing a sorting step allows us to use a two-pointer strategy for rapid scanning for valid number pairs, extracting their largest positive k value when found.