Introduction
It is the first time I like to ask new algorithms in my mock interviews. I like to review a few algorithms before I work on an online code screen this weekend. I asked the algorithm I just reviewed called Letter tiles possibilities. Here is my post.
Mock interview case study
The transcript starts here:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
/* | |
* To execute Java, please define "static void main" on a class | |
* named Solution. | |
* | |
* If you need more classes, simply define them inline. | |
*/ | |
class Solution { | |
public static void main(String[] args) { | |
ArrayList<String> strings = new ArrayList<String>(); | |
strings.add("Hello, World!"); | |
strings.add("Welcome to CoderPad."); | |
strings.add("This pad is running Java " + Runtime.version().feature()); | |
for (String string : strings) { | |
System.out.println(string); | |
} | |
possibleSequence("AAB"); | |
//possibleSequence("AAABBC"); | |
} | |
public static int possibleSequence(String inp) { | |
Set<String> set = generateSequences(inp.toCharArray()); | |
//System.out.println(set); | |
System.out.println(set.size()); | |
return 0; | |
} | |
public static Set<String> generateSequences(char[] chars) { | |
Set<String> set = new HashSet<>(); | |
if (chars.length == 1) { | |
set.add(String.valueOf(chars[0])); | |
return set; | |
} | |
for (int i = 0; i < chars.length; i++) { | |
char temp = chars[0]; // put ith to 0th | |
chars[0] = chars[i]; | |
chars[i] = temp; | |
char[] rem = new char[chars.length - 1]; // take one off | |
System.arraycopy(chars, 1, rem, 0, rem.length); // rem - | |
Set<String> result = generateSequences(rem); // hashset | |
for (String res: result) { // | |
set.add(String.format("%s%s", String.valueOf(chars[0]), res)); //? | |
set.add(String.format("%s", res)); // ? | |
} | |
/* | |
"A" ? | |
"B" ? | |
"A" | |
"B" | |
Char[0] + "A" | |
Char[0] + "B" | |
*/ | |
temp = chars[0]; | |
chars[0] = chars[i]; | |
chars[i] = temp; | |
} | |
return set; | |
} | |
} | |
/* | |
You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make. | |
Example 1: | |
Input: "AAB" | |
Output: 8 | |
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". | |
Example 2: | |
Input: "AAABBC" | |
Output: 188 | |
Find permutations for all possible lengths, factor in repeating | |
n! / (n - r)! | |
Note: | |
1 <= tiles.length <= 7 | |
tiles consists of uppercase English letters. | |
*/ |
No comments:
Post a Comment