Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package algorithms.curated170.medium;

import java.util.ArrayList;
import java.util.List;

public class StrobogrammaticNumber2 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great:
image

Copy link
Collaborator

@altay9 altay9 Jun 8, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a quote of Erdem's explanation:

Resolves #57

Algorithm:

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 a bit, 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.

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.


final char[][] reflectives = new char[][]
{
{'0','0'},
{'6','9'},
{'1','1'},
{'9','6'},
{'8','8'}
};

char[] numBuilder;

List<String> numbers;

public List<String> findStrobogrammatic(int n) {
numbers = new ArrayList<>();
numBuilder = new char[n];

createNum(0, n-1);
return numbers;
}

void createNum(int left, int right)
{
if(left==right)
{
for(int i = 0; i<5; i+=2)
{
numBuilder[left] = reflectives[i][0];
numbers.add(String.valueOf(numBuilder));
}
return;
}
else if(left > right)
{
numbers.add(String.valueOf(numBuilder));
return;
}
for(char[] pair : reflectives)
{
if(left == 0 && pair[0] == '0')
{
continue;
}
numBuilder[left] = pair[0];
numBuilder[right] = pair[1];
createNum(left+1, right-1);
}
}

public static void main(String[] args) {

System.out.println(new StrobogrammaticNumber2().findStrobogrammatic(5));
}

}