What is the optimal length of H1 and H2 for a good SEO?

There is no optimal length, it depends on the content of your page, but generally, the H2 tags are longer than the H1 tags because they describe the subtitles with respect to H1 and it is better to use H1 to emphasize important text, for example

Optimal length of H1 and H2 for SEO

Why does it matter to know the optimal length for H1 and H2?

How different lengths of H1 and H2 affects SEO?

But it is always better to make H2 tags shorter and H1 tags shorter and to the point, do not fill it with unnecessary words because that will negatively affect your SEO.
For example, if someone searches Foo
, and there are 2 websites equally SEO, except for that
one has the H1 as

Foo

the other one has the H1 as

Foo Bar Baz

The number 1 site will be the first because 100% of the keywords are Foo, but if it was Foo Bar Baz, 33% will be for each keyword (only with respect to the header).

Another rule of length factor is the content of your website.
Having keywords in the header that are repeated several times in their content is a good practice.

Foo Bar

content:

200 words of content is a good practice regarding foo bar because 200 words of content foo 200 words of content bar

The only thing that Google explicitly mentioned regarding the length of the titles is not to use very long titles.