Maximum Subarray With Equal Products: solution and explanation

Learn how to find the maximum subarray with equal products by combining array traversal with mathematical constraints to optimize a brute-force approach.

beginner10 min readBy sahil1678kumarReviewed by sahil1678kumar · 24 Nov 2026

Practise this problem, or start a mock DSA round on it

Finding the longest contiguous subarray where the product of its elements equals the product of their greatest common divisor and least common multiple is a classic test of array traversal and basic number theory. It is worth knowing because it teaches you how to use mathematical constraints to optimize what looks like a slow brute-force solution into a highly efficient algorithm.

The problem

Suppose you are given a sequence of positive integers. Your task is to look at all possible contiguous slices (subarrays) of this sequence.

For every slice, you need to calculate three values:

  1. The total product of all numbers in the slice.
  2. The least common multiple (LCM) of the numbers.
  3. The greatest common divisor (GCD) of the numbers.

A slice is considered valid if its total product is exactly equal to its LCM multiplied by its GCD. Your goal is to find the maximum number of elements in any valid slice. If no such slice exists, you return 0.

Let us look at a small example to make this concrete. Suppose our array is [4, 2, 1].

We can check the slices starting from the first element:

  • The slice [4] has a product of 4. Its LCM is 4 and its GCD is 4. The product of LCM and GCD is 16. Since 4 does not equal 16, this slice is invalid.
  • The slice [4, 2] has a product of 8. The LCM of 4 and 2 is 4. The GCD of 4 and 2 is 2. The product of LCM and GCD is 8. Since 8 equals 8, this slice is valid. Its length is 2.
  • The slice [4, 2, 1] has a product of 8. The LCM of 4, 2, and 1 is 4. The GCD of 4, 2, and 1 is 1. The product of LCM and GCD is 4. Since 8 does not equal 4, this slice is invalid.

If we check all other slices, we will find that [4, 2] and [2, 1] are the longest valid slices, both having a length of 2. Therefore, the answer is 2.

The key idea

A naive approach would check every single subarray. For each one, it would calculate the product, the LCM, and the GCD from scratch. This is slow and repetitive.

The first improvement is to calculate these values on the fly. As we expand a subarray to the right by adding one element at a time, we can update our running product, running LCM, and running GCD. This saves us from recalculating everything from the beginning of the slice.

The second improvement is the real secret to this problem. We are given a specific constraint: the numbers in the array will not exceed 10. This small detail changes everything.

Think about the maximum possible values for our mathematical operations. The LCM of any combination of numbers from 1 to 10 is at most 2520. You get this by finding the LCM of all numbers from 1 to 10. The GCD of any numbers up to 10 is at most 10. Therefore, the maximum possible value for LCM * GCD is 2520 multiplied by 10, which is 25200.

Because our array only contains positive integers, the running product will grow very quickly as we multiply more numbers together. Once our running product exceeds 25200, it is mathematically impossible for it to ever equal LCM * GCD again for that specific starting position. The product will keep growing, but LCM * GCD is capped at 25200.

This means we can stop expanding our current subarray as soon as the product exceeds 25200. We break out of the inner loop early and move on to the next starting position. This simple check prevents integer overflow and drastically reduces the number of operations.

Approach

Here is how we turn this idea into a working algorithm:

  1. Initialize a variable to keep track of the maximum valid length found so far. Set it to 0.
  2. Start an outer loop to pick the starting index of the subarray.
  3. For each starting index, initialize three variables: the running product, the running LCM, and the running GCD. Set all three to the value of the element at the starting index.
  4. Start an inner loop from the starting index to the end of the array to expand the subarray one element at a time.
  5. In the inner loop, multiply the running product by the current element.
  6. Check if the running product is greater than 25200. If it is, break out of the inner loop immediately.
  7. Update the running LCM and running GCD using the current element.
  8. Check if the running product equals the product of the running LCM and running GCD. If it does, calculate the length of the current subarray and update the maximum length if this one is longer.
  9. After checking all possible starting positions, return the maximum length.

Here is a visual representation of the logic inside the loops:

Code

import math
from typing import List

class Solution:
    def maxLength(self, nums: List[int]) -> int:
        ans = 0
        n = len(nums)
        for i in range(n):
            p = 1
            l = nums[i]
            g = nums[i]
            for j in range(i, n):
                p *= nums[j]
                if p > 25200:
                    break
                l = math.lcm(l, nums[j])
                g = math.gcd(g, nums[j])
                if p == l * g:
                    ans = max(ans, j - i + 1)
        return ans

Complexity

Time Complexity: O(n^2) in the worst case, where n is the length of the array. The outer loop runs n times. The inner loop could theoretically run n times if the array is filled mostly with 1s, because multiplying by 1 does not increase the product, meaning we never hit the 25200 limit. However, for arrays with larger numbers, the inner loop breaks very quickly (usually in less than 15 steps). Even in the worst case, given that n is small (up to 100), O(n^2) requires at most 10,000 iterations, which executes in a fraction of a millisecond.

Space Complexity: O(1). We only allocate a few variables to store the running product, LCM, GCD, and the maximum length. We do not create any new arrays or data structures that scale with the input size.

Edge cases and common mistakes

There are a few scenarios where this problem can trip you up:

  • Arrays filled with 1s: If the array is [1, 1, 1, 1], the product will always be 1, and the LCM * GCD will always be 1. The early break condition (prod > 25200) will never trigger. Your algorithm must be efficient enough to handle the full O(n^2) traversal for this case.
  • Single element subarrays: A common mistake is assuming a single element is always valid. If the element is 2, the product is 2, the LCM is 2, and the GCD is 2. LCM * GCD is 4. Since 2 does not equal 4, it is invalid. A single element is only valid if it is exactly 1.
  • Forgetting that GCD and LCM take time: While calculating GCD and LCM is fast, it is not strictly O(1). The Euclidean algorithm for GCD takes logarithmic time based on the values. Since our values are capped at 2520, this takes a negligible and constant amount of time, but it is a good detail to mention to an interviewer.

Follow-ups an interviewer may ask

1. What happens if the array can contain zeros? If the array contains zeros, our logic breaks. Multiplying by zero makes the product zero, and calculating the LCM or GCD with zero requires special handling. To fix this, we would treat zeros as boundaries. We would split the array at every zero and run our algorithm independently on the resulting zero-free segments.

2. How does the early break prevent integer overflow? In languages like Java or C++, standard integers have a maximum value of around 2.1 billion. If we multiply many numbers together, we can easily exceed this limit, causing the numbers to wrap around into negative values and producing incorrect results. By breaking out of the loop as soon as the product hits 25200, we guarantee that our product variable never gets anywhere near the integer limit.

3. Can we solve this in O(n) time? There is no known O(n) solution for this specific problem. The relationship between product, LCM, and GCD across arbitrary subsets does not allow us to reuse calculations from previous starting positions in a way that avoids nested loops. The O(n^2) approach with an early exit is the optimal strategy.

4. What if the maximum array value was 100 instead of 10? If the maximum value was 100, the maximum possible LCM would be astronomically larger. The early break threshold would have to be set so high that it would no longer prevent integer overflow for standard 32-bit integers. We would need to use 64-bit integers (like long in Java or C++) or BigInts, and the inner loop would run for many more iterations before breaking.

Mock interview

Now explain it like you would in the interview

Knowing the solution isn't the same as explaining it under questions. The interviewer starts you on this problem, asks you to clarify, code while you talk and defend each line.

  • Starts on this exact problem, in a real editor
  • Judged on hidden tests, with follow-up questions
  • A scored report that quotes your answers and says what to fix
Explain it in a mock interview Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
Coding problems•beginner

Stone Removal Game: solution and explanation

7 min read
Coding problems•intermediate

Product Of The Last K Numbers: solution and explanation

7 min read
DSA patterns•intermediate

The two pointers pattern

15 min read
DSA patterns•intermediate

The sliding window pattern

11 min read