↓Skip to main content
  1. LeetCode/

LeetCode 2176: Count Equal and Divisible Pairs in an Array

·1 min· ·
LeetCode Easy Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-04-17

  • Submissions: Wrong Answer → Accepted

Approach
#

With n <= 100, enumerate every pair i < j (Array Template 4). Two conditions: nums[i] == nums[j], and the index product i * j divisible by k.

My Attempts
#

Attempt 1 wrote (nums[i] * nums[j]) // 2, using values and integer division by 2 as the condition. For nums = [1, 1], k = 4, 0 × 1 = 0 is divisible by 4, so the answer is 1; it computed 1 × 1 // 2 = 0, which is falsy, and returned 0. Changing to not (i * j) % k passed.

Solution
#

class Solution:
    def countPairs(self, nums: List[int], k: int) -> int:
        n = len(nums)
        return sum(nums[i] == nums[j] and i * j % k == 0
                   for i in range(n) for j in range(i + 1, n))

Complexity
#

Time O(n²), space O(1).

Mistakes to Avoid
#

  • The product uses indices, not values.
  • “Divisible by k” is % k == 0.

Interview Explanation
#

With n small, I enumerate all pairs and check equal values and an index product divisible by k. Time O(n²).

Related

LeetCode 1431: Kids With the Greatest Number of Candies
·1 min
LeetCode Easy Array
LeetCode 1431 note: compute the maximum once; a kid is True when their candies plus the extra reach >= the maximum, since a tie counts
LeetCode 3487: Maximum Unique Subarray Sum After Deletion
·2 mins
LeetCode Easy Greedy Hash-Table Array
LeetCode 3487 note: free deletion means picking distinct values; take every non-negative one, or only the maximum when all are negative
LeetCode 3507: Minimum Pair Removal to Sort Array I
·2 mins
LeetCode Easy Simulation Array
LeetCode 3507 note: n is tiny, so simulate; the right side of a slice assignment must be a list
LeetCode 3131: Find the Integer Added to Array I
·1 min
LeetCode Easy Array
LeetCode 3131 note: every element gets the same x, so x is the difference of the two minimums (or of the sums divided by the length)
LeetCode 3074: Apple Redistribution into Boxes
·1 min
LeetCode Easy Array Greedy Sorting
LeetCode 3074 note: apples can be split freely, so take boxes from the largest capacity until the total fits every apple
LeetCode 2099: Find Subsequence of Length K With the Largest Sum
·1 min
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
LeetCode 2099 note: pick the k largest values along with their indices, then sort by index to restore the original order