Start learning free

LESSON 212 OF 410 · BRUTE FORCE

Pair Count in O(n^2) Time Complexity using Java

Practice O(n2) Read the full explanation

Given two positive integers n and sum, count the number of different pairs of integers (x, y) such that 1 <= x, y <= n and x + y equals sum.

Example:

Input: n = 7, sum = 6
Output: 3
Explanation: There are 3 valid pairs: (1, 5), (2, 4), (3, 3).
Note that pairs such as (1, 5) and (5, 1) are not considered different.

Note:

Your algorithm should run in O(n^2) time and use O(1) space.


Hints:

Let's come up with a brute force approach. Brute force tries each and every candidate to our solution. For this problem, the candidates are all the pairs of numbers (x, y) such that 1 <= x <= y <= n. How can we try out all these pairs?

Using two nested for loops! The first loop will try out each possible x between 1 and n. The second loop will be written inside the first one and will try out each possible y between x and n.
for each x : 1 -> n:
	for each y : x -> n:
	
What should be written inside these loops?

Inside the loops we should check if the pair (x, y) is a solution, e.g. if x + y == sum. If so, we should add 1 to the answer. But where do we store the answer? We'll need a variable for that. Let's name it result.
result = 0
for each x : 1 -> n:
	for each y : x -> n:
		if x + y == sum:
			add 1 to result
return result
	


STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · BRUTE FORCE

    Pair Count in Java, explained

    Understanding the Problem

    The core challenge of this problem is to find all unique pairs (x, y) such that their sum equals a given value, and both x and y are within the range from 1 to n. This problem is significant in various applications such as finding pairs in arrays that sum up to a specific value, which is a common task in data analysis and algorithm design.

    Potential pitfalls include counting pairs like (1, 5) and (5, 1) as different, which is incorrect as per the problem statement.

    Approach

    To solve this problem, we can start with a brute force approach and then discuss its optimization:

    Naive Solution

    The naive solution involves using two nested loops to iterate through all possible pairs (x, y) and checking if their sum equals the given value. This approach is straightforward but not optimal in terms of time complexity.

    public class PairCount {
        public static int countPairs(int n, int sum) {
            int result = 0;
            for (int x = 1; x <= n; x++) {
                for (int y = x; y <= n; y++) {
                    if (x + y == sum) {
                        result++;
                    }
                }
            }
            return result;
        }
    
        public static void main(String[] args) {
            int n = 7;
            int sum = 6;
            System.out.println(countPairs(n, sum)); // Output: 3
        }
    }
    

    In this code, we use two nested loops to iterate through all possible pairs (x, y) and check if their sum equals the given value. If it does, we increment the result counter.

    Optimized Solution

    Given the constraints, the naive solution is already optimal in terms of time complexity (O(n^2)). However, we can make the code cleaner and more readable by avoiding unnecessary checks.

    public class PairCount {
        public static int countPairs(int n, int sum) {
            int result = 0;
            for (int x = 1; x <= n; x++) {
                int y = sum - x;
                if (y >= x && y <= n) {
                    result++;
                }
            }
            return result;
        }
    
        public static void main(String[] args) {
            int n = 7;
            int sum = 6;
            System.out.println(countPairs(n, sum)); // Output: 3
        }
    }
    

    In this optimized version, we reduce the number of iterations by calculating y directly and checking if it falls within the valid range. This approach still has a time complexity of O(n^2) but is more efficient in practice.

    Complexity Analysis

    The time complexity of both the naive and optimized solutions is O(n^2) because we are using nested loops to iterate through all possible pairs. The space complexity is O(1) as we are using a constant amount of extra space.

    Edge Cases

    Potential edge cases include:

    • n = 1 and sum = 2: The output should be 0 as there are no valid pairs.
    • n = 10 and sum = 20: The output should be 0 as no pairs can sum up to 20.

    Testing

    To test the solution comprehensively, we should include a variety of test cases:

    • Simple cases with small n and sum values.
    • Cases where no pairs exist.
    • Cases with larger n values to test performance.

    Thinking and Problem-Solving Tips

    When approaching such problems, it's essential to start with a brute force solution to understand the problem better. Then, look for patterns or mathematical properties that can help optimize the solution. Practice solving similar problems and studying algorithms to improve problem-solving skills.

    Conclusion

    In this blog post, we discussed how to solve the problem of counting pairs of integers that sum up to a given value. We explored both naive and optimized solutions, analyzed their complexities, and discussed edge cases and testing strategies. Understanding and solving such problems is crucial for developing strong algorithmic thinking and problem-solving skills.

    Additional Resources

    For further reading and practice, consider the following resources:

    • LeetCode - A platform for practicing coding problems.
    • GeeksforGeeks - A comprehensive resource for learning algorithms and data structures.
    • Coursera - Online courses on algorithms and data structures.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free