LeetCode 2176: Count Equal and Divisible Pairs in an Array Solution

Master LeetCode problem 2176 (Count Equal and Divisible Pairs in an Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2176. Count Equal and Divisible Pairs in an Array

Easy

Problem Explanation

Explanation:

To solve this problem, we can iterate through all pairs of indices (i, j) where 0 <= i < j < n. For each pair, we check if nums[i] == nums[j] and if (i * j) is divisible by k. If both conditions are met, we increment a counter to keep track of the valid pairs.

Algorithmic Idea:

  1. Initialize a counter count to 0.
  2. Iterate through all pairs of indices (i, j) where 0 <= i < j < n.
  3. Check if nums[i] == nums[j] and if (i * j) is divisible by k.
  4. If both conditions are met, increment the counter count.
  5. Return the final count after iterating through all pairs.

Time Complexity:

The time complexity of this solution is O(n^2), where n is the length of the input array nums.

Space Complexity:

The space complexity is O(1) as we are using a constant amount of extra space.

:

Solution Code

class Solution {
    public int countPairs(int[] nums, int k) {
        int n = nums.length;
        int count = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i] == nums[j] && (i * j) % k == 0) {
                    count++;
                }
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2176 (Count Equal and Divisible Pairs in an Array)?

This page provides optimized solutions for LeetCode problem 2176 (Count Equal and Divisible Pairs in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2176 (Count Equal and Divisible Pairs in an Array)?

The time complexity for LeetCode 2176 (Count Equal and Divisible Pairs in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2176 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2176 in Java, C++, or Python.

Back to LeetCode Solutions