FunctionRacerProblemsRace

One From Each Group

EasyRecursionPython, JavaScript, TypeScript, Java, C++

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

groups ["ab","xy"]
returns ["ax","ay","bx","by"]

With a fixed, the second group gives ax then ay; then b gives bx and by.

Example 2

groups ["abc"]
returns ["a","b","c"]

There is one group, so each of its letters is a result on its own.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Recursion problems