A common problem that can occur with any computer is a keyboard malfunctioning and typing random characters. There can be other reasons why characters are being randomly typed on your computer but a faulty keyboard is usually the main culprit.
On your Apple iMac you might find that even after replacing a Wireless Keyboard with another one or trying a standard USB keyboard the problem still exists.
You have also unplugged all other USB devices from your Mac whilst troubleshooting.
Resolution
Ensure that the suspected faulty Wireless keyboard has been disconnected from the iMac by turning it off (holding down the power button on the right hand side) or un-pairing it in the Bluetooth Settings. If connecting a new Wireless Keyboard you may automatically assume that the old one automatically disconnects which is not the case. It is possible to have more than one Wireless Keyboard connected to your iMac at the same time.
This sounds like the result of RF interference.
I’ve had my iMac Bluetooth keyboard type endless random strings of characters after the computer “wakes.” Rejoining the keyboard fixes this, but it seems to be a preventable problem if you figure out what is causing the interference. I’ve noticed that a nearby Microsoft Surface Book disrupts not only the keyboard but Bluetooth audio connections. Running a microwave nearby often jams BT signals too.