Backtracking and memoization: O(2^N) worst case runtime

This problem seems to be very tricky, but in fact we can solve it with a pretty usual backtracking algorithm. There are two easy cases to consider and one complicated case:

Case 1: s1[i] is equal to the current character in s3, so we just move i and pos of s3 forward by one.

Case 2: s2[j] is equal to the current character in s3. Do the same as above, but with j

Case 3: s1[i] and s2[j] are equal to the current character in s3. At this point, we do not know which pointer will be the correct one to move. We just try to move pointer i and see what happens. If we are lucky, we will get a valid result. Otherwise we backtrack to this position and move pointer j forward by one.

The above algorithm takes O(2^N) runtime worst case. We can improve this by using memoization. We create a hashmap which stores indexes of the pointers to positions of s3. Whenever we find a constellation that is invalid, we store it in this map.