Skip to main content

Count Number of Bad Pairs - Solution & Explanation

MediumArrayHash TableMathCounting15 min readAsked at: Amazon, Microsoft, Google +1
Practice this problem

Problem Statement

You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].

Return the total number of bad pairs in nums.

 

Example 1:

Input: nums = [4,1,3,3]
Output: 5
Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
There are a total of 5 bad pairs, so we return 5.

Example 2:

Input: nums = [1,2,3,4,5]
Output: 0
Explanation: There are no bad pairs.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Approach Overview

Problem Overview: You are given an integer array nums. A pair of indices (i, j) with i < j is considered bad if j - i != nums[j] - nums[i]. The task is to count how many such bad pairs exist in the array.

Approach 1: Brute Force Pair Check (O(n²) time, O(1) space)

The most direct approach checks every pair of indices. Use two nested loops: the outer loop picks i and the inner loop checks all j > i. For each pair, compute j - i and nums[j] - nums[i]. If the values differ, increment the bad pair count. This approach is straightforward and useful for validating logic during development. However, it performs about n(n-1)/2 comparisons, which becomes too slow for large inputs.

Approach 2: Hash Map with Mathematical Transformation (O(n) time, O(n) space)

Rewrite the condition to reveal a useful pattern. A pair is good when j - i = nums[j] - nums[i]. Rearranging gives nums[j] - j = nums[i] - i. This means two indices form a good pair when the value nums[k] - k is the same for both indices. Instead of directly counting bad pairs, count good pairs using a frequency map.

Iterate through the array once. For each index i, compute key = nums[i] - i. Use a hash table to track how many times this key has appeared. Every previous occurrence forms a good pair with the current index, so add that frequency to the good pair count. Update the map afterward. Finally, compute total possible pairs using n * (n - 1) / 2 and subtract the number of good pairs to get the bad pair count.

This optimization relies on a simple math transformation and efficient lookups using a hash map. The algorithm scans the array once and performs constant-time hash operations, reducing the complexity from quadratic to linear.

Recommended for interviews: The hash map approach is the expected solution. Interviewers want to see the algebraic transformation nums[i] - i that converts the pair condition into a frequency counting problem. Explaining the brute force solution first shows understanding of the problem, while deriving the O(n) hash map solution demonstrates algorithmic insight.

Approach 1: Brute Force Approach

This approach involves checking every possible pair of indices (i, j) where i < j and seeing if they satisfy the condition j - i != nums[j] - nums[i]. This will involve nested loops and checking the condition directly.

The C solution uses two nested loops to iterate through all pairs of indices. The outer loop iterates through each element, and the inner loop checks for every element succeeding it. If the condition for a bad pair is satisfied, we increment the counter. The solution is straightforward but not optimal for large inputs due to its O(n^2) complexity.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2)
Space Complexity: O(1)

Try this approach in the editor →

Approach 2: Optimized Approach using Hash Maps

To improve upon the brute force method, this approach introduces the concept of a hash map (or dictionary) to track the counts of differences calculated by "nums[i] - i". Using this, we can efficiently compute the number of good pairs and then derive the number of bad pairs from it.

The C implementation uses an array to simulate the hash map functionality, storing differences and their occurrences. Each difference is used to quickly calculate how many good & bad pairs exist as the input is processed. This efficient algorithm reduces time complexity to nearly O(n) via its single pass nature.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n)
Space Complexity: O(n)

Try this approach in the editor →

Approach 3: Equation Transformation + Hash Table

According to the problem description, for any i \lt j, if j - i neq nums[j] - nums[i], then (i, j) is a bad pair.

We can transform the equation into i - nums[i] neq j - nums[j]. This suggests using a hash table cnt to count the occurrences of i - nums[i].

While iterating through the array, for the current element nums[i], we add i - cnt[i - nums[i]] to the answer, and then increment the count of i - nums[i] by 1.

Finally, we return the answer.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Brute Force Approach

Time Complexity: O(n^2)
Space Complexity: O(1)

Optimized Approach using Hash Maps

Time Complexity: O(n)
Space Complexity: O(n)

Equation Transformation + Hash Table—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Pair EnumerationO(n²)O(1)Small input sizes or verifying logic during initial implementation
Hash Map with nums[i] - i TransformationO(n)O(n)General case and interview settings where linear time is required

Video Solution

Count Number of Bad Pairs - Leetcode 2364 - Python • NeetCodeIO • 10,974 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Count Number of Bad Pairs easy or hard?
Count Number of Bad Pairs is rated Medium difficulty. The brute force idea is simple, but recognizing the algebraic transformation nums[i] - i and converting the problem into a hash map counting task requires pattern recognition common in mid-level interview problems.
Count Number of Bad Pairs Python/Java solution
The standard implementation uses a dictionary in Python or a HashMap in Java. During a single pass through the array, compute nums[i] - i, update its frequency in the map, and accumulate good pair counts. The final answer is total pairs minus the number of good pairs.
How to solve Count Number of Bad Pairs in O(n)?
Compute key = nums[i] - i while iterating through the array. Use a hash map to count how many times this key has appeared before. Each previous occurrence forms a good pair with the current index. Track total good pairs and subtract them from n*(n-1)/2 to obtain the number of bad pairs in O(n) time.
What is the best approach for Count Number of Bad Pairs?
The optimal approach uses a hash map with a mathematical transformation. By rewriting the condition j - i = nums[j] - nums[i] into nums[i] - i, you can count good pairs with the same value using a frequency map. The number of bad pairs is then total pairs minus good pairs. This runs in O(n) time with O(n) space.
Is Count Number of Bad Pairs asked at Google/Amazon/Meta?
This problem reflects a common interview pattern involving hash maps, pair counting, and mathematical transformations. Variations of this pattern appear in interviews at companies like Amazon, Google, and Meta where candidates must optimize pair comparisons from O(n^2) to O(n).
What data structure is used in Count Number of Bad Pairs?
The optimized solution primarily uses a hash table (hash map) to store the frequency of values nums[i] - i. This allows constant-time lookups and efficient counting of previously seen matching values while scanning the array.
What is the time complexity of Count Number of Bad Pairs?
The brute force approach checks every pair and runs in O(n^2) time. The optimized solution processes the array once while maintaining a hash map of values nums[i] - i, giving O(n) time complexity and O(n) space complexity.

Ready to solve this problem?

Practice Count Number of Bad Pairs with our built-in code editor and test cases.

Practice on FleetCode