-1

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;
}
Max Newton
  • 13
  • 5
  • May I know why this question gets a negative ranking? – Max Newton Jul 01 '18 at 11:15
  • You need to ask more specific question when you put code (e.g why this for statement doesn't run).Sometimes when your question isnt clear you can get negative upvotes.In my opinion this is a little bit strict and i had the same problem when i start to asking questions here.Nevertheless this is the community and you have to compromise. Also see https://stackoverflow.com/help/how-to-ask for more help ! – bembas Jul 01 '18 at 11:24

1 Answers1

1

Boy, you should not share problems that are live on competition website. This problem is live on hackerearth.com for kelton tech challenge.

sacgro
  • 459
  • 2
  • 5