Facebook (Meta) | Phone Interview | Form a palindrome

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2021-12-01Added By Anonymous
Source: Link

Company: Meta (Facebook)
Role: unknown
Interview Stage: Phone Interview
Location: unknown
Year: unknown

Original Post Content:

Check if characters of a given string can be rearranged to form a
palindrome

Input: facebface
output: true because -> facebecaf

Input : facebookface
output: false because -> facekoobecaf

I went with the bit approach since I've doing bit manipulation for too long now
public static boolean formPalindrome(String s) {
int b = 0;
int a = 0;
for (int i = 0; i < s.length(); i++) {
int x = s.charAt(i) - 'a';
a = 1 << x;

b = b ^ a;
}
return b & (b - 1) == 0;
}

Time complexity 0(n) and space is 0(1)

Comments