Nice idea, but I think the interviewer is going to ask you to avoid updating the original grid.
animageofmine
@animageofmine
Posts made by animageofmine

RE: My accepted c++ solution (may be trivial)

RE: C++ backtracking solution with detailed explanation
You don't need else block

RE: 7 lines C / C++
@Hal you are not alone. I face a lot of problems as well while solving such problems. I guess practice will make us better.

RE: Sharing my simple c++ code: O(n) time, O(1) space
excellent solution. Never thought of this idea. How long did it take for you to come up with this idea?

Easy to read, c++ solution
I tried updating the solution from part I of this problem, but I think it is a bad idea. I just simply started back from scratch and it was easy to come up with a solution.
The trick here is to find out the next pointers. I created a getNext function that takes care of the next pointers. The solution beats 81% of the other submitted solutions.
void connect(TreeLinkNode *root) { while (root) { TreeLinkNode* p = root; while (p) { if (p>left && p>right) { p>left>next = p>right; p>right>next = getNext(p>next); } else if (p>left) { p>left>next = getNext(p>next); } else if (p>right) { p>right>next = getNext(p>next); } p = p>next; } root = getNext(root); } } TreeLinkNode* getNext(TreeLinkNode* node) { while (node && !node>left && !node>right) { node = node>next; } return (node ? (node>left ? node>left : node>right) : NULL); }

RE: My easy understood solution with O(n) time and O(1) space without modifying the array. With clear explanation.
did you just come up with this idea in 30 minutes? Can you gives us an idea as to how long did it take? Because a lot of interviewers pick questions from this website. I want to see where I stand.

RE: Simple and fast C++/C with explanation
lovely explanation. Thanks so much!

RE: My concise O(m+n) Java solution
@hukun01 excellent point, it does save a lot of time (down from 206ms to 156ms). I would also like to make a minor point. This shouldn't matter in this solution, but in general, preincrement is better than postincrements (++i is better than i++) because of the way it works internally avoiding an extra register copy. Search online for the details.

RE: DP solution & some thoughts
lovely explanation, but if you observe carefully, you don't need O(n) space, all you are using is dp[i  1]. You can easily update the solution using O(1) space.

RE: An General Way to Handle All this sort of questions.
b'ful explanation! It was much easier to understand than the OP's comment, very much appreciated.