Check If It Is a Good Array - Problem

Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers.

The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.

Return True if the array is good otherwise return False.

Input & Output

Example 1 — Good Array
$ Input: nums = [12,5,7,23]
Output: true
💡 Note: GCD(12,5,7,23) = GCD(GCD(GCD(12,5),7),23) = GCD(GCD(1,7),23) = GCD(1,23) = 1. Since GCD equals 1, we can form sum of 1 using integer combinations.
Example 2 — Not Good Array
$ Input: nums = [29,6,10]
Output: true
💡 Note: GCD(29,6,10) = GCD(GCD(29,6),10) = GCD(1,10) = 1. Since GCD equals 1, we can form sum of 1 using integer combinations.
Example 3 — All Even Numbers
$ Input: nums = [4,6,10,12]
Output: false
💡 Note: All numbers are even, so GCD(4,6,10,12) = 2 ≠ 1. Cannot form sum of 1 since all combinations will be even.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Check If It Is a Good Array INPUT Array nums[] 12 5 7 23 [0] [1] [2] [3] Find subset and integers x, y, z... such that: a*x + b*y + c*z = 1 Goal: Check if sum of 1 is achievable ALGORITHM STEPS 1 Bezout's Identity GCD(a,b)=1 means ax+by=1 2 Compute GCD Find GCD of all elements 3 Check Result If GCD == 1, return true 4 Time: O(n log m) Space: O(1) GCD Calculation: GCD(12, 5) = 1 GCD(1, 7) = 1 GCD(1, 23) = 1 Final GCD = 1 FINAL RESULT true Array is GOOD Why true? GCD(12,5,7,23) = 1 By Bezout's Identity: exists x,y: 5x + 7y = 1 Example Solution: 5 * 3 + 7 * (-2) = 1 15 - 14 = 1 OK - Valid! Key Insight: By Bezout's Identity, integers x and y exist such that ax + by = GCD(a,b). For a linear combination of array elements to equal 1, the GCD of ALL elements must be 1. Simply compute GCD iteratively! TutorialsPoint - Check If It Is a Good Array | Optimal Solution (GCD Approach)
Asked in
Google 12 Microsoft 8
28.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen