FIrst Problem Linear O(N) Solution This is a neat BFS Problem and a simple one.
You start with a queue with an empty string
q = {""}
At each step, you pop out all strings from the queue one by one. Let some string be S.
Push
4S4 in the queue. Do this for all popped strings S.
Now, push
5S5 in the queue for all popped strings S.
Stop when you are pushing the Nth string.
Constructive O(|S|) Solution First, make N 0-indexed by decreasing it by 1.
Realize that there are exactly pow(2, L/2) palindromic strings of L here.
Thus we can find out the length of the Nth string of length
L as well as it's first and last characters. Either both are 4 or both are 5.
Fix them both and then recursive solve for length
L-2 and appropriate remaining N = N-pow(2, L/2)+1 (please verify this).
Obviously, the recursion ends at the base case with an empty string.