Alternate vowel and consonant string in C/C++?



We are given a string with both vowels and consonants. Our task is to rearrange it so that vowels and consonants appear alternately, while keeping their original order within their groups.

This rearrangement is only possible if the number of vowels and consonants is equal, or their difference is exactly one. If multiple valid arrangements are possible, we return the one that is lexicographically smaller.

Let's understand this with a few example scenarios.

Scenario 1

Input: "objective"
Output: "bojecitev"
Explanation:
Vowels = [o, e, i, e], Consonants = [b, j, c, t, v]
Consonants are more by 1 -> valid for alternating arrangement
We start with a consonant -> b -> o -> j -> e -> c -> i -> t -> e -> v

Scenario 2

Input: "aepr"
Output: "aper"
Explanation:
Vowels = [a, e], Consonants = [p, r]
Both groups have equal count -> valid for alternating arrangement
Two valid combinations:
a -> p -> e -> r -> "aper"
p -> a -> r -> e -> "pare"
We compare both and choose the lexicographically smaller one -> "aper".

Rearranging Vowels and Consonants Alternately

To rearrange the vowels and consonants alternately in a string, we start by separating them into two arrays and then build a new string by picking one character from each, alternatively, keeping their original order unchanged.

Algorithm

The following are the steps:

  • First, we counted the number of vowels and consonants in the input string by checking each character.
  • If the absolute difference between the count of vowels and consonants is more than 1, it is not possible to arrange them in alternating order. In that case, we return an empty string.
  • Then, we created two separate strings, one for vowels and the other for consonants, while preserving their original order.
  • If both vowels and consonants are equal in number, we can start with either. We chose to start with a vowel and then alternate characters from both strings to form the final result.
  • If the number vowels is greater, we begin the result string with a vowel and then alternate characters from both strings.
  • If the number of consonants is greater, we start the result string with a consonant and follow the same process to build the final result.

C++ Program to Alternate Vowels and Consonants

Following is a C++ program where we rearrange the characters of a string so that vowels and consonants appear in alternating positions.

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

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

string alternateVowelConsonant(const string& s) {
   string vowels = "", consonants = "";

   // Separate vowels and consonants
   for (char c : s) {
      if (isVowel(c)) vowels += c;
      else consonants += c;
   }

   // Check if alternating arrangement is possible
   if (abs((int)vowels.size() - (int)consonants.size()) >= 2) {
      return "Not possible to rearrange alternately!";
   }

   string result = "";
   bool startWithVowel = vowels.size() >= consonants.size();
   int i = 0, j = 0;

   while (i < vowels.size() || j < consonants.size()) {
      if (startWithVowel && i < vowels.size()) {
         result += vowels[i++];
      }
      if (j < consonants.size()) {
         result += consonants[j++];
      }
      startWithVowel = true;  // After the first, always alternate
   }
   return result;
}

int main() {
   string inputs[] = {"individual", "noe", "objective"};

   for (string s : inputs) {
      cout << "Input : " << s << "\n";
      cout << "Output: " << alternateVowelConsonant(s) << "\n\n";
   }
   return 0;
}

The output of the above program is as follows:

Input : individual  
Output: inidivudal

Input : noe  
Output: one

Input : objective  
Output: bojecitev

Time Complexity: O(n), because we go through the string once to separate characters and once more to build the result.

Space Complexity: O(n), because we use extra space to store vowels, consonants, and the final result.

C Program to Alternate Vowels and Consonants

Here is a startC program that rearranges the letters of a string so that vowels and consonants appear alternately.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>  // for tolower

#define MAX_LEN 100

// Function to check if a character is a vowel
bool isVowel(char ch) {
    ch = tolower(ch);
    return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}

// Function to rearrange vowels and consonants in alternating order
const char* alternateVowelConsonant(const char* s) {
    static char result[MAX_LEN];
    char vowels[MAX_LEN] = "", consonants[MAX_LEN] = "";
    int vi = 0, ci = 0;

    // Separate vowels and consonants
    for (int i = 0; s[i]; i++) {
        if (isVowel(s[i]))
            vowels[vi++] = s[i];
        else
            consonants[ci++] = s[i];
    }

    vowels[vi] = '\0';
    consonants[ci] = '\0';

    // Check if alternating is possible
    if (abs(vi - ci) >= 2) {
        return "Not possible to rearrange alternately!";
    }

    int i = 0, j = 0, k = 0;
    bool startWithVowel = vi >= ci;

    while (i < vi || j < ci) {
        if (startWithVowel && i < vi)
            result[k++] = vowels[i++];
        if (j < ci)
            result[k++] = consonants[j++];
        startWithVowel = true; // alternate after first
    }

    result[k] = '\0';
    return result;
}

int main() {
    const char* inputs[] = {"individual", "noe", "objective"};
    int n = sizeof(inputs) / sizeof(inputs[0]);

    for (int i = 0; i < n; i++) {
        printf("Input : %s\n", inputs[i]);
        printf("Output: %s\n\n", alternateVowelConsonant(inputs[i]));
    }

    return 0;
}

Below is the output of the above program, where each string is rearranged so that vowels and consonants appear alternately:

Input : individual  
Output: indiuvidal

Input : noe  
Output: neon

Input : objective  
Output: obejctive

Time Complexity:O(n).

Space Complexity:O(n).

Conclusion

In this article, we learned to rearrange a string by placing vowels and consonants alternately, while keeping their original group order. We solved it by first separating vowels and consonants, then merging them alternately based on the valid starting character. The approach runs in O(n) time and uses O(n) space.

Updated on: 2025-08-04T16:36:50+05:30

410 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements