This is the programming question asked in GE Vernova for Selenium with cypress profile. This question is often asked to test your logic-building ability, even for automation roles like Selenium or Cypress.
A palindrome is a string that reads the same forward and backward.
To determine whether a string can be rearranged to form a palindrome, we check character frequencies.
⭐ Key Rule
- A string can be rearranged into a palindrome if:
- Every character appears an even number of times,
OR - Only one character is allowed to appear an odd number of times (for the center position in odd-length palindromes)
- If more than one character has an odd frequency → cannot form a palindrome.
🔍 Why this rule works?
- Palindromes are symmetric.
- Characters on the left must match characters on the right → even count.
- Only the middle character (in odd-length palindrome) can have an odd count.
🔢 Steps Using Java (Automation-Friendly Explanation)
- Create a HashMap<Character, Integer>
- Count the frequency of each character
- Loop through the map and count how many characters have odd occurrences
- If odd count > 1 → return false
- Otherwise → return true
Java Code Example (Selenium-Friendly Java Logic)
import java.util.HashMap;
import org.testng.annotations.Test;
public class PalindromeVerification {
@Test
public void verification() {
String str = "aabbc"; // You can test with different inputs
if (verifyPalindrome(str)) {
System.out.println(str + " can be rearranged as a palindrome");
} else {
System.out.println(str + " cannot be rearranged as a palindrome");
}
}
public boolean verifyPalindrome(String str) {
// Handle null or empty string safely
if (str == null || str.isEmpty()) {
return false;
}
HashMap<Character, Integer> map = new HashMap<>();
// Count character frequencies
for (char c : str.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
int oddCount = 0;
// Check how many characters have odd frequency
for (int count : map.values()) {
if (count % 2 != 0) {
oddCount++;
}
if (oddCount > 1) {
return false; // More than 1 odd → cannot form palindrome
}
}
return true; // Valid for palindrome formation
}
}