As it is a binary string, the hash value of a string will be the sum of some distinct power of base . So let’s try to generate all the hash values that can be generated. It can be done using dynamic programming, we keep track of all the hash values that we already generated for power < , and then we add to all the generated data to get some new hash values that are possible. The transition will be, or . Here means hash value can be generated using some powers of upto . After processing this for upto , if we didn’t get hash value then it is not possible to generate .
Otherwise, we need to generate the lexicographically smallest string. How do we do that?
Notice if a lexicographically smaller string will have a higher power of for some index . So if we start from the highest value of and come downwards we will encounter the lexicographically smaller one first. So, we will start from and come downwards keeping track of the highest index where we first encountered the hash value . Now using these values we can generate the string.
Complexity:
Judge solution(C++): https://paste.ofcode.org/zQwCrDESwTFB4SpNYnGz2E