Arrays & Stringsmedium
1 views

Toggle Consonants Adjacent to Vowels

Toggle the case of consonants that are adjacent to vowels in a given string.

Understand the Problem

Problem Statement

The program must accept a string S containing only alphabets both in lower and upper case. The program must toggle the case of the consonants (non-vowels) adjacent to the vowels.

Constraints

  • 2 <= Length of the string S <= 100
  • String S contains only alphabets (both uppercase and lowercase)
  • Adjacent means immediately next to (left or right) in the string
  • Vowels are a, e, i, o, u (both cases)
  • Consonants are all other alphabets

Examples

Example 1
Input
adJaeCent
Output
aDjaeceNt
Explanation

For 'a' at position 0, adjacent 'd' becomes 'D'. For 'ae' at positions 2-3, adjacent 'J' becomes 'j' and 'C' becomes 'N'. For 'e' at position 5, adjacent 'e' is a vowel so no change.

Example 2
Input
mAtRIMonY
Output
MATrImoNY
Explanation

For 'A' at position 1, adjacent 'm' becomes 'M' and 't' becomes 'T'. For 'I' at position 4, adjacent 'R' becomes 'r' and 'M' becomes 'm'. For 'o' at position 6, adjacent 'n' becomes 'N' and 'Y' remains uppercase.

Solution

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

int isVowel(char ch) {
    char c = tolower(ch);
    return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

void toggle(char *s, int i) {
    if (isupper(s[i]))
        s[i] = tolower(s[i]);
    else
        s[i] = toupper(s[i]);
}

int main() {
    char s[100];
    int i, n, toggled[100] = {0};
    
    scanf("%s", s);
    n = strlen(s);
    
    for (i = 0; i < n; i++) {
        if (isVowel(s[i])) {
            // Check left neighbor
            if (i > 0 && !isVowel(s[i-1]) && !toggled[i-1]) {
                toggle(s, i-1);
                toggled[i-1] = 1;
            }
            // Check right neighbor
            if (i < n-1 && !isVowel(s[i+1]) && !toggled[i+1]) {
                toggle(s, i+1);
                toggled[i+1] = 1;
            }
        }
    }
    
    printf("%s", s);
    return 0;
}
Time:O(n)
Space:O(n)
Approach:

C Solution Explanation:

  1. isVowel(): Checks if a character is a vowel by converting to lowercase and comparing against 'aeiou'.
  2. toggle(): Toggles case using standard library functions toupper() and tolower().
  3. Main Logic: Iterate through string, for each vowel check adjacent characters.
  4. Tracking: Use boolean array 'toggled' to prevent double-toggling consonants between vowels.
  5. Edge Handling: Check bounds (i > 0 and i < n-1) before accessing neighbors.

Visual Explanation

Loading diagram...