Finding a number and its nth multiple in an array in JavaScript

We are required to write a JavaScript function that takes in an array of integers as the first argument and a number, say n, as the second argument.

The function should check whether there exists two such numbers in the array that one is the nth multiple of the other.

If there exists any such pair in the array, the function should return true, false otherwise.

For example, if we have an array containing numbers 2 and 8, and n = 4, then 8 is the 4th multiple of 2 (8 = 2 × 4), so the function should return true.

Problem Example

If the array and the number are:

const arr = [4, 2, 7, 8, 3, 9, 5];
const n = 4;

Then the output should be:

true

Because there exist the numbers 2 and 8 in the array and 8 = 2 × 4.

Solution Using Set

The most efficient approach uses a Set to store visited numbers and checks if either the nth multiple or the nth divisor exists:

const arr = [4, 2, 7, 8, 3, 9, 5];
const n = 4;

const containsNthMultiple = (arr = [], n = 1) => {
    const hash = new Set();
    
    for (let i = 0; i < arr.length; i++) {
        const el = arr[i];
        const left = el / n;   // Check if el is nth multiple of some number
        const right = el * n;  // Check if some number is nth multiple of el
        
        if (hash.has(left) || hash.has(right)) {
            return true;
        }
        
        hash.add(el);
    }
    
    return false;
};

console.log(containsNthMultiple(arr, n));
true

How It Works

The algorithm works by:

  • Creating a Set to store previously seen numbers
  • For each element, calculating both its nth divisor (el/n) and nth multiple (el*n)
  • Checking if either value already exists in the Set
  • If found, returning true immediately
  • Otherwise, adding the current element to the Set and continuing

Additional Examples

// Example 1: No nth multiple pairs
const arr1 = [1, 3, 5, 7];
const n1 = 2;
console.log("Example 1:", containsNthMultiple(arr1, n1));

// Example 2: Found pair (6 and 18, where 18 = 6 * 3)
const arr2 = [6, 10, 18, 25];
const n2 = 3;
console.log("Example 2:", containsNthMultiple(arr2, n2));

// Example 3: Self multiple (when n = 1)
const arr3 = [5, 10, 15];
const n3 = 1;
console.log("Example 3:", containsNthMultiple(arr3, n3));
Example 1: false
Example 2: true
Example 3: true

Time and Space Complexity

  • Time Complexity: O(n) - Single pass through the array
  • Space Complexity: O(n) - Set storage for visited elements

Conclusion

This solution efficiently finds nth multiple pairs in an array using a Set for O(1) lookup time. The algorithm handles both directions of the multiple relationship in a single pass.

Updated on: 2026-03-15T23:19:00+05:30

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements