![]() |
VOOZH | about |
Given two integers n and k, your task is to find a string of minimum length to contain all possible strings of size n as a substring. The characters of the string should be integers ranging from 0 to k - 1.
Examples:
Input: n = 2, k = 2
Output: 00110
Explanation: Allowed characters are from 0 to k-1 (i.e., 0 and 1). There are 4 string possible of size n = 2 and two integers (i.e "00", "01","10","11"). "00110" contains all possible string as a substring.Input: n = 2, k = 3
Output: 0022120110
Explanation: Allowed characters are from 0 to k-1 (i.e., 0, 1 and 2). There are total 9 strings possible of size N, given output string has the minimum length that contains all those strings as substring.
Approach:
The idea is to construct a De Bruijn–style sequence by starting with N zeros and then, at each step, appending the biggest possible digit that creates a new length-n substring. By always choosing the extension that hasn’t been seen before, the algorithm guarantees that every n-digit string over {0,…,K−1} will appear exactly once in the shortest possible superstring.
Why does this work?
n, and every appended character creates a new substring. We use a hashset to ensure that we append only when a new substring is being generated.Step by Step Algorithm
0022120110
Time Complexity: O(kn + 1), As we are running the loop of size O(kn + 1).
Auxiliary Space: O(kn + 1), As we have the set to store the all the possible permutations.