Building an array of specific size with consecutive element sum being perfect square in JavaScript

We need to create a JavaScript function that arranges numbers 1 to n such that the sum of each pair of consecutive elements forms a perfect square. This is a classic backtracking problem that requires careful arrangement of numbers.

Problem Understanding

For an array of size n, we must arrange integers 1 through n where each adjacent pair sums to a perfect square. For example, if two consecutive numbers are 9 and 7, their sum (16) should be a perfect square (4²).

Algorithm Approach

We use a backtracking algorithm with these steps:

  • Try each unused number from 1 to n
  • Check if it forms a perfect square sum with the previous element
  • If valid, add to result and continue recursively
  • If no solution found, backtrack and try the next number

Implementation

const n = 15;

const buildSquaresArray = (n = 1, res = []) => {
    const helper = (res, set, n) => {
        if (set.size === n) {
            return true;
        }
        
        for (let i = 1; i 

Output

[
  9,
  7,
  2,
  14,
  11,
  5,
  4,
  12,
  13,
  3,
  6,
  10,
  15,
  1,
  8
]

How It Works

Let's verify a few consecutive pairs from the result:

const result = [9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8];

// Check first few consecutive pairs
console.log("9 + 7 =", 9 + 7, "?16 =", Math.sqrt(16)); // Perfect square: 4²
console.log("7 + 2 =", 7 + 2, "?9 =", Math.sqrt(9));   // Perfect square: 3²
console.log("2 + 14 =", 2 + 14, "?16 =", Math.sqrt(16)); // Perfect square: 4²
console.log("14 + 11 =", 14 + 11, "?25 =", Math.sqrt(25)); // Perfect square: 5²
9 + 7 = 16 ?16 = 4
7 + 2 = 9 ?9 = 3
2 + 14 = 16 ?16 = 4
14 + 11 = 25 ?25 = 5

Key Points

  • The algorithm uses backtracking to explore all possible arrangements
  • We use a Set to track used numbers for O(1) lookup
  • Perfect square validation: Math.sqrt(sum) % 1 === 0
  • Building the array from front using unshift() for efficiency

Conclusion

This backtracking solution efficiently finds an arrangement where consecutive elements sum to perfect squares. The algorithm explores possibilities systematically and backtracks when no valid solution exists for the current path.

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

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements