EasyNo. 2176

Count Equal and Divisible Pairs in an Array — LeetCode 2176 Python Solution

Topics
Array
Reading time
2 min

The problem

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

Input
nums = [3,1,2,2,2,1,3], k = 2
Output
4
Explanation
There are 4 pairs that meet all the requirements:

Python solution

PythonSolution
class Solution:
    def countPairs(self, nums: List[int], k: int) -> int:
        ans = 0
        for j, y in enumerate(nums):
            for i, x in enumerate(nums[:j]):
                ans += int(x == y and i * j % k == 0)
        return ans

Complexity

Time
O(n2)where n is the length of the array nums
Space · auxiliary
O(1)

Related problems

Related problems
No.ProblemDifficulty
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy
0665Non-decreasing ArrayMedium
0674Longest Continuous Increasing SubsequenceEasy
0699Falling SquaresHard

Frequently asked questions

How hard is LeetCode 2176. Count Equal and Divisible Pairs in an Array?

LeetCode 2176. Count Equal and Divisible Pairs in an Array is rated Easy on LeetCode.

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

The Python solution on this page runs in O(n2), where n is the length of the array \textit{nums}.

What is the space complexity of LeetCode 2176. Count Equal and Divisible Pairs in an Array?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2176. Count Equal and Divisible Pairs in an Array cover?

LeetCode 2176. Count Equal and Divisible Pairs in an Array is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.