LC: Strobogrammatic Number II - spiralgo/algorithms GitHub Wiki

Strobogrammatic Number II

The Essence:

We could think of a strobogrammatic number as another kind palindrome. From the question statement, we already know the length of this number. So, in order to build this number, we can create a character array. In this char array, we put the reflective digits in the opposite sides of the array.

  • For example, in an array of length 5, if we put 1 on the index 0, we put another one on the index 4 (n-1). After that, we put a 6 on the index 1 (previous left+1) and then the corresponding digit 9 on the index 3 (n-2, previous right+1). At the end, when we continue the pattern both left and right becomes 2. We then put digits that are suitable for a middle reflection (0, 1, 8).

  • This pattern also holds when modified for even lengths: At even lengths such as 4, left will eventually assume the index value 2 and right the index value 1 (left>right). Then, we shall not add anything into the character array.

In this problem, it's important recognize how this "strobogrammatic" number described using mathematical terms is just another appearance of something seemingly unrelated from string data type. It's important to notice that they are same in their essence.

Details:

Only thing we should also consider is that we shouldn't place '0' at the front when left is 0, that would not be a valid number.

We can also put the reflective number pairs in char[][] and easily loop over them.

The algorithm described here can be implemented using a backtracking algorithm. It's important for the problem-solvers to familiarize themselves with such algorithmic techniques.