K and -K in Python

In Python, finding the largest number k where both k and -k exist in a list is a common programming problem. This means we need to find pairs of numbers that are additive inverses of each other.

So, if the input is like [-5, 2, 9, -6, 5, -9], then the output will be 9 because both 9 and -9 exist in the list.

Algorithm Approach

To solve this problem, we follow these steps:

  • Create L1: a list of non-negative elements (? 0) from nums
  • Create L2: a list of non-positive elements (? 0) from nums
  • Sort L1 in descending order to check larger values first
  • Sort L2 in ascending order for efficient searching
  • For each element i in L1, check if its negative counterpart exists in L2
  • Return the first (largest) match found, or -1 if none exists

Implementation

class Solution:
    def solve(self, nums):
        # Separate positive/zero and negative/zero numbers
        L1 = [i for i in nums if i >= 0]
        L2 = [i for i in nums if i <= 0]
        
        # Sort L1 in descending order to find largest k first
        L1.sort(reverse=True)
        # Sort L2 in ascending order for efficient search
        L2.sort()
        
        # Check each positive number against negative numbers
        for i in L1:
            for j in L2:
                if i + j == 0:  # Found k and -k pair
                    return i
                elif i + j > 0:  # No need to check further in L2
                    break
        
        return -1

# Test the solution
ob = Solution()
nums = [-5, 2, 9, -6, 5, -9]
result = ob.solve(nums)
print(f"Input: {nums}")
print(f"Output: {result}")
Input: [-5, 2, 9, -6, 5, -9]
Output: 9

How It Works

The algorithm works by:

  • Separation: L1 contains [2, 9, 5] and L2 contains [-5, -6, -9]
  • Sorting: L1 becomes [9, 5, 2] and L2 becomes [-9, -6, -5]
  • Checking: For i = 9, we find j = -9 where 9 + (-9) = 0
  • Result: Return 9 as it's the largest k where both k and -k exist

Alternative Approach Using Set

A more efficient solution uses a set for O(1) lookups:

def find_largest_k(nums):
    num_set = set(nums)
    max_k = -1
    
    for num in nums:
        if num > 0 and -num in num_set:
            max_k = max(max_k, num)
    
    return max_k

# Test the alternative approach
nums = [-5, 2, 9, -6, 5, -9]
result = find_largest_k(nums)
print(f"Alternative approach result: {result}")
Alternative approach result: 9

Conclusion

Both approaches solve the k and -k problem effectively. The original nested loop approach has O(n²) complexity, while the set-based solution achieves O(n) time complexity with better performance for larger datasets.

Updated on: 2026-03-25T10:26:50+05:30

851 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements