Start learning free

LESSON 211 OF 409 · BRUTE FORCE

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

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

    C++ · BRUTE FORCE

    Pair Count in C++, explained

    Problem Definition

    The problem requires counting the number of unique pairs (x, y) such that their sum equals a given value, and both x and y lie within the range [1, n].

    Input: Two integers, n and sum.

    Output: An integer representing the number of valid pairs.

    Constraints:

    • 1 <= n <= 10^4
    • 1 <= sum <= 2 * n

    Example:

    Input: n = 7, sum = 6
    Output: 3
    Explanation: Valid pairs are (1, 5), (2, 4), and (3, 3).

    Understanding the Problem

    The core challenge is to find pairs of integers within a specified range that add up to a given sum. This problem is significant in various applications such as finding pairs in arrays, solving two-sum problems, and more.

    Potential pitfalls include counting duplicate pairs (e.g., (1, 5) and (5, 1)) and ensuring that pairs are within the specified range.

    Approach

    To solve this problem, we can use a brute force approach with nested loops to check all possible pairs. Although this approach is not optimal, it is straightforward and easy to understand.

    We can then optimize the solution by reducing unnecessary checks and leveraging mathematical properties.

    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.

    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;
    }
    

    This approach has a time complexity of O(n^2) and space complexity of O(1).

    Optimized Solution

    We can optimize the solution by reducing the range of the inner loop. Instead of iterating from x to n, we can iterate from max(1, sum - n) to min(n, sum - 1).

    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;
    }
    

    This approach still has a time complexity of O(n) but reduces unnecessary checks, making it more efficient.

    Algorithm

    1. Initialize a counter variable to store the number of valid pairs.

    2. Iterate through all possible values of x from 1 to n.

    3. For each x, calculate the corresponding y as sum - x.

    4. Check if y is within the valid range and if y >= x to avoid counting duplicate pairs.

    5. Increment the counter if the pair (x, y) is valid.

    6. Return the counter value.

    Code Implementation

    #include <iostream>
    using namespace std;
    
    // Function to count the number of valid pairs
    int countPairs(int n, int sum) {
        int result = 0;
        for (int x = 1; x <= n; ++x) {
            int y = sum - x;
            // Check if y is within the valid range and y >= x
            if (y >= x && y <= n) {
                result++;
            }
        }
        return result;
    }
    
    int main() {
        int n = 7;
        int sum = 6;
        cout << "Number of valid pairs: " << countPairs(n, sum) << endl;
        return 0;
    }
    

    Complexity Analysis

    The time complexity of the optimized solution is O(n) because we iterate through all possible values of x once. The space complexity is O(1) as we only use a few variables for counting and calculations.

    Edge Cases

    Consider edge cases such as:

    • n = 1, sum = 2: Only one pair (1, 1).
    • n = 10, sum = 20: No valid pairs as the maximum sum is 19.
    • n = 5, sum = 3: Valid pairs are (1, 2).

    Testing

    To test the solution comprehensively, consider a variety of test cases:

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

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller parts and solve each part step-by-step.
    • Think about edge cases and how to handle them.
    • Optimize the solution by reducing unnecessary computations.

    Conclusion

    In this blog post, we discussed how to solve the problem of counting valid pairs with a given sum using a brute force approach and an optimized solution. We analyzed the complexity, considered edge cases, and provided a comprehensive code implementation in C++.

    Understanding and solving such problems is crucial for developing problem-solving skills and improving algorithmic thinking.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free