This is correct, but have you considered the runtime complexity? What happens if a large input, say 10000 elements is provided?
Take a look at this playground for an example (it is likely to timeout so you may wish to copy the code and run it locally) :)
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.