Programming Search⌘K

Conceptadvanced

Multiset

Also called bag, mset, counter, Counter, std::multiset, Multiset, frequency map, count map.

A multiset is a set in which an item can appear more than once. Programs store it as a map from each item to its count, as Python Counter does.

Applies to
core-languages

Idea

A set holds each item once. A list holds items in an order. A multiset is between the two: it can hold an item more than once, like a list, but the order does not matter, like a set. The letters of a word, the words of a text, the coins in a pocket and the items in a shopping cart are multisets.

Wikipedia defines a multiset, also called a bag, as "a modification of the concept of a set"1 that "allows for multiple instances for each of its elements"1. "The number of instances given for each element is called the multiplicity of that element in the multiset."1 A program rarely stores every copy. It stores each item once, with its count. Python Counter works this way: "It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values."2

from collections import Counter

# A multiset is a set that can hold an item more than once.
# Counter stores each item once, with the number of times it appears.
bag = Counter(["apple", "pear", "apple", "fig", "apple", "pear"])
print(bag)
print(bag["apple"], bag["kiwi"])

# Order does not matter: two lists with the same items the same number of times are equal as multisets.
print(Counter("listen") == Counter("silent"), Counter("aab") == Counter("ab"))

# The size counts every copy. The number of distinct items is smaller.
print(bag.total(), len(bag))

# Union takes the larger count, intersection the smaller, sum adds the counts.
a, b = Counter("aabc"), Counter("abbd")
print(sorted((a | b).elements()), sorted((a & b).elements()), sorted((a + b).elements()))
Output
Counter({'apple': 3, 'pear': 2, 'fig': 1})
3 0
True False
6 3
['a', 'a', 'b', 'b', 'c', 'd'] ['a', 'b'] ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'd']

The words listen and silent use the same letters the same number of times, so their multisets are equal. The strings aab and ab use the same letters, so their sets are equal, but their multisets are not.

How it works

A map from item to count. The usual form is a map whose values are counts. To add an item, add 1 to its count, or put 1 if the item is new. To remove one copy, take 1 from the count, and remove the key when the count reaches 0. The count of an item that is not in the map is 0. Python Counter returns this 0: "Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError"2. The Java Map.merge method does the update in one call, and it removes the key when the function returns null: "If the remapping function returns null, the mapping is removed."3

Every copy in a sorted container. C++ std::multiset stores every copy. It "is an associative container that contains a sorted set of objects of type Key. Unlike set, multiple keys with equivalent values are allowed."4 The copies of a value sit next to each other in the tree. This form is useful when the copies are equivalent by the order but different in other fields, for example records sorted by date.

Operations. The operations of sets have multiset forms that work on the counts. For Python, "Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts."2 Inclusion asks whether each count in one multiset is less than or equal to the count in the other. It answers the question: can the letters of this note be cut from that page?

Size. A multiset has two sizes: the number of copies and the number of distinct items. In the idea above, the bag has six fruits but three kinds of fruit. Guava says its Multiset helps with "collecting a variety of useful statistics, like the total number of words"5, which a plain map of counts does not give.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiomTypeScript uses the JavaScript idiom, a Map<T, number> from item to count. No example file exists.
GoIdiom
RustIdiom
KotlinIdiomGroupingBy { it }.eachCount() counts the items of a collection into a Map<T, Int>. A MutableMap updated with merge or getOrDefault is the form that can change. No example file exists because kotlinc is not installed.
SQLNativeA table without a unique constraint and the result of a query are multisets of rows. GROUP BY with COUNT(*) gives the count of each value, and UNION ALL keeps the copies that UNION removes.
BashIdiomAn associative array of counts, updated with ((count[key]++)). The pipeline sort | uniq -c counts the lines of a text. No example file exists.
PowerShellIdiomGroup-Object gives each distinct value with its Count, and a hashtable of counts is the form that can change. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup and has no data structures.
CSSDoes not applyCSS has no data structures.
Regular expressionsDoes not applyA regular expression matches text. It has no collections.
Language Verdict Mechanism
Python stdlib collections.Counter, with most_common, total, elements and + - | &
JavaScript idiom a Map from item to count
TypeScript idiom the JavaScript idiom, typed as Map<T, number>
Java idiom Map<E, Integer> with merge; Collectors.counting; Guava Multiset
Kotlin idiom groupingBy { it }.eachCount(); a MutableMap of counts
C# idiom CountBy in .NET 9; a Dictionary<T, int> of counts
Go idiom map[T]int; a missing key reads as 0, so m[k]++ works
Rust idiom HashMap<T, usize> with *m.entry(k).or_insert(0) += 1
C idiom an array of counts for a small alphabet, or a hash table of counts
C++ stdlib std::multiset and std::unordered_multiset; std::map<T, int> of counts
Bash idiom an associative array of counts; sort | uniq -c for lines
PowerShell idiom Group-Object, or a hashtable of counts
SQL native tables and query results are multisets of rows; GROUP BY with COUNT(*)
Regex n/a patterns match text and have no collections
HTML n/a markup with no data structures
CSS n/a style rules with no data structures

Python names the idea directly: "The Counter class is similar to bags or multisets in other languages."2 C++ has two multiset containers, a sorted one and a hashed one. For the sorted one, "Search, insertion, and removal operations have logarithmic complexity."4

Java has no multiset in its standard library. Guava describes the plain Java form, a Map<String, Integer> updated by hand, as "awkward, prone to mistakes, and doesn't support collecting a variety of useful statistics"5, and adds a Multiset type. With Java 8 and later, merge and Collectors.counting make the map form short. Guava's count method returns "the number of occurrences of an element that have been added to this multiset"5.

The example files show these forms. Python uses the Counter methods and shows that a count set to 0 stays in the counter. JavaScript builds a Map of counts and writes equality and the removal of one copy by hand. Java uses merge and Collectors.counting. C# uses CountBy and CollectionsMarshal.GetValueRefOrAddDefault. Go uses m[k]++ and maps.Equal. Rust uses entry and compares two BTreeMap values. C uses an array of 26 counts to test anagrams and inclusion. C++ uses std::multiset with count, equal_range and both forms of erase.

PythonGitHub
from collections import Counter

words = "the cat and the hat and the bat".split()
c = Counter(words)

# most_common gives the items with the highest counts first.
print(c.most_common(2))

# A missing item has the count 0, not a KeyError.
print(c["dog"], "dog" in c)

# Subtraction removes items whose count becomes zero or less.
print(Counter(a=3, b=1) - Counter(a=1, b=2))

# But setting a count to 0 keeps the item. Use del to remove it.
c["cat"] = 0
print("cat" in c, c.total())
del c["cat"]
print("cat" in c)

# update adds counts. subtract can make counts negative.
d = Counter(a=1)
d.update("aab")
d.subtract({"b": 3})
print(d)

# Is one multiset contained in another? Every count must be less or equal.
need, have = Counter("aab"), Counter("abca")
print(need <= have, Counter("aaa") <= have)
Output
[('the', 3), ('and', 2)]
0 False
Counter({'a': 2})
True 7
False
Counter({'a': 3, 'b': -2})
True False
  • Verdict: stdlib. collections.Counter is a dict from item to count. A missing item counts 0, most_common gives the top items, and + - | & combine counters. Subtraction drops counts of zero or less, but a count set to 0 stays until del. <= tests that one multiset is inside another.
#include <iostream>
#include <iterator>
#include <set>
#include <string>

int main() {
    // std::multiset keeps every copy, in sorted order.
    std::multiset<std::string> m{"the", "cat", "and", "the", "hat", "and", "the", "bat"};
    for (const auto& w : m) std::cout << w << " ";
    std::cout << "end\n";
    std::cout << m.count("the") << " " << m.count("dog") << " " << m.size() << "\n";

    // erase(value) removes every copy. erase(iterator) removes one.
    m.erase(m.find("the"));
    std::cout << m.count("the") << "\n";
    std::cout << m.erase("the") << " " << m.count("the") << " " << m.size() << "\n";

    // equal_range gives the run of copies of one value.
    auto [lo, hi] = m.equal_range("and");
    std::cout << std::distance(lo, hi) << "\n";

    // Two multisets compare equal when they hold the same values the same number of times.
    std::multiset<char> a{'l', 'i', 's', 't', 'e', 'n'}, b{'s', 'i', 'l', 'e', 'n', 't'};
    std::cout << (a == b) << "\n";
}
Output
and and bat cat hat the the the end
3 0 8
2
2 0 5
2
1
  • Verdict: stdlib. std::multiset and std::unordered_multiset keep every copy. count gives the number of copies, erase with a value removes all copies, and erase with an iterator removes one. A std::map<K, int> of counts is the other common form.
JavaGitHub
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    String[] words = "the cat and the hat and the bat".split(" ");

    // merge with Integer::sum adds 1 to the count, or puts 1 for a new word.
    Map<String, Integer> counts = new TreeMap<>();
    for (String w : words) counts.merge(w, 1, Integer::sum);
    System.out.println(counts + " " + counts.getOrDefault("dog", 0));

    // groupingBy with counting builds the same multiset from a stream.
    Map<String, Long> byStream = Stream.of(words)
        .collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()));
    System.out.println(byStream);

    // Remove one copy: merge with -1, and return null at zero to remove the key.
    counts.merge("and", -1, (a, b) -> a + b == 0 ? null : a + b);
    counts.merge("cat", -1, (a, b) -> a + b == 0 ? null : a + b);
    System.out.println(counts.get("and") + " " + counts.containsKey("cat"));

    // The size of the multiset is the sum of the counts.
    int total = counts.values().stream().mapToInt(Integer::intValue).sum();
    System.out.println(counts.size() + " " + total);
  }
}
Output
{and=2, bat=1, cat=1, hat=1, the=3} 0
{and=2, bat=1, cat=1, hat=1, the=3}
1 false
4 6
  • Verdict: idiom. A Map<E, Integer> updated with merge(e, 1, Integer::sum), or Collectors.groupingBy with Collectors.counting. A merge function that returns null removes the key at zero. Guava has Multiset, HashMultiset and TreeMultiset.
#include <ctype.h>
#include <stdio.h>
#include <string.h>

/* For a small, known alphabet, a multiset is an array of counts. */
static void count(const char *s, int c[26]) {
    memset(c, 0, 26 * sizeof c[0]);
    for (; *s; s++)
        if (isalpha((unsigned char)*s)) c[tolower((unsigned char)*s) - 'a']++;
}

/* Is every count of a less than or equal to the count in b? */
static int subset(const int a[26], const int b[26]) {
    for (int i = 0; i < 26; i++)
        if (a[i] > b[i]) return 0;
    return 1;
}

int main(void) {
    int a[26], b[26];
    count("Listen", a);
    count("Silent", b);
    printf("anagram %d\n", memcmp(a, b, sizeof a) == 0);

    count("aab", a);
    count("ab", b);
    printf("anagram %d\n", memcmp(a, b, sizeof a) == 0);

    /* Can the letters of a note be cut from a magazine page? */
    count("cab", a);
    count("abracadabra", b);
    printf("subset %d %d\n", subset(a, b), subset(b, a));

    /* The size of the multiset and the number of distinct letters. */
    int total = 0, distinct = 0;
    for (int i = 0; i < 26; i++) {
        total += b[i];
        distinct += b[i] > 0;
    }
    printf("%d %d a=%d\n", total, distinct, b[0]);
    return 0;
}
Output
anagram 1
anagram 0
subset 1 0
11 5 a=5
  • Verdict: idiom. For a small known alphabet, a multiset is an array of counts. memcmp compares two of them, and a loop over the counts tests whether one multiset is inside another.
using System.Runtime.InteropServices;

string[] words = "the cat and the hat and the bat".Split(' ');

// CountBy (.NET 9) counts the items in one call.
var counted = words.CountBy(w => w).OrderByDescending(p => p.Value).ThenBy(p => p.Key, StringComparer.Ordinal);
Console.WriteLine(string.Join(" ", counted.Take(2)));

// A Dictionary of counts. GetValueRefOrAddDefault adds the key with 0 and
// returns a reference to the count, so one lookup does the update.
var counts = new Dictionary<string, int>();
foreach (var w in words) CollectionsMarshal.GetValueRefOrAddDefault(counts, w, out _)++;
Console.WriteLine($"{counts["the"]} {counts.GetValueOrDefault("dog")} {counts.Count} {counts.Values.Sum()}");

// Two multisets are equal when every key has the same count.
static Dictionary<char, int> Bag(string s) => s.GroupBy(ch => ch).ToDictionary(g => g.Key, g => g.Count());
static bool Same(Dictionary<char, int> a, Dictionary<char, int> b) =>
    a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var n) && n == p.Value);
Console.WriteLine($"{Same(Bag("listen"), Bag("silent"))} {Same(Bag("aab"), Bag("ab"))}");
Output
[the, 3] [and, 2]
3 0 5 8
True False
  • Verdict: idiom. .NET has no multiset type. CountBy from .NET 9 counts in one call, and CollectionsMarshal.GetValueRefOrAddDefault updates a Dictionary<TKey, int> with one lookup.
JavaScriptGitHub
// JavaScript has no multiset. A Map from item to count is the usual form.
function count(items) {
  const m = new Map();
  for (const x of items) m.set(x, (m.get(x) ?? 0) + 1);
  return m;
}

const c = count("the cat and the hat and the bat".split(" "));
console.log([...c].map(([k, v]) => `${k}=${v}`).join(" "));
console.log(c.get("the"), c.get("dog") ?? 0);

// The most common items: sort the entries by count, then by name.
const top = [...c].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 2);
console.log(top);

// Two multisets are equal when they have the same keys with the same counts.
function equal(a, b) {
  if (a.size !== b.size) return false;
  for (const [k, v] of a) if (b.get(k) !== v) return false;
  return true;
}
console.log(equal(count("listen"), count("silent")), equal(count("aab"), count("ab")));

// Remove one copy: lower the count, and delete the key at zero.
function removeOne(m, x) {
  const n = m.get(x) ?? 0;
  if (n <= 1) m.delete(x);
  else m.set(x, n - 1);
}
removeOne(c, "and");
removeOne(c, "cat");
console.log(c.get("and"), c.has("cat"), c.size);
Output
the=3 cat=1 and=2 hat=1 bat=1
3 0
[ [ 'the', 3 ], [ 'and', 2 ] ]
true false
1 false 4
  • Verdict: idiom. JavaScript has no multiset. A Map from item to count, updated with (m.get(x) ?? 0) + 1. Equality, the most common items and the removal of one copy are short functions.
package main

import (
	"fmt"
	"maps"
	"slices"
	"strings"
)

func count(items []string) map[string]int {
	m := map[string]int{}
	for _, x := range items {
		m[x]++ // a missing key reads as 0
	}
	return m
}

func main() {
	c := count(strings.Fields("the cat and the hat and the bat"))
	keys := slices.Sorted(maps.Keys(c))
	for _, k := range keys {
		fmt.Printf("%s=%d ", k, c[k])
	}
	fmt.Println("end")
	fmt.Println(c["the"], c["dog"])

	// maps.Equal compares two multisets of letters.
	letters := func(s string) map[string]int { return count(strings.Split(s, "")) }
	fmt.Println(maps.Equal(letters("listen"), letters("silent")), maps.Equal(letters("aab"), letters("ab")))

	// Remove one copy, and delete the key when the count reaches 0.
	for _, w := range []string{"and", "cat"} {
		c[w]--
		if c[w] == 0 {
			delete(c, w)
		}
	}
	total := 0
	for _, n := range c {
		total += n
	}
	_, hasCat := c["cat"]
	fmt.Println(c["and"], hasCat, len(c), total)
}
Output
and=2 bat=1 cat=1 hat=1 the=3 end
3 0
true false
1 false 4 6
  • Verdict: idiom. A map[K]int. A missing key reads as 0, so m[k]++ needs no check. maps.Equal compares two multisets. The program deletes a key when its count reaches 0.
RustGitHub
use std::collections::BTreeMap;

fn count(s: &str) -> BTreeMap<char, usize> {
    let mut m = BTreeMap::new();
    for ch in s.chars() {
        *m.entry(ch).or_insert(0) += 1;
    }
    m
}

fn main() {
    let words = "the cat and the hat and the bat";
    let mut c: BTreeMap<&str, usize> = BTreeMap::new();
    for w in words.split_whitespace() {
        *c.entry(w).or_insert(0) += 1;
    }
    println!("{:?}", c);
    println!("{} {}", c["the"], c.get("dog").copied().unwrap_or(0));

    // The most common word: max by count, then by the smaller word on a tie.
    let top = c.iter().max_by(|a, b| a.1.cmp(b.1).then(b.0.cmp(a.0))).unwrap();
    println!("{:?}", top);

    // Two BTreeMaps compare equal when they have the same keys and counts.
    println!("{} {}", count("listen") == count("silent"), count("aab") == count("ab"));

    // Remove one copy; remove the key at zero.
    for w in ["and", "cat"] {
        if let Some(n) = c.get_mut(w) {
            *n -= 1;
            if *n == 0 {
                c.remove(w);
            }
        }
    }
    let total: usize = c.values().sum();
    println!("{:?} {} {} {}", c.get("and"), c.contains_key("cat"), c.len(), total);
}
Output
{"and": 2, "bat": 1, "cat": 1, "hat": 1, "the": 3}
3 0
("the", 3)
true false
Some(1) false 4 6
  • Verdict: idiom. A HashMap<K, usize> or BTreeMap<K, usize> updated with *m.entry(k).or_insert(0) += 1. Two maps compare equal with ==. The standard library has no multiset type.
  • Word counts. Counting the words of a text builds a multiset. See count word frequencies.
  • Sets. A multiset whose counts are all 1 is a set. The keys of a count map are the set of distinct items. See remove duplicates from a list.
  • Multimaps. A multimap keeps a list of values for each key. A multiset keeps only the number of values.
  • Sorted multisets. A sorted multiset can count the items in a range. Guava TreeMultiset and C++ std::multiset do this, and so does an ordered map of counts.
  • Histograms. A histogram is a multiset of the values that fall into each bin. A count map of the bin numbers builds one.
  • Signed counts. Python Counter allows counts of zero and below, so it can hold a difference between two multisets. A true multiset has only positive counts.

Pitfalls

  • Keys with a count of zero. Python says: "Setting a count to zero does not remove an element from a counter. Use del to remove it entirely"2. Then len and in count an item that has no copies. In any count map, remove the key when its count reaches 0.
  • Negative counts. Python subtract and a hand-written update can make a count below zero. The - operator drops counts of zero or less, but subtract keeps them. Check which one the program needs.
  • Equality of count maps. Two count maps are equal multisets only when no key has a count of 0. A map with {"a": 1, "b": 0} is not equal to {"a": 1} as a dict, but it holds the same multiset.
  • Two sizes. len of a Counter and size of a Map give the number of distinct items. The number of copies is the sum of the counts, which Python 3.10 gives with total.
  • Erase in C++. m.erase(value) on a std::multiset removes every copy. To remove one copy, use m.erase(m.find(value)), after a check that find did not return end().
  • Ties in the top items. Python most_common orders items with equal counts by first appearance. Other languages give no order for ties. Sort by count and then by the item to get a stable result.

Cost

Operation Hash map of counts Tree map of counts std::multiset (every copy)
add one copy constant on average logarithmic in the distinct items logarithmic in the copies
count of an item constant on average logarithmic logarithmic + the count
remove one copy constant on average logarithmic logarithmic
union, intersection, sum linear in the distinct items linear in the distinct items linear in the copies
top k items n log k with a heap, or a sort the same the same
memory one entry for each distinct item one node for each distinct item one node for each copy

A map of counts is much smaller than a list of copies when items repeat often. A count array, as in the C example, is the smallest and fastest form when the items are small integers or letters.

History

The idea is old, but the name is new. Wikipedia: "Nicolaas Govert de Bruijn coined the word multiset in the 1970s, according to Donald Knuth."1 Smalltalk-80 had a Bag class. The C++ Standard Template Library had multiset, and it became part of the C++ standard in 1998. SQL tables and query results have always been multisets of rows, and UNION ALL keeps the copies that UNION removes. Python added collections.Counter in 2.7 and 3.1, and total in 3.10. Guava added Multiset for Java, and .NET 9 added CountBy in 2024.

References

  1. Multiset, Wikipedia, Introduction
  2. collections, Container datatypes, The Python Standard Library, Counter objects
  3. Interface Map, Java SE 25 API, merge
  4. std::multiset, cppreference.com, Description
  5. New Collection Types Explained, Guava wiki, Multiset

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DEB5SJ/text.yaml