Watch tutorials and explanations by expert teachers that walk through solving this problem.
NeetCode
Inside code
NeetCodeIO
Solve more problems to master this pattern