One From Each Group
groups is a list of strings; each string is a group of distinct lowercase letters. Return every string that can be made by taking exactly one letter from each group, in the order of the groups: the letter taken from groups[0] comes first, then the letter from groups[1], and so on.
List the results in nested-loop order: the choice from the first group changes slowest and the choice from the last group changes fastest, with the letters of each group tried in the order they are written. With no groups at all there is exactly one result, the empty string, so [] gives [""].
Nested loops cannot be written for an unknown number of groups, which is why recursion fits: pick a letter from the first group and put it in front of every result for the remaining groups.
For example, ["ab", "xy"] gives ["ax", "ay", "bx", "by"].
Example 1
With a fixed, the second group gives ax then ay; then b gives bx and by.
Example 2
There is one group, so each of its letters is a result on its own.
Constraints
0 <= len(groups) <= 41 <= len(groups[i]) <= 4- Each group holds distinct lowercase letters
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Recursion problems
- Subset SumsEasy
- Subsets by DoublingEasy
- Sum Then ProductEasy
- Teams of a Given SizeEasy
- The Climb FunctionEasy
- Count the BlobsMedium
- Discs After k MovesMedium
- Distinct Arrangements in OrderMedium