I should note:
this answer is OK. It provides C++ code but it also clearly explains the issue and what the solution should be. The fact that it's C++ code is not super relevant, you can treat it as pseudocode and implement in any language. But there are a bunch that just go "100/100 solution in <language> <code>".