Find the Number of Good Pairs I - Complete Solution Guide
Find the Number of Good Pairs I is LeetCode problem 3162, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given 2 integer arrays nums1 and nums2 of lengths n and m respectively. You are also given a positive integer k . A pair (i, j) is called good if nums1[i] is divisible by nums2[j] * k ( 0 <= i <= n - 1 , 0 <= j <= m - 1 ). Return the total number of good pairs. Example 1: Input: nums1 = [1,3,4], nums2 = [1,3,4], k = 1 Output: 5 Explanation: The 5 good pairs are (0, 0) , (1, 0) , (1, 1) , (2, 0) , and (2, 2) . Example 2: Input: nums1 = [1,2,4,12], nums2 = [2,4], k = 3 Output: 2 Explanatio
Detailed Explanation
The problem asks you to count the number of 'good pairs' between two integer arrays, `nums1` and `nums2`. A pair `(i, j)` is considered 'good' if the element at index `i` in `nums1` (i.e., `nums1[i]`) is perfectly divisible by the product of the element at index `j` in `nums2` (i.e., `nums2[j]`) and a given positive integer `k`. The input consists of two integer arrays and a positive integer `k`. The output is a single integer representing the total count of good pairs.
Solution Approach
The provided solution uses a brute-force approach with nested loops. It iterates through each element of `nums1` and for each element, it iterates through each element of `nums2`. Inside the inner loop, it checks if the divisibility condition is met. If it is, a counter `count` is incremented. Finally, the function returns the value of `count`.
Step-by-Step Algorithm
- Initialize a counter variable `count` to 0.
- Iterate through each element `nums1[i]` of the `nums1` array using a `for` loop.
- For each `nums1[i]`, iterate through each element `nums2[j]` of the `nums2` array using another nested `for` loop.
- Inside the inner loop, calculate `nums2[j] * k`.
- Check if `nums1[i]` is divisible by `nums2[j] * k` using the modulo operator: `nums1[i] % (nums2[j] * k) == 0`.
- If the condition is true (divisible), increment the `count`.
- After iterating through all pairs, return the final value of `count`.
Key Insights
- The core logic involves checking divisibility using the modulo operator (`%`). If `nums1[i] % (nums2[j] * k) == 0`, then `nums1[i]` is divisible by `nums2[j] * k`.
- A nested loop is the most straightforward approach to iterate through all possible pairs of indices `(i, j)` from `nums1` and `nums2` respectively.
- The problem constraints (small array sizes) suggest a brute-force approach is acceptable. More efficient solutions (e.g., using hash tables for larger inputs) are not necessary here.
Complexity Analysis
Time Complexity: O(n*m)
Space Complexity: O(1)
Topics
This problem involves: Array, Hash Table.
Companies
Asked at: Airbus SE.