Maximum Subarray With Equal Products - Problem

You are given an array of positive integers nums. Your task is to find the longest subarray that satisfies a special mathematical property.

A subarray is called product equivalent if it satisfies the equation:

product(arr) = lcm(arr) × gcd(arr)

Where:

  • product(arr) is the product of all elements in the subarray
  • gcd(arr) is the Greatest Common Divisor of all elements
  • lcm(arr) is the Least Common Multiple of all elements

Goal: Return the length of the longest product equivalent subarray.

Example: For array [6, 10, 15], we have gcd = 1, lcm = 30, product = 900. Since 30 × 1 ≠ 900, this subarray is not product equivalent.

Input & Output

example_1.py — Basic Case
$ Input: [6, 10, 15]
Output: 2
💡 Note: The longest product equivalent subarray is [6,10] with length 2. For [6,10]: product=60, gcd=2, lcm=30, and 60 = 2×30. Also [10,15] works: product=150, gcd=5, lcm=30, and 150 = 5×30.
example_2.py — Single Element
$ Input: [12]
Output: 0
💡 Note: For [12]: product=12, gcd=12, lcm=12, but 12 ≠ 12×12 = 144. So no valid subarray exists.
example_3.py — Multiple Valid Subarrays
$ Input: [2, 4, 6, 8]
Output: 2
💡 Note: Several length-2 subarrays work: [2,4] has product=8, gcd=2, lcm=4, and 8 = 2×4. The maximum length is 2.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 104
  • All elements are positive integers

Visualization

Tap to expand
Product Equivalent Property: product = gcd × lcmExample: [6, 10]Product = 6 × 10 = 60GCD(6,10) = 2, LCM(6,10) = 30Check: 60 = 2 × 30 ✓ TRUECounter-example: [6, 10, 15]Product = 6 × 10 × 15 = 900GCD(6,10,15) = 1, LCM(6,10,15) = 30Check: 900 ≠ 1 × 30 = 30 ✗ FALSEMathematical Insight:• For any set of numbers: product ≥ gcd × lcm• Equality holds when numbers have specific relationships• Common case: two numbers where one divides the other• Rare for larger sets, making brute force viable
Understanding the Visualization
1
Calculate GCD
Find the greatest common divisor of all elements
2
Calculate LCM
Find the least common multiple of all elements
3
Calculate Product
Multiply all elements together
4
Check Equality
Verify if product equals gcd × lcm
Key Takeaway
🎯 Key Insight: The product = gcd × lcm property is mathematically rare, occurring mainly in small subarrays with special number relationships, making exhaustive search practical.
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 5
28.4K Views
Medium Frequency
~18 min Avg. Time
847 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