TITLE: Number of functions $f:\{1,...,n\}\to\{1,...,n\}$ that have $|f^{-1}(\{i\})|=i$ for some $i$
QUESTION [17 upvotes]: Let $S=\{1,...,n\}$, I am looking at number of functions functions $f:S\to S$ such that there exists $i \in S$ such that $$|f^{-1}(\{i\})|=i$$
I am guessing I am supposed to use PIE (Principle of Inclusion and Exclusion)
I let $X=\{f:S\to S\}$.
My attempt is to define $A_i=\{f\in X;|f^{-1}(\{i\})|=i\}$.
It can be computed that $|A_i|=\binom{n}{i}(n-1)^{n-i}$.
Similarly, $|A_i\cap A_j|=\binom{n}{i}\binom{n-i}{j}(n-2)^{n-i-j}$.
but I am not sure how to proceed.

REPLY [6 votes]: Using combinatorial classes as in Analytic Combinatorics by Flajolet
and Sedgewick we  get for the complementary problem  i.e. no pre-image
$f^{-1}(k)$ of $k$ having $k$ elements the class
$$\def\textsc#1{\dosc#1\csod}
\def\dosc#1#2\csod{{\rm #1{\small #2}}}
\prod_{k=1}^n \textsc{SET}_{\ne k}(\mathcal{Z})$$
with EGF
$$F(z) = \prod_{k=1}^n  \left(\exp(z)-\frac{z^k}{k!}\right).$$
The desired quantity is then given by
$$n^n - n! [z^n] F(z)$$
or
$$\bbox[5px,border:2px solid #00A000]{
n^n - n! [z^n]
\prod_{k=1}^n  \left(\exp(z)-\frac{z^k}{k!}\right).}$$
It appears that for computational purposes the alternate form below
is slightly more efficient:
$$\bbox[5px,border:2px solid #00A000]{
n^n - n! [z^n]
\prod_{k=1}^n  \sum_{q=0, q\ne k}^n \frac{z^q}{q!}.}$$
Here we have used the class
$$\def\textsc#1{\dosc#1\csod}
\def\dosc#1#2\csod{{\rm #1{\small #2}}}
\prod_{k=1}^n \textsc{SET}_{\ne k, \le n}(\mathcal{Z}).$$
The sequence starts as follows:
$$1, 3, 16, 147, 1756, 25910, 453594, 9184091, 211075288, 5427652794,
\\ 154380255250, 4812088559014, 163110595450466, 5973198636395003,
\ldots $$