You are given an array nums
consisting of distinct positive integers. We call an array “good” if for any two elements a
and b
(where a != b
), the product a * b
is not present in the array nums
. Your task is to determine whether the given array is “good”.
Write a Python function to check if the array is good.
nums
distinct and positive?Assumptions based on common problem constraints:
10^4
elements.[1, 10^9]
.nums
for O(1) average time complexity check.(a, b)
in nums
and check if a * b
exists in the set.Let’s implement the solution step by step.
from typing import List
def is_good_array(nums: List[int]) -> bool:
num_set = set(nums)
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
product = nums[i] * nums[j]
if product in num_set:
return False
return True
This code ensures that we iterate over every unique pair of elements in the array, check if their product already exists in the set, and return False
immediately if it does. If no such product is found, the array is determined to be “good.”
num_set
from the list nums
to allow O(1) time complexity when checking for the presence of elements.(nums[i], nums[j])
where i < j
.nums[i] * nums[j]
and check if it’s present in num_set
.False
. If we complete the loop without finding any such product, we return True
.Considering the potential size of the input and constraints, this approach will efficiently determine if the array is “good.”
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?