VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-increasing-sequences-length-k-first-n-natural-numbers/

⇱ Print all increasing sequences of length k from first n natural numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all increasing sequences of length k from first n natural numbers

Last Updated : 24 Jun, 2022

Given two positive integers n and k, print all increasing sequences of length k such that the elements in every sequence are from the first n natural numbers.

Examples: 

Input: k = 2, n = 3
Output: 1 2
 1 3
 2 3 

Input: k = 5, n = 5
Output: 1 2 3 4 5

Input: k = 3, n = 5
Output: 1 2 3
 1 2 4
 1 2 5
 1 3 4
 1 3 5
 1 4 5
 2 3 4
 2 3 5
 2 4 5
 3 4 5

We strongly recommend minimizing the browser and trying this yourself first.
It's a good recursion question. The idea is to create an array of lengths k. The array stores the current sequence. For every position in the array, we check the previous element and one by one put all elements greater than the previous element. If there is no previous element (first position), we put all numbers from 1 to n. 

Below is the implementation of the above idea : 

Output: 

1 2 3
1 2 4
1 2 5
1 2 6
1 2 7
1 3 4
1 3 5
1 3 6
1 3 7
1 4 5
1 4 6
1 4 7
1 5 6
1 5 7
1 6 7
2 3 4
2 3 5
2 3 6
2 3 7
2 4 5
2 4 6
2 4 7
2 5 6
2 5 7
2 6 7
3 4 5
3 4 6
3 4 7
3 5 6
3 5 7
3 6 7
4 5 6
4 5 7
4 6 7
5 6 7

Time Complexity: O(n*n!), as there are n! permutations and it requires O(n) time to print a permutation. T(n) = n * T(n-1) + O(1) when reduced will result in O(n*n!) time.

Auxiliary Space: O(n)
 

Comment
Article Tags: