Letter Case Permutation in C++

C++Server Side ProgrammingProgramming

Suppose we have a string with letters and numbers. We have to generate all possible combinations of that string by taking uppercase and lowercase versions of letters that are present in the string. So if one string has only numbers, only that will be returned. Suppose the string is like “1ab2”, then the strings will be [“1ab2”, “1Ab2”, “1aB2”, “1AB2”]

To solve this problem, we will use recursive approach. It takes the index parameter to start work from that index. It also takes a temp string up to which the result is created. When the index is same as the string length, then return the temp string. For the given index, if that is lowercase letter, make it to uppercase and vice-versa, then recursively do the task.


Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<string> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   cout << "]"<<endl;
class Solution {
   vector <string> res;
   void solve(string s, int idx = 0, string temp = ""){
      if(idx == s.size()){
      solve(s, idx + 1, temp + s[idx]);
      int diff = 'a' - 'A';
      if(s[idx] >= 'a' && s[idx] <= 'z'){
         char x = (s[idx] - diff);
         solve(s, idx + 1, temp + x);
      else if (s[idx] >= 'A' && s[idx] <= 'Z'){
         char x = (s[idx] + diff);
         solve(s, idx + 1, temp + x);
   vector<string> letterCasePermutation(string S) {
      return res;
   Solution ob;




[1ab2, 1aB2, 1Ab2, 1AB2, ]
[9876, ]
Published on 16-Jan-2020 15:41:18