It’s based on a musical notation system used in the Middle Ages.
First, let’s look at Merriam-Webster’s definition of the phrase:
“To encompass an entire range of something. Ex: Her emotions ran the gamut from joy to despair.”
To put that another way, “run the gamut" means to go from the start of something to the ending, and this meaning has an origin in medieval music theory. The monk Guido of Arezzo developed a system of syllables to denote musical tones in a scale (that type of system is called solfège, and the one we’re most familiar with uses the syllables do, re, mi, fah, so, la, and ti). He used “ut” to signify the lowest note. The musicians of the time had three different scales, each starting with C, F, or G, so any of those three notes could be “ut,” and G was the “gamma-ut.”
Eventually, “gamut" referred to the largest possible interpretation of a scale—from the lowest possible note to the highest possible note. At some point over the last few centuries, the phrase “run the gamut" came to mean singing (or playing) the entire scale. Today, we use it to refer to any especially large series of things.
We should note that people often confuse “run the gamut" with a similar phrase, “run the gauntlet.” The latter phrase means to endure a long, potentially painful ordeal. It comes from a form of punishment in which people would arrange themselves into two lines; the person receiving the punishment would walk down the lines, receiving beatings from each person in the lineup.
Again, the phrases are similar, but they’re not interchangeable. A politician might “run the gauntlet" by spending her days going door-to-door to attract voters, but if she appealed to voters of all ages, we could say that her voters “run the gamut from young to old.”