703816. Pairs with Positive Negative values

Easy

Here is a detailed Markdown blog post for the GeeksforGeeks problem:

Pairs with Positive Negative values

Summary

Given an array of integers, find all pairs that have positive and negative values. The input array contains only integers. This problem involves arrays and data structures.

Detailed Explanation

The key to solving this problem is to iterate through the array, keeping track of the positive and negative values. We can use a hash map to store the counts of positive and negative values.

Here's a step-by-step breakdown of the solution:

  1. Initialize two variables positiveCount and negativeCount to 0.
  2. Iterate through the input array:
    • For each integer, check if it is positive or negative.
    • If the integer is positive, increment positiveCount. Otherwise, increment negativeCount.
  3. Since we are interested in pairs with a positive and negative value, find all possible combinations of positive and negative integers from the counts.

Here's an ASCII art diagram to illustrate the process:

  +---------------+
  |  Positive    |
  |  Count: 3     |
  +---------------+
          |
          v
  +---------------+
  |  Negative   |
  |  Count: 2     |
  +---------------+

The time complexity for this solution is O(n), where n is the length of the input array. This is because we are iterating through the array once. The space complexity is also O(n) as we are storing counts in a hash map.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.HashMap;
import java.util.Map;

public class PairsWithPositiveNegative {
    public static void findPairs(int[] arr) {
        Map<Integer, Integer> positiveCount = new HashMap<>();
        Map<Integer, Integer> negativeCount = new HashMap<>();

        for (int num : arr) {
            if (num > 0) {
                positiveCount.put(num, positiveCount.getOrDefault(num, 0) + 1);
            } else {
                negativeCount.put(num, negativeCount.getOrDefault(num, 0) + 1);
            }
        }

        System.out.println("Pairs with positive and negative values:");
        for (Map.Entry<Integer, Integer> entry : positiveCount.entrySet()) {
            int positive = entry.getKey();
            int positiveCountValue = entry.getValue();

            for (int i = 0; i < positiveCountValue; i++) {
                int negative = -positive;
                System.out.println("(" + positive + ", " + negative + ")");
            }
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.