LeetCode 2364: Count Number of Bad Pairs

Problem Description

Explanation:

To solve this problem, we iterate through the array and for each pair of indices (i, j), we check if it forms a bad pair according to the given condition. We compare the differences between the indices and the differences between the values at those indices. If they are not equal, we increment a counter to keep track of the number of bad pairs. At the end, we return the total count of bad pairs found.

  • Initialize a counter to keep track of bad pairs.
  • Iterate through the array and for each pair of indices (i, j):
    • Check if i < j and nums[j] - nums[i] is not equal to j - i.
    • If the condition is met, increment the bad pair counter.
  • Return the total count of bad pairs.

Time complexity: O(n) where n is the number of elements in the array. Space complexity: O(1)

Solutions

class Solution {
    public int countPairs(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (i < j && nums[j] - nums[i] != j - i) {
                    count++;
                }
            }
        }
        return count;
    }
}

Loading editor...