Taro Logo

Count Equal and Divisible Pairs in an Array

#1 Most AskedEasy
1 view
Topics:
Arrays
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.

Example 1:

Input: nums = [3,1,2,2,2,1,3], k = 2
Output: 4
Explanation:
There are 4 pairs that meet all the requirements:
- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.
- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.
- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.
- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.

Example 2:

Input: nums = [1,2,3,4], k = 1
Output: 0
Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i], k <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of the `nums` array and the value of `k`?
  2. Can `nums` contain negative numbers, zeros, or duplicate values?
  3. Is the pair $(i, j)$ considered distinct from $(j, i)$, or should we only count pairs where $i < j$?
  4. What should be returned if no such valid pairs exist in the array?
  5. Can `k` be zero, and if so, how should division by zero be handled when checking if $(i imes j)$ is divisible by `k`?

Brute Force Solution

Approach

Imagine you have a row of items and you want to find all pairs that share a special connection based on their positions and values. The brute force approach simply tests every single possible pair of items to see if they fit the special rule.

Here's how the algorithm would work step-by-step:

  1. Pick the first item in the group.
  2. Compare it one by one with every other item that comes after it to form pairs.
  3. For each pair you form, check the two conditions: do the items have the exact same value, and when you multiply their positions together, does that result divide evenly into a specific target number?
  4. If both conditions are met, count this pair as a successful match.
  5. Move down the line and repeat the entire checking process for the next starting item.
  6. Continue doing this until every possible pair has been tested.
  7. Add up all the successful matches you found along the way to get your final answer.

Code Implementation

def count_pairs(numbers, target_divisor):
    match_counter = 0

    # Iterate through every possible starting item to ensure we check all unique pairs
    for outer_index in range(len(numbers)):

        # Compare the current item with every subsequent item in the list
        for inner_index in range(outer_index + 1, len(numbers)):

            # Verify if both items share the exact same value and their position product divides evenly
            if numbers[outer_index] == numbers[inner_index] and (outer_index * inner_index) % target_divisor == 0:
                match_counter += 1

    return match_counter

Big(O) Analysis

Time Complexity
O(n²) – For an array of size n, the first step picks each item sequentially as the starting point of a pair. The second step uses a nested loop to compare this item against every other remaining item that comes after it in the array. Checking all possible pairs requires roughly n * (n - 1) / 2 individual evaluations. Because this scales quadratically with the input size n, the operations simplify to a final time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described involves iterating through every possible pair of items using nested loops without utilizing any additional data structures like hash maps or temporary lists. The algorithm only uses a few primitive integer variables to keep track of the current loop indices and the running count of successful matches. Because these scalar variables consume a constant amount of memory that does not scale with the input size N, the auxiliary space complexity remains strictly constant.

Optimal Solution

Approach

Instead of comparing every single pair of items one by one, the optimal strategy organizes items by their values and keeps track of where they are located as you move along. By grouping similar items together, you can quickly calculate how many valid partnerships exist without having to check every combination.

Here's how the algorithm would work step-by-step:

  1. Scan through the collection from the beginning to the end, one item at a time.
  2. As you encounter each item, check your memory to see if you have seen the exact same value previously.
  3. If you have seen that value before, look at the positions where those previous items were located.
  4. Combine the current position with the past positions to see which combinations meet the divisibility requirement.
  5. Keep a running total of all the successful partnerships you discover along the way.
  6. Record the current item and its position in your memory so future items can check against it.
  7. Continue this process until you reach the end of the collection, ensuring you count every valid pair efficiently.

Code Implementation

def count_pairs(nums, divisor):
    from collections import defaultdict

    value_to_indices = defaultdict(list)
    valid_pair_count = 0

    for current_index, current_value in enumerate(nums):
        # Check past occurrences of this value to find potential pairs.
        if current_value in value_to_indices:
            for past_index in value_to_indices[current_value]:
                # Verify the divisibility condition for the index product.
                if (past_index * current_index) % divisor == 0:
                    valid_pair_count += 1

        value_to_indices[current_value].append(current_index)

    return valid_pair_count

Big(O) Analysis

Time Complexity
O(n²) – As we scan through each of the n elements in the array, we check its historical positions stored in our memory to evaluate the divisibility requirement. In the worst-case scenario where all elements share the same value, the first element has 0 past positions to check, the second has 1, the third has 2, and the nth has n-1. This accumulation of past position checks results in approximately n * n/2 total operations, which simplifies to O(n²).
Space Complexity
O(N) – The auxiliary space is driven by a hash map used to store the values of the items as keys, and a list of their past positions as values. As we scan through the collection of size N, every unique item and its indices are recorded in this map. In the worst-case scenario where all elements in the input are unique, the map will store N distinct entries, leading to linear space growth relative to the input size.

Edge Cases

Array with fewer than two elements
How to Handle:
Return zero immediately since a valid pair requires at least two distinct indices.
Value of k is 1
How to Handle:
Since every integer product is divisible by 1, the condition reduces strictly to checking index product divisibility.
Indices product is zero because one or both indices are zero
How to Handle:
Since any number divides zero, pairs involving index 0 will satisfy the divisibility condition if their values match.
All elements in the array are identical
How to Handle:
The algorithm compares every historical index of the value with the current index to test the divisibility condition.
No pairs satisfy both equality and divisibility conditions
How to Handle:
The counter remains zero and the function correctly returns zero at the end.
Maximum possible array length with nested loop approach
How to Handle:
Using an optimized hash map or frequency counting strategy prevents the O(n^2) time limit exceeded error on large inputs.
Large index products causing integer overflow
How to Handle:
Using standard 64-bit integer types for the product of indices prevents overflow before the modulo operation.
0/1 completed