easy
1 views

Non Palindromic Words [ZOHO]

Given a string with one or more words, print only the words that are not palindromes. Print -1 if all words are palindromes.

Understand the Problem

Problem Statement

Non Palindromic Words: A string with one or more words is passed as the input. The program must print only the words which are not palindromes. Print -1 if all the words in the string are palindromes.

Constraints

  • 1 <= N <= 1000 (where N is the number of words)
  • 1 <= Length of S <= 1000 (where S is the input string)
  • Each word consists of alphabetic characters only
  • Words are separated by single spaces
  • Case-sensitive palindrome checking

Examples

Example 1
Input
Today madam came to the class
Output
Today came to the class
Explanation

The word 'madam' is a palindrome (reads same forward and backward), so it is excluded. All other words ('Today', 'came', 'to', 'the', 'class') are not palindromes, so they are printed.

Example 2
Input
malayalam ere
Output
-1
Explanation

Both 'malayalam' and 'ere' are palindromes. Since all words are palindromes, the output is -1.

Solution

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

bool isPalindrome(char word[]) {
    int len = strlen(word);
    for (int i = 0; i < len / 2; i++) {
        if (word[i] != word[len - 1 - i]) {
            return false;
        }
    }
    return true;
}

int main() {
    char input[1001];
    fgets(input, sizeof(input), stdin);
    
    // Remove newline if present
    int len = strlen(input);
    if (input[len - 1] == '\n') {
        input[len - 1] = '\0';
    }
    
    char *token = strtok(input, " ");
    bool foundNonPalindrome = false;
    bool first = true;
    
    while (token != NULL) {
        if (!isPalindrome(token)) {
            if (!first) {
                printf(" ");
            }
            printf("%s", token);
            foundNonPalindrome = true;
            first = false;
        }
        token = strtok(NULL, " ");
    }
    
    if (!foundNonPalindrome) {
        printf("-1");
    }
    
    printf("\n");
    return 0;
}
Time:O(n * m) where n is the number of words and m is the average length of words. For each word, we check palindrome in O(m) time.
Space:O(1) additional space (not counting input storage). We only use a few variables for tracking state.
Approach:

The C solution works as follows:

  1. Define a function isPalindrome that checks if a word reads the same forward and backward by comparing characters from both ends
  2. In main, read the input string using fgets
  3. Remove the trailing newline character
  4. Use strtok to split the string into words
  5. For each word, check if it's not a palindrome using isPalindrome
  6. If it's not a palindrome, print it with proper spacing
  7. Track whether any non-palindromic words were found
  8. If none were found, print -1

Visual Explanation

Loading diagram...