3162. Find the Number of Good Pairs I
Problem Description
You are given two integer arrays, nums1
and nums2
, with lengths n
and m
, respectively. You also have a positive integer k
. A pair (i, j)
is considered "good" if the element nums1[i]
from the first array is divisible by the product of nums2[j]
and k
. Indices i
range from 0
to n-1
, and indices j
range from 0
to m-1
. The task is to find the total number of such "good" pairs.
Intuition
To solve the problem, you can use a simple strategy: iterate through every possible pair of elements from nums1
and nums2
. For each combination (x, y)
, check whether x % (y * k) == 0
, which means x
is perfectly divisible by y
multiplied by k
. If this condition holds true, it means the pair (i, j)
is "good" and contributes to the count. This is an exhaustive search approach that checks each pair without any optimization but is straightforward to implement for a smaller range of input sizes.
Solution Approach
Solution 1: Brute Force Enumeration
The solution uses a straightforward brute force enumeration method to find the "good" pairs:
- Nested Iteration: The algorithm iterates through each element
x
innums1
and each elementy
innums2
. - Condition Check: For every pair
(x, y)
, it checks if the conditionx % (y * k) == 0
is satisfied, which meansx
is divisible by the product ofy
andk
. - Counting Good Pairs: If the condition is true, it increments a counter to keep track of the number of "good" pairs.
- Summation: The algorithm utilizes a generator expression within the
sum()
function to execute the above logic concisely. The expression iterates over each pair and yieldsTrue
values interpreted as1
for pairs meeting the condition.
The Python implementation is encapsulated in the numberOfPairs
method, leveraging Python's functional capabilities for compactness and clarity:
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
return sum(x % (y * k) == 0 for x in nums1 for y in nums2)
This brute force approach is simple and effective for small input sizes, ensuring all potential pairings are considered without missing any potential "good" pairs.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
To illustrate the solution approach, let's consider a small example:
nums1 = [4, 9]
nums2 = [1, 2]
k = 2
We need to find the total number of "good" pairs (i, j)
where nums1[i]
is divisible by nums2[j] * k
.
-
Initialize Counters: Start with a count of
0
for keeping track of "good" pairs. -
Iterate Over Pairs:
-
For
i = 0, nums1[0] = 4
:- For
j = 0, nums2[0] = 1
:- Check if
4 % (1 * 2) == 0
:- Calculation:
4 % 2 == 0
is true, so this is a "good" pair. - Increment count:
count = 1
.
- Calculation:
- Check if
- For
j = 1, nums2[1] = 2
:- Check if
4 % (2 * 2) == 0
:- Calculation:
4 % 4 == 0
is true, so this is also a "good" pair. - Increment count:
count = 2
.
- Calculation:
- Check if
- For
-
For
i = 1, nums1[1] = 9
:- For
j = 0, nums2[0] = 1
:- Check if
9 % (1 * 2) == 0
:- Calculation:
9 % 2 == 0
is false, not a "good" pair.
- Calculation:
- Check if
- For
j = 1, nums2[1] = 2
:- Check if
9 % (2 * 2) == 0
:- Calculation:
9 % 4 == 0
is false, not a "good" pair.
- Calculation:
- Check if
- For
-
-
Final Count: The total count of "good" pairs is
2
.
Through this example, the brute force approach iterates through all possible pairs and checks the divisibility condition, incrementing the counter for every "good" pair found. This process ensures that the solution captures all valid pairings.
Solution Implementation
1from typing import List
2
3class Solution:
4 def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
5 # Initialize a counter for valid pairs
6 count = 0
7
8 # Iterate through each element in nums1
9 for x in nums1:
10 # Iterate through each element in nums2
11 for y in nums2:
12 # Check if x is divisible by y multiplied by k
13 if x % (y * k) == 0:
14 # Increment the count if the condition is true
15 count += 1
16
17 # Return the total count of valid pairs
18 return count
19
1class Solution {
2 public int numberOfPairs(int[] nums1, int[] nums2, int k) {
3 int ans = 0; // Initialize the count for pairs
4 for (int x : nums1) { // Iterate through each element x in nums1
5 for (int y : nums2) { // Iterate through each element y in nums2
6 // Check if x is divisible by the product of y and k
7 if (x % (y * k) == 0) {
8 ++ans; // Increment the pairs count if condition is met
9 }
10 }
11 }
12 return ans; // Return the total number of pairs
13 }
14}
15
1#include <vector>
2using namespace std;
3
4class Solution {
5public:
6 int numberOfPairs(vector<int>& nums1, vector<int>& nums2, int k) {
7 int resultCount = 0; // Initialize the result counter
8
9 // Iterate through each element in the first vector
10 for (int num1 : nums1) {
11 // Iterate through each element in the second vector
12 for (int num2 : nums2) {
13 // Check if the element from nums1 is divisible by the product of an element from nums2 and k
14 if (num1 % (num2 * k) == 0) {
15 ++resultCount; // Increment the count of valid pairs
16 }
17 }
18 }
19
20 return resultCount; // Return the total count of valid pairs
21 }
22};
23
1/**
2 * Calculates the number of valid pairs (x, y) such that x from nums1 and y from nums2 satisfy x % (y * k) === 0.
3 *
4 * @param nums1 - First input array of numbers.
5 * @param nums2 - Second input array of numbers.
6 * @param k - A number to multiply with elements from nums2.
7 * @returns number of pairs satisfying the condition.
8 */
9function numberOfPairs(nums1: number[], nums2: number[], k: number): number {
10 let ans = 0; // Initialize the counter for valid pairs
11
12 // Iterate over each element in nums1
13 for (const num1 of nums1) {
14 // Iterate over each element in nums2
15 for (const num2 of nums2) {
16 // Check if the condition x % (y * k) === 0 is met
17 if (num1 % (num2 * k) === 0) {
18 ++ans; // Increment the count if the condition is satisfied
19 }
20 }
21 }
22
23 return ans; // Return the number of valid pairs
24}
25
Time and Space Complexity
The time complexity of the code is O(m * n)
, where m
and n
are the lengths of the arrays nums1
and nums2
, respectively. This is because the code uses a nested loop to iterate over each element in nums1
and nums2
, resulting in a total of m * n
iterations. Each iteration performs a modulus operation and a comparison, both of which can be considered O(1)
operations.
The space complexity is O(1)
since no additional space is used that scales with the size of the input arrays. The only extra space used is for a few variables, which is constant in size.
Learn more about how to find time and space complexity quickly.
Which of the following array represent a max heap?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!