Permutation of numbers such that sum of two consecutive numbers is a perfect square
Last Updated :
10 Mar, 2023
Prerequisite: Hamiltonian Cycle Given an integer n(>=2), find a permutation of numbers from 1 to n such that the sum of two consecutive numbers of that permutation is a perfect square. If that kind of permutation is not possible to print "No Solution".
Examples:
Input : 17
Output : [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17]
Explanation : 16+9 = 25 = 5*5, 9+7 = 16 = 4*4, 7+2 = 9 = 3*3 and so on.
Input: 20
Output: No Solution
Input : 25
Output : [2, 23, 13, 12, 24, 25, 11, 14, 22, 3, 1, 8,
17, 19, 6, 10, 15, 21, 4, 5, 20, 16, 9, 7, 18]
Method: We can represent a graph, where numbers from 1 to n are the nodes of the graph and there is an edge between ith and jth node if (i+j) is a perfect square. Then we can search if there is any Hamiltonian Path in the graph. If there is at least one path then we print a path otherwise we print "No Solution".

Approach:
1. First list up all the perfect square numbers
which we can get by adding two numbers.
We can get at max (2*n-1). so we will take
only the squares up to (2*n-1).
2. Take an adjacency matrix to represent the graph.
3. For each number from 1 to n find out numbers with
which it can add upto a perfect square number.
Fill respective cells of the adjacency matrix by 1.
4. Now find if there is any Hamiltonian path in the
graph using backtracking as discussed earlier.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check if a node is safe to visit in the
// current Hamiltonian path
bool issafe(int v, int graph[][20], int path[], int pos)
{
// Check if the current node is connected to the
// previous node in the path
if (graph[path[pos - 1]][v] == 0)
return false;
// Check if the current node has already been visited in
// the current path
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
// If the current node is connected to the previous node
// and has not been visited yet, return true
return true;
}
// Function to form the Hamiltonian path by visiting nodes
// recursively
bool formpath(int graph[][20], int path[], int pos, int n)
{
// If all the nodes have been visited, return true
if (pos == n + 1)
return true;
// Try visiting each node and see if it forms a
// Hamiltonian path
for (int v = 1; v < n + 1; v++) {
if (issafe(v, graph, path, pos)) {
path[pos] = v;
if (formpath(graph, path, pos + 1, n) == true)
return true;
path[pos] = -1;
}
}
// If none of the nodes form a Hamiltonian path, return
// false
return false;
}
// Function to find a Hamiltonian path in a given graph
void hampath(int n)
{
// Adjacency matrix to store the graph
int graph[20][20];
// Array to store the Hamiltonian path
int path[20];
// Temporary variable used to store square root of 2n-1
int k = 0;
// If there is only 1 node in the graph, there is no
// Hamiltonian path
if (n == 1) {
cout << "No Solution";
return;
}
// Vector to store the squares of the numbers from 1 to
// sqrt(2n-1)
vector<int> l;
int nsqrt = sqrt(2 * n - 1);
for (int i = 1; i <= nsqrt + 1; i++) {
l.push_back(i * i);
}
// Initialize the graph to 0
memset(graph, 0, sizeof(graph));
// Form the graph using the squares stored in the vector
// 'l'
for (int i = 1; i < n + 1; i++) {
for (auto ele : l) {
// Check if the difference between the square
// and the current node is greater than 0 and
// less than or equal to n Also, make sure that
// the difference is not equal to 2 times the
// current node (to avoid repeated edges)
if ((ele - i) > 0 && (ele - i) <= n
&& (2 * i != ele)) {
graph[i][ele - i] = 1;
graph[ele - i][i] = 1;
}
}
}
// Loop through all vertices starting from vertex 1
for (int j = 1; j < n + 1; j++) {
// Reset the path array
memset(path, -1, sizeof(path));
// Start the path from vertex j
path[1] = j;
// Check if a Hamiltonian path can be formed
// starting from vertex j
if (formpath(graph, path, 2, n) == true) {
cout << "Hamiltonian Path: ";
// Print the path
for (int i = 1; i < n + 1; i++) {
cout << path[i] << " ";
}
// Return the path
return;
}
}
// If no solution is found, print "No Solution"
cout << "No Solution";
return;
}
// Driver Function
int main()
{
cout << "17 -> ";
hampath(17);
cout << endl << "20 -> ";
hampath(20);
cout << endl << "25 -> ";
hampath(25);
return 0;
}
Java
import java.util.*;
public class HamiltonianPath {
// Function to check if a node is safe to visit in the
// current Hamiltonian path
static boolean issafe(int v, int[][] graph, int[] path,
int pos)
{
// Check if the current node is connected to the
// previous node in the path
if (graph[path[pos - 1]][v] == 0) {
return false;
}
// Check if the current node has already been
// visited in the current path
for (int i = 0; i < pos; i++) {
if (path[i] == v) {
return false;
}
}
// If the current node is connected to the previous
// node and has not been visited yet, return true
return true;
}
// Function to form the Hamiltonian path by visiting
// nodes recursively
static boolean formpath(int[][] graph, int[] path,
int pos, int n)
{
// If all the nodes have been visited, return true
if (pos == n + 1) {
return true;
}
// Try visiting each node and see if it forms a
// Hamiltonian path
for (int v = 1; v < n + 1; v++) {
if (issafe(v, graph, path, pos)) {
path[pos] = v;
if (formpath(graph, path, pos + 1, n)
== true) {
return true;
}
path[pos] = -1;
}
}
// If none of the nodes form a Hamiltonian path,
// return false
return false;
}
// Function to find a Hamiltonian path in a given graph
static void hampath(int n)
{
// Adjacency matrix to store the graph
int[][] graph = new int[n+1][n+1];
// Array to store the Hamiltonian path
int[] path = new int[n+1];
// If there is only 1 node in the graph, there is no
// Hamiltonian path
if (n == 1) {
System.out.println("No Solution");
return;
}
// Vector to store the squares of the numbers from 1
// to sqrt(2n-1)
ArrayList<Integer> l = new ArrayList<Integer>();
int nsqrt = (int)Math.sqrt(2 * n - 1);
for (int i = 1; i <= nsqrt + 1; i++) {
l.add(i * i);
}
// Initialize the graph to 0
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < n + 1; j++) {
graph[i][j] = 0;
}
}
// Form the graph using the squares stored in the
// vector 'l'
for (int i = 1; i < n + 1; i++) {
for (int ele : l) {
// Check if the difference between the
// square and the current node is greater
// than 0 and less than or equal to n Also,
// make sure that the difference is not
// equal to 2 times the current node (to
// avoid repeated edges)
if ((ele - i) > 0 && (ele - i) <= n
&& (2 * i != ele)) {
graph[i][ele - i] = 1;
graph[ele - i][i] = 1;
}
}
}
for (int j = 1; j < n + 1; j++) {
// Reset the path array
Arrays.fill(path, -1);
// Start the path from vertex j
path[1] = j;
// Check if a Hamiltonian path can be formed
// starting from vertex j
if (formpath(graph, path, 2, n) == true) {
System.out.print("Hamiltonian Path: ");
// Print the path
for (int i = 1; i < n + 1; i++) {
System.out.print(path[i] + " ");
}
// Return the path
return;
}
}
// If no solution is found, print "No Solution"
System.out.print("No Solution");
}
public static void main(String[] args)
{
System.out.print("17 -> ");
hampath(17);
System.out.println();
System.out.print("20 -> ");
hampath(20);
System.out.println();
System.out.print("25 -> ");
hampath(25);
}
}
Python3
# Python3 program for Sum-square series using
# hamiltonian path concept and backtracking
# Function to check whether we can add number
# v with the path in the position pos.
def issafe(v, graph, path, pos):
# if there is no edge between v and the
# last element of the path formed so far
# return false.
if (graph[path[pos - 1]][v] == 0):
return False
# Otherwise if there is an edge between
# v and last element of the path formed so
# far, then check all the elements of the
# path. If v is already in the path return
# false.
for i in range(pos):
if (path[i] == v):
return False
# If none of the previous cases satisfies
# then we can add v to the path in the
# position pos. Hence return true.
return True
# Function to form a path based on the graph.
def formpath(graph, path, pos):
# If all the elements are included in the
# path i.e. length of the path is n then
# return true i.e. path formed.
n = len(graph) - 1
if (pos == n + 1):
return True
# This loop checks for each element if it
# can be fitted as the next element of the
# path and recursively finds the next
# element of the path.
for v in range(1, n + 1):
if issafe(v, graph, path, pos):
path[pos] = v
# Recurs for next element of the path.
if (formpath(graph, path, pos + 1) == True):
return True
# If adding v does not give a solution
# then remove it from path
path[pos] = -1
# if any vertex cannot be added with the
# formed path then return false and
# backtracks.
return False
# Function to find out sum-square series.
def hampath(n):
# base case: if n = 1 there is no solution
if n == 1:
return 'No Solution'
# Make an array of perfect squares from 1
# to (2 * n-1)
l = list()
for i in range(1, int((2 * n-1) ** 0.5) + 1):
l.append(i**2)
# Form the graph where sum of two adjacent
# vertices is a perfect square
graph = [[0 for i in range(n + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
for ele in l:
if ((ele-i) > 0 and (ele-i) <= n
and (2 * i != ele)):
graph[i][ele - i] = 1
graph[ele - i][i] = 1
# starting from 1 upto n check for each
# element i if any path can be formed
# after taking i as the first element.
for j in range(1, n + 1):
path = [-1 for k in range(n + 1)]
path[1] = j
# If starting from j we can form any path
# then we will return the path
if formpath(graph, path, 2) == True:
return path[1:]
# If no path can be formed at all return
# no solution.
return 'No Solution'
# Driver Function
print(17, '->', hampath(17))
print(20, '->', hampath(20))
print(25, '->', hampath(25))
C#
//C# Equivalent of above code
using System;
using System.Collections.Generic;
public class HamiltonianPath
{
// Function to check if a node is safe to visit in the
// current Hamiltonian path
static bool issafe(int v, int[,] graph, int[] path,
int pos)
{
// Check if the current node is connected to the
// previous node in the path
if (graph[path[pos - 1], v] == 0)
{
return false;
}
// Check if the current node has already been
// visited in the current path
for (int i = 0; i < pos; i++)
{
if (path[i] == v)
{
return false;
}
}
// If the current node is connected to the previous
// node and has not been visited yet, return true
return true;
}
// Function to form the Hamiltonian path by visiting
// nodes recursively
static bool formpath(int[,] graph, int[] path,
int pos, int n)
{
// If all the nodes have been visited, return true
if (pos == n + 1)
{
return true;
}
// Try visiting each node and see if it forms a
// Hamiltonian path
for (int v = 1; v < n + 1; v++)
{
if (issafe(v, graph, path, pos))
{
path[pos] = v;
if (formpath(graph, path, pos + 1, n)
== true)
{
return true;
}
path[pos] = -1;
}
}
// If none of the nodes form a Hamiltonian path,
// return false
return false;
}
// Function to find a Hamiltonian path in a given graph
static void hampath(int n)
{
// Adjacency matrix to store the graph
int[,] graph = new int[n + 1, n + 1];
// Array to store the Hamiltonian path
int[] path = new int[n + 1];
// If there is only 1 node in the graph, there is no
// Hamiltonian path
if (n == 1)
{
Console.WriteLine("No Solution");
return;
}
// List to store the squares of the numbers from 1
// to sqrt(2n-1)
List<int> l = new List<int>();
int nsqrt = (int)Math.Sqrt(2 * n - 1);
for (int i = 1; i <= nsqrt + 1; i++)
{
l.Add(i * i);
}
// Initialize the graph to 0
for (int i = 1; i < n + 1; i++)
{
for (int j = 1; j < n + 1; j++)
{
graph[i, j] = 0;
}
}
// Form the graph using the squares stored in the
// List 'l'
for (int i = 1; i < n + 1; i++)
{
foreach (int ele in l)
{
// Check if the difference between the
// square and the current node is greater
// than 0 and less than or equal to n Also,
// make sure that the difference is not
// equal to 2 times the current node (to
// avoid repeated edges)
if ((ele - i) > 0 && (ele - i) <= n
&& (2 * i != ele))
{
graph[i, ele - i] = 1;
graph[ele - i, i] = 1;
}
}
}
for (int j = 1; j < n + 1; j++)
{
// Reset the path array
Array.Fill(path, -1);
// Start the path from vertex j
path[1] = j;
// Check if a Hamiltonian path can be formed
// starting from vertex j
if (formpath(graph, path, 2, n) == true)
{
Console.Write("Hamiltonian Path: ");
// Print the path
for (int i = 1; i < n + 1; i++)
{
Console.Write(path[i] + " ");
}
// Return the path
return;
}
}
// If no solution is found, print "No Solution"
Console.Write("No Solution");
}
public static void Main(string[] args)
{
Console.Write("17 -> ");
hampath(17);
Console.WriteLine();
Console.Write("20 -> ");
hampath(20);
Console.WriteLine();
Console.Write("25 -> ");
hampath(25);
}
}
JavaScript
function issafe(v, graph, path, pos) {
if (graph[path[pos - 1]][v] === 0) {
return false;
}
for (let i = 0; i < pos; i++) {
if (path[i] === v) {
return false;
}
}
return true;
}
function formpath(graph, path, pos, n) {
if (pos === n + 1) {
return true;
}
for (let v = 1; v < n + 1; v++) {
if (issafe(v, graph, path, pos)) {
path[pos] = v;
if (formpath(graph, path, pos + 1, n)) {
return true;
}
path[pos] = -1;
}
}
return false;
}
function hampath(n) {
const graph = new Array(n + 1).fill(0).map(() => new Array(n + 1).fill(0));
const path = new Array(n + 1).fill(-1);
if (n === 1) {
console.log("No Solution");
return;
}
const l = [];
const nsqrt = Math.floor(Math.sqrt(2 * n - 1));
for (let i = 1; i <= nsqrt + 1; i++) {
l.push(i * i);
}
for (let i = 1; i < n + 1; i++) {
for (let j = 1; j < n + 1; j++) {
graph[i][j] = 0;
}
}
for (let i = 1; i < n + 1; i++) {
for (let ele of l) {
if ((ele - i) > 0 && (ele - i) <= n && (2 * i !== ele)) {
graph[i][ele - i] = 1;
graph[ele - i][i] = 1;
}
}
}
for (let j = 1; j < n + 1; j++) {
path[1] = j;
if (formpath(graph, path, 2, n)) {
console.log("Hamiltonian Path: " + path.slice(1).join(" "));
return;
}
}
console.log("No Solution");
}
console.log("17 -> ");
hampath(17);
console.log();
console.log("20 -> ");
hampath(20);
console.log();
console.log("25 -> ");
hampath(25);
Output17 -> [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17]
20 -> No Solution
25 -> [2, 23, 13, 12, 24, 25, 11, 14, 22, 3, 1, 8, 17, 19, 6, 10, 15, 21, 4, 5, 20, 16, 9, 7, 18]
Discussion:
- This backtracking algorithm takes exponential time to find Hamiltonian Path.
- Hence the time complexity of this algorithm is exponential. In the last part of the hampath(n) function if we just print the path rather returning it then it will print all possible Hamiltonian Path i.e. all possible representations. Actually we will first get a representation like this for n = 15. For n<15 there is no representation.
- For n = 18, 19, 20, 21, 22, 24 there is also no Hamiltonian Path. For rest of the numbers it works well.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem