#784
Letter Case Permutation
MediumApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute-force approach generates all possible combinations of the string by treating each letter independently. For each letter, we can either keep it as is or change its case, leading to a combinatorial explosion of possibilities.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a list to store all permutations.
- 2Step 2: Use a recursive function to explore each character in the string.
- 3Step 3: For each character, if it's a letter, branch into two recursive calls: one with the lowercase and one with the uppercase version.
- 4Step 4: If it's a digit, simply continue to the next character without changing it.
- 5Step 5: When reaching the end of the string, add the current permutation to the list.
solution.py19 lines
1def letterCasePermutation(s):
2 res = []
3 def backtrack(path, index):
4 if index == len(s):
5 res.append(''.join(path))
6 return
7 if s[index].isalpha():
8 path.append(s[index].lower())
9 backtrack(path, index + 1)
10 path.pop()
11 path.append(s[index].upper())
12 backtrack(path, index + 1)
13 path.pop()
14 else:
15 path.append(s[index])
16 backtrack(path, index + 1)
17 path.pop()
18 backtrack([], 0)
19 return resℹ
Complexity note: The time complexity is O(n²) because for each character, we might create two branches in the recursion tree, leading to 2^n combinations, and each combination takes O(n) time to build.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.