VOOZH about

URL: https://www.geeksforgeeks.org/dsa/min-length-string-with-all-substrings-of-size-n/

⇱ Min Length String with All Substrings of Size N - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Min Length String with All Substrings of Size N

Last Updated : 28 Apr, 2025

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?

  • We start with a string of size 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.
  • Therefore, the total string length will be: k^n + (n-1) which is the minimum possible length.

Step by Step Algorithm

  • Initialize an empty string ans with n zeros
  • Decrement K by 1 to convert to 0-based digits
  • Create an unordered set visited and insert the initial string res.
  • Loop until visited.size() equals (K+1) ^ n. Inside the loop, start with largest digit and stop when we find a digit such that appending the digit covers a new substring.

Output
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.

Comment