Letter Case Permutation in C++

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 −

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;




Published on 16-Jan-2020 11:11:18