Generate all combinations of a string in JavaScript
Intermediate · 4 min read
Given the word 'dog', this exercise wants every piece you can cut out of it without skipping letters: d, do, dog, o, og and g. Lists like this power search-as-you-type boxes, word games and text tools that look for repeated patterns.
In this tutorial you will write a function called combinations that returns all of those pieces in an array. You will learn how two loops, one inside the other, can walk through every start and end position in a string. You need to know what a for loop and an array are.
Reading the expected output
The exercise names the result "combinations", but the expected output tells you more than the name does. Look at it again: d,do,dog,o,og,g.
- It is grouped by where each piece starts: first everything starting at
d, then ato, then atg. - Inside each group, the pieces grow one letter at a time.
dgis missing. You can't jump over theo.
A piece of a string with no gaps is called a substring. So the real task is: list every substring.
Cutting text with slice
slice(start, end) copies part of a string. start is the position of the first character you want (counting from 0), and end is the position just after the last one:
console.log('dog'.slice(0, 1)); // 'd'
console.log('dog'.slice(0, 3)); // 'dog'
console.log('dog'.slice(1, 3)); // 'og'
Because end is "one past", slice(0, 3) on a three-letter word gives the whole word. Every substring is just a slice with some start and some end.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
3 All combinations of a string
fair'dog' should give d,do,dog,o,og,g. Work out from that ordering what is being generated.
Stuck? Three hints, smallest first
- 1. Read the expected output: grouped by starting position, growing in length.
- 2. Those are contiguous substrings.
‘dg’is absent, so gaps are not allowed. - 3. There are exactly
n(n+1)/2of them.
Step 1: one loop for the start
Begin with the outer loop. It visits each position a substring can start at:
const text = 'dog';
for (let start = 0; start < text.length; start++) {
console.log('start at', start, text[start]);
}
That prints three lines: start at 0 d, start at 1 o and start at 2 g. These are the three groups in the expected output.
Step 2: a second loop for the end
For each start, the end can be anywhere from one past the start up to the end of the word. A loop inside a loop is called a nested loop:
for (let start = 0; start < 'dog'.length; start++) {
for (let end = start + 1; end <= 'dog'.length; end++) {
console.log(start, end, 'dog'.slice(start, end));
}
}
Notice two details in the inner loop:
endstarts atstart + 1, so every piece has at least one letter.- The test is
end <= text.length, with<=. With<you would never reach the last letter, anddog,ogandgwould be missing.
Step 3: collect the pieces in an array
Printing is good for seeing what happens. A function should return the results instead, so push each slice into an array:
function combinations(text) {
const out = [];
for (let start = 0; start < text.length; start++) {
for (let end = start + 1; end <= text.length; end++) {
out.push(text.slice(start, end));
}
}
return out;
}
console.log(combinations('dog')); // [ 'd', 'do', 'dog', 'o', 'og', 'g' ]
console.log(combinations('dog').join(',')); // 'd,do,dog,o,og,g'
join(',') turns the array into the exact comma-separated text the exercise shows.
Step 4: how many pieces?
A word with 3 letters gave 6 pieces. There is a formula: a string of length n has n × (n + 1) / 2 substrings. For 'dog' that is 3 × 4 / 2 = 6, and for 'house' it is 5 × 6 / 2 = 15:
console.log(combinations('house').length); // 15
console.log(combinations('').length); // 0
The empty string has no letters, so the outer loop never runs and you get an empty array.
Step 5: repeated letters
Try a word with the same letter twice:
console.log(combinations('aa')); // [ 'a', 'aa', 'a' ]
const distinct = (text) => [...new Set(combinations(text))];
console.log(distinct('aa')); // [ 'a', 'aa' ]
'a' appears twice because it was cut from two different positions. Whether you want that depends on the question. If you only want each different piece once, put the results in a Set, which keeps one copy of each value, then spread it back into an array. That is what distinct does.
The full solution
The panel has combinations, an asList helper that joins the result with commas, and distinct. It prints the pieces for 'dog', the expected text, the 'aa' case both ways and the count for 'house'. Press Run to see the output.
function combinations(text) {
const out = [];
for (let start = 0; start < text.length; start++) {
for (let end = start + 1; end <= text.length; end++) {
out.push(text.slice(start, end));
}
}
return out;
}
// The expected output is comma-separated, which is where the example comes from.
const asList = (text) => combinations(text).join(',');
// Only the distinct ones, which differs as soon as a letter repeats.
const distinct = (text) => [...new Set(combinations(text))];
console.log("combinations('dog') :", combinations('dog'));
console.log("the expected output :", asList('dog'));
console.log("combinations('aa') :", combinations('aa'), '<- "a" twice, by position');
console.log("distinct('aa') :", distinct('aa'));
console.log('count for a 5-letter word:', combinations('house').length, '= 5 x 6 / 2');
Output
14 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 14 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the expected output, exactly", asList('dog'), 'd,do,dog,o,og,g');
test('as an array', combinations('dog'), ['d', 'do', 'dog', 'o', 'og', 'g']);
test('six of them', combinations('dog').length, 6);
test('which is n(n+1)/2', combinations('dog').length, (3 * 4) / 2);
test('and for a longer word', combinations('house').length, (5 * 6) / 2);
test('one letter gives one', combinations('a'), ['a']);
test('the empty string gives none', combinations(''), []);
test('the whole string is always included', combinations('dog').includes('dog'), true);
test('gaps are not allowed', combinations('dog').includes('dg'), false);
test('every result is a real slice of the input', combinations('dog').every((s) => 'dog'.includes(s)), true);
test('repeated letters give repeated results', combinations('aa'), ['a', 'aa', 'a']);
test('because these are positions, not values', combinations('aa').length, 3);
test('deduplicating changes the count', distinct('aa').length, 2);
test('but not for a word with no repeats', distinct('dog').length, combinations('dog').length);
Object 7 asks for the same thing and calls it "subsets" there. It is neither a subset nor a combination in the mathematical sense: those allow gaps, and 'dg' is absent from the expected output. What is being asked for is every contiguous substring, which is why two nested loops suffice and why there are exactly n(n+1)/2 of them.
The 'aa' assertions are the detail worth noticing. It produces ['a', 'aa', 'a'] — 'a' twice, because these are positions rather than values. Whether you want the duplicates depends on the question, so distinct is there too and the difference is asserted rather than assumed.
Common mistakes
- Using
end < text.length. The last letter is never included, so'dog'losesdog,ogandg. - Starting
endatstart.slice(1, 1)is the empty string'', so you fill the list with empty pieces. - Expecting gaps. Two nested loops only make substrings.
dgneeds a different method, one that chooses letters to keep or drop.
Try it yourself
- Change the function so it only returns pieces of length 2 or more. For
'dog'you should get['do', 'dog', 'og']. - Sort the result of
combinations('dog')from shortest to longest withsort((a, b) => a.length - b.length). - Count the distinct substrings of
'banana', usingdistinct. Compare it withcombinations('banana').length.