DEV Community

Cover image for LeetCode — 2824. Count Pairs Whose Sum is Less than Target
Ben Pereira
Ben Pereira

Posted on

LeetCode — 2824. Count Pairs Whose Sum is Less than Target

It’s an easy problem with the description being:

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.

It’s a easy problem so we shouldn’t go deep on it. First we read and understand the conditions, and with that we see that we may need to iterate twice nums (it’s possible to not, but add much more pain than purpose), and the condition that the sums needs to be smaller than the target. With that in mind, let’s jump straight to the code:

class Solution {
    public int countPairs(List<Integer> nums, int target) {
        int pairs = 0;

        for(int i=0;i<nums.size();i++) {
            for(int j=(i+1);j<nums.size();j++) {
                if((nums.get(i) + nums.get(j)) < target) {
                    pairs++;
                }
            }
        }

        return pairs;
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime: 2ms, faster than 96.64% of Java online submissions.

Memory Usage:42.23 MB, less than 83.37% of Java online submissions.

As you can see, is as simple as it gets. That’s the code translated from the problem as solution.


That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.

Until next post! :)

Top comments (0)