Be the first user to complete this post

  • 0
Add to List
Medium

343. Generate all the strings of length n from 0 to k-1

Objective: Given two numbers, n and k (k>=n), write an algorithm to generate all the strings of length n drawn from 0 – k-1.

Example:

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

Approach:

  • This problem is similar to “Generate All Strings of n bits” with some modification.
  • Recursion is the key here.
  • Create integer array of size n.
  • Traverse from 0 to k and put all the values from 0 to k at the last index in the array and make a recursive call to n-1.
  • Print the array at the base case print the array but only for size n.
  • See the code below for more understanding.

Output:

0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2