Tag Archives: Print all permutations

Print all the possible permutations by adding X and Y (Hacker Rank Interview Question)

Input:
X and Y are integer values, where X < Y
N is the length of permutation
Output:
To print all the possible permutations in sorted order, in given form, starting from zero.

i.e 0 , 0 + X (or Y)

For example:
X = 1, Y = 2
N = 3.

output should be:
0 1 2
0 1 3
0 2 3
0 2 4

To solve this problem, we can use recursion by passing the value of X and Y with the current state array.
At each recursion step, we will call the method by passing values of X or Y in order. The end of the recursion would be the length of array reaching the value of N.

Here is the code:

You can also clone the repository from GIT using the link below:

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git

HackerRankProjectStructure

import java.util.ArrayList;

public class PossiblePermutations {
	
		int x=1;
		int y=2;
		int permutSize = 5;
		int length;

		public static void main(String args[]){
			PossiblePermutations pd = new PossiblePermutations();
			ArrayList<Integer> al = new ArrayList<Integer>();
			al.add(0);
			
			pd.printAllPermutations(al);
		}
		
		public void printAllPermutations(ArrayList<Integer> a){
			ArrayList<Integer> a1 = new ArrayList<Integer>(a);
			
			if(a.size() == permutSize){
				System.out.println(a);
			}else{
				a.add(a.get(a.size()-1) + x);
				printAllPermutations(a);
				a1.add(a1.get(a1.size()-1) + y);
				printAllPermutations(a1);
			}
		}
		
		public void printArray(int a[]){
			for(int i=0;i<a.length;i++){
				System.out.print(a[i]+" ");
			}
			System.out.println("");
		}
}

The output of above code:

Input:
X = 1
Y = 2
N = 5

Output:
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 5]
[0, 1, 2, 4, 5]
[0, 1, 2, 4, 6]
[0, 1, 3, 4, 5]
[0, 1, 3, 4, 6]
[0, 1, 3, 5, 6]
[0, 1, 3, 5, 7]
[0, 2, 3, 4, 5]
[0, 2, 3, 4, 6]
[0, 2, 3, 5, 6]
[0, 2, 3, 5, 7]
[0, 2, 4, 5, 6]
[0, 2, 4, 5, 7]
[0, 2, 4, 6, 7]
[0, 2, 4, 6, 8]

You can also clone the repository from GIT using the link below:

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git