So, last week I refereed a paper for a journal. The paper in question is a reply to a previous paper by a different author: it points out a serious problem in the original paper and then proposes a solution. The evaluation I sent back to the editors is that, while the problem is real (to the extent that a different researcher has independently identified it), there are a number of reasons why the proposed solution is not going to work.
Over the weekend, I started thinking about the paper in question again and suddenly realized that I know how to solve the problem (in a nutshell: you need to use a technique originally developed to solve a mildly related class of problems, but which nobody had yet thought of applying to this particular domain). Right now, I have a bunch of handwritten notebook pages with everything I need to write a paper, and all I have left to do is to find a couple of hours to sit in front of my computer and type it up properly.
The question is, how should I proceed now? On the one hand, given that I've developed my own solution, I'm not plagiarizing the paper I refereed (in fact, I intend to give it proper credit for discovering the problem). On the other hand, if I hadn't been asked to referee this paper, I wouldn't have put enough thought into it to come up with my own solution. More generally, to what extent is it acceptable to write a paper that directly builds on a paper you've been asked to referee?