Faaez Razeen

Letter Case Permutation

  • 3 min read
  • LC-Medium
  • Backtracking

3 years ago

Solution

TimeSpaceExplanation
O(2^n)O(n)Space is because of recursion call stack depth
function isAlphabet(char) { const alphabets = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return alphabets.includes(char); } function letterCasePermutation(s: string): string[] { const permutations: string[] = []; function dfs(i: number, perm: string) { if (i === s.length) { permutations.push(perm); return; } if (isAlphabet(s[i])) { dfs(i + 1, perm + s[i].toLowerCase()); dfs(i + 1, perm + s[i].toUpperCase()); } else { dfs(i + 1, perm + s[i]); } } dfs(0, ''); return permutations; };

Inefficient (but pretty (imo)) solution

Why inefficient?

Because it uses a set to store values to avoid duplicates Duplicates occur because there are similar DFS branches due to the solution below not checking if the current character is lowercase before "converting" it to lowercase, and vice versa for uppercase

enum CaseType { LOWER = 'lower', UPPER = 'upper', NEITHER = 'neither' } function getCharCase(char: string): CaseType { if (char >= 'a' && char <= 'z') { return CaseType.LOWER; } else if (char >= 'A' && char <= 'Z') { return CaseType.UPPER; } else { return CaseType.NEITHER; } } function permuteLetter(ch: string) { switch (getCharCase(ch)) { case CaseType.NEITHER: return ch; case CaseType.LOWER: return ch.toUpperCase(); case CaseType.UPPER: return ch.toLowerCase(); } } function letterCasePermutation(s: string): string[] { const permutations = new Set(); function dfs(i: number, perm: string[]) { if (i === s.length) { permutations.add(perm.join('')); return; } perm.push(permuteLetter(s[i])); dfs(i + 1, perm); perm.pop(); perm.push(s[i]); dfs(i + 1, perm); perm.pop(); } dfs(0, []); return Array.from(permutations) as string[]; };