Palindrome Permutation - C Solution

1. Introduction

This blog post explores a unique problem in C programming: determining if a permutation of the given string can form a palindrome. A palindrome is a word that reads the same backward as forward. This problem is a fascinating intersection of string manipulation and the understanding of palindromic properties.

Problem

Given a string, the task is to determine if any permutation of the string can form a palindrome. The string may contain any ASCII character, and the case of characters should be ignored. This problem challenges us to understand and apply the characteristics of palindromes in string processing.

2. Solution Steps

1. Use a frequency array to count the occurrences of each character in the string.

2. Ignore case differences and non-alphabetical characters.

3. Check if the frequency of each character is even, with at most one character having an odd frequency.

4. Return true if these conditions are met, indicating a palindromic permutation is possible.

3. Code Program

#include <stdio.h>
#include <string.h>
#include <ctype.h>

// Function to check if a palindromic permutation is possible
int canPermutePalindrome(char *s) {
    int freq[128] = {0}; // Frequency array for ASCII characters

    // Count frequency of each character
    for (int i = 0; s[i] != '\0'; i++) {
        char ch = tolower(s[i]); // Convert to lowercase for case-insensitive comparison
        if (isalpha(ch)) { // Check if the character is an alphabet
            freq[ch]++; // Increment frequency
        }
    }

    int oddCount = 0; // Count of characters with odd frequency
    for (int i = 0; i < 128; i++) {
        if (freq[i] % 2 != 0) {
            oddCount++; // Increment odd count
            if (oddCount > 1) return 0; // More than one character with odd frequency
        }
    }

    return 1; // Palindromic permutation is possible
}

int main() {
    char s[] = "Tact Coa"; // Example string
    int result = canPermutePalindrome(s); // Call the function
    printf("Output: %d\n", result); // Print the result (1 for true, 0 for false)

    return 0;
}

Output:

1

Explanation:

The program checks if any permutation of the string "Tact Coa" can form a palindrome. It uses a frequency array to count the occurrences of each character, considering only alphabetic characters and ignoring case differences. A string can form a palindrome if at most one character has an odd frequency. 

In "Tact Coa", the characters 't', 'a', 'c', and 'o' appear an odd number of times, but since 't' and 'a' are repeated, only 'c' and 'o' are odd in frequency, meeting the condition. Therefore, a palindromic permutation is possible, and the output is 1 (true).


Comments