TheAlgorithms/JavaScript · error · Error

Triplet cannot exist with the given array

Error message

Triplet cannot exist with the given array

What it means

Thrown by maxProductOfThree(arrayItems) (plain Error) when arrayItems.length < 3. The algorithm tracks the three largest and two smallest values in a single pass, which is only meaningful when at least three numbers exist; fewer than three means no triplet product is defined.

Source

Thrown at Dynamic-Programming/MaxProductOfThree.js:11

/**
 *  Given an array of numbers, return the maximum product
 *  of 3 numbers from the array
 *  https://wsvincent.com/javascript-three-sum-highest-product-of-three-numbers/
 * @param {number[]} arrayItems
 * @returns number
 */
export function maxProductOfThree(arrayItems) {
  // if size is less than 3, no triplet exists
  const n = arrayItems.length
  if (n < 3) throw new Error('Triplet cannot exist with the given array')
  let max1 = arrayItems[0]
  let max2 = null
  let max3 = null
  let min1 = arrayItems[0]
  let min2 = null
  for (let i = 1; i < n; i++) {
    if (arrayItems[i] > max1) {
      max3 = max2
      max2 = max1
      max1 = arrayItems[i]
    } else if (max2 === null || arrayItems[i] > max2) {
      max3 = max2
      max2 = arrayItems[i]
    } else if (max3 === null || arrayItems[i] > max3) {
      max3 = arrayItems[i]
    }
    if (arrayItems[i] < min1) {
      min2 = min1

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Check arrayItems.length >= 3 before calling.
  2. If a smaller array is legitimate in your domain, define a fallback (e.g. product of all elements) rather than calling the function.
  3. Filter out degenerate groups before aggregating.
  4. Validate input size at the API boundary and return a domain-specific error.

Example fix

// before
const p = maxProductOfThree(arr) // throws when arr.length < 3

// after
if (arr.length < 3) throw new RangeError('need >= 3 numbers')
const p = maxProductOfThree(arr)
Defensive patterns

Strategy: validation

Validate before calling

function safeMaxProductOfThree(arr) {
  if (!Array.isArray(arr) || arr.length < 3) {
    throw new RangeError('array must contain at least 3 numbers')
  }
  return maxProductOfThree(arr)
}

Type guard

const hasTriplet = (arr) => Array.isArray(arr) && arr.length >= 3

Try / catch

try {
  return maxProductOfThree(arr)
} catch (e) {
  if (e instanceof Error && /triplet/i.test(e.message)) {
    // not enough elements; return a domain fallback or rethrow as a clearer error
  } else throw e
}

Prevention

When it happens

Trigger: maxProductOfThree([]); maxProductOfThree([5]); maxProductOfThree([1, 2]).

Common situations: Filtered/downsampled datasets that shrank below 3; empty input from a failed fetch; arrays built from a group-by whose group happened to have 1-2 members.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/9d32d193bd7bc90d. Report an issue: GitHub.