algoadvance

Leetcode 784. Letter Case Permutation

Problem Statement

Leetcode Problem 784: Letter Case Permutation

Given a string s, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.

Example

Constraints

Clarifying Questions

  1. Does the transformation affect non-letter characters (e.g., digits)?
    • No, only letters (both lowercase and uppercase) are transformed.
  2. Is there an expected order in the output permutations?
    • No specific order is required for the output permutations.
  3. What should be returned if the input string contains no letters?
    • The output should be a list containing the original string itself.

Strategy

  1. Backtracking Approach:
    • Use a recursive backtracking approach to explore all possible transformations of the input string.
    • For each character in the string, decide whether to:
      • Keep the character as is (if it’s a digit).
      • Convert the character to both lowercase and uppercase and continue the search.
    • Collect all transformed strings into a result list.

Code

#include <vector>
#include <string>

using namespace std;

class Solution {
public:
    vector<string> letterCasePermutation(string s) {
        vector<string> result;
        backtrack(s, 0, "", result);
        return result;
    }

private:
    void backtrack(string &s, int index, string current, vector<string> &result) {
        if (index == s.size()) {
            result.push_back(current);
            return;
        }

        char c = s[index];
        if (isalpha(c)) {
            // Choice 1: Keep the current character in lowercase
            backtrack(s, index + 1, current + (char)tolower(c), result);
            // Choice 2: Change the current character to uppercase
            backtrack(s, index + 1, current + (char)toupper(c), result);
        } else {
            // If the character is not a letter, keep it as is
            backtrack(s, index + 1, current + c, result);
        }
    }
};

Time Complexity

This solution should be efficient enough given the constraint that (s) can have a maximum length of 12.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI