algoadvance

Leetcode 2824. Count Pairs Whose Sum is Less than Target

Problem Statement

Given a 0-indexed integer array nums of length n and an integer target, return the number of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target.

Clarifying Questions

  1. Constraints:
    • What is the range and limit of the integer values in nums and the target?
    • Can nums contain negative numbers?
    • Are there any duplicate numbers in nums?
  2. Output:
    • Should the function only count pairs without returning the pairs themselves?

Strategy

To solve this problem, we need to count all pairs (i, j) such that the sum of the elements at these indices is less than target. Here’s the step-by-step strategy:

  1. Brute Force Approach:
    • Use a nested loop to check every possible pair.
    • For each pair (i, j), where 0 <= i < j < n, check if nums[i] + nums[j] < target.
    • If the condition holds true, increment the count.
  2. Optimized Approach (Optional for Interview):
    • Sort the array nums.
    • Use two pointers to find pairs in a more efficient way than the brute force approach.
    • One pointer starts at the beginning (left) and the other at the end (right).
    • Move the pointers towards each other based on the sum comparison with the target.

Given typical constraints in coding interviews, starting with the brute force solution to illustrate understanding and then optimizing if required is a good approach.

Code

Here’s the brute force solution to count the pairs:

#include <vector>
using namespace std;

class Solution {
public:
    int countPairsLessThanTarget(vector<int>& nums, int target) {
        int count = 0;
        int n = nums.size();
        
        for (int i = 0; i < n - 1; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] < target) {
                    ++count;
                }
            }
        }
        
        return count;
    }
};

Time Complexity

Discussion

Would you need the optimized solution with two pointers as well?

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI