Arrays and strings · Exercise 2 of 100

Factorial

The factorial of a nonnegative whole number counts how many ways you can arrange that many distinct items in a row. Multiply the number of choices for each position as the choices drop from the starting number to one. The factorial of zero is one because there is one empty arrangement.

Try it yourself

You have five different postcards. How many orders can you put all five in?

One-step hint

Draw a slot for each postcard. Write how many cards are still available for each slot, then multiply those counts.

Worked solution
  1. Choose among 5 cards for the first spot, then 4 for the second and 3 for the third. That gives 60 ways to fill those spots.
  2. Each of those choices leaves 2 options for the fourth spot and 1 for the last, giving 60 × 2 × 1 = 120 orders.
DSA compiler

Explore the idea visually in the big o and counting comparisons lab.