I came across this question on a coding website. Here we have to check whether the grid can be rearrange to form a palindrome both rows wise and column wise.
My approach was first to check all the rows, and then columns. If any of them can not become palindrome then print NO else print YES.
But my program is only passing 15 test cases out of 50.
Below is the code I used:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
for(int i=0; i<testCases; i++)
{
int n = scanner.nextInt();
int m = scanner.nextInt();
scanner.nextLine();
boolean printYes = true;
String[] input = new String[n];
for(int k=0; k<n; k++)
{
input[k] = scanner.nextLine();
boolean check = canFormPalindrome(input[k]);
if(!check)
{
printYes= false;
}
}
if(printYes)
{
for(int k=0; k<m; k++)
{
String s = "";
for(int l=0; l<n; l++)
{
s=s+input[l].charAt(k);
}
boolean check = canFormPalindrome(s);
if(!check)
{
System.out.println("NO");
printYes = false;
break;
}
}
if(printYes)
{
System.out.println("YES");
}
}
else
{
System.out.println("NO");
}
}
scanner.close();
}
static boolean canFormPalindrome(String str) {
int count[] = new int[256];
Arrays.fill(count, 0);
for (int i = 0; i < str.length(); i++)
count[(int)(str.charAt(i))]++;
int odd = 0;
for (int i = 0; i < 256; i++)
{
if ((count[i] & 1) == 1)
odd++;
if (odd > 1)
return false;
}
return true;
}