Game of Thrones - I

  • + 1 comment

    Figure out whether any anagram of the string can be a palindrome or not.

    A palindrome of even length should have all character counts even. A palindrome of odd length should have all but one character counts even.

    the given input string contains only lower case english letters, which are 26 of them. I am masking the bits for each character occurences.

    let me take an example:

    1. Even length palindrome: abba :- Here we have 2 occurences of 'a' and 'b'.
      • s[0] == 'a':- enables bit 1. => mask: 00000000000000000000000001
      • s[1]== 'b' :- enables bit 2. => mask: 00000000000000000000000011
      • s[2]== 'b' :- if bit is enabled then XOR disable it. => mask: 00000000000000000000000010
      • s[3]== 'a' :- if bit is enabled then XOR disables it. => mask: 00000000000000000000000000
    2. Odd length palindrome: abcba :- Here we have 2 occurneces of 'a' and 'b' and one occurence of 'c'.
      • s[0] == 'a':- enables bit 1. => mask: 00000000000000000000000001
      • s[1]== 'b' :- enables bit 2. => mask: 00000000000000000000000011
      • s[2]== 'c' :- enables bit 3. => mask: 00000000000000000000000111
      • s[3]== 'b' :- if bit is enabled then XOR disable it. => mask: 00000000000000000000000101
      • s[4]== 'a' :- if bit is enabled then XOR disable it. => mask: 00000000000000000000000100

    If our given string is even length palindrome then "mask" will always be zero going by above logic.

    If our given string is odd length palindrome then "mask" will always be power of 2 (to check if given integer is power of 2 :-> (n & (n - 1) == 0)).

    hope it helps.