How to Check if a String Can Be Formed as a Palindrome

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

  1. A string can be rearranged into a palindrome if:
  2. Every character appears an even number of times,
    OR
  3. Only one character is allowed to appear an odd number of times (for the center position in odd-length palindromes)
  4. 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)
  1. Create a HashMap<Character, Integer>
  2. Count the frequency of each character
  3. Loop through the map and count how many characters have odd occurrences
  4. If odd count > 1 → return false
  5. 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
}

}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x