Solving dynamic programming interview problems
blog.refdash.com
blog.refdash.com
1. Write a recursive solution.
2. Memoize.
If you can solve it this way, then you have a DP problem. Of course this forces you into the top down (aka recursive) approach. But in an interview, "easier to reason about" is all that matters.
Also the tradeoffs in section 5 has a mistake. Memory can and frequently does go either way. Top down can let you recognize which states you never need to think through. But a bottom up (aka iterative) approach can let you discard memory after finishing an iteration. The memory savings from that can be considerable.
You can spend a lot of time getting very good at them, or you can just use memorization/rsolve just like you can just use maple or evaluate them numerically for integrals.
For clarity, perhaps one can include a "proof of correctness" of the algorithm in the comments.
Take a look at the wikipedia page for computing Levenshtein distance: https://en.wikipedia.org/wiki/Levenshtein_distance#Computing...
The recursive version needs barely any explanation. But ask me to carry it out by hand and I'm sure I'll pretty quickly get lost. The iterative version needs a lot more explanation for why it is the way it is, but I also think I could carry it out on paper quite easily.
If a recursive solution works on a small input, it will work on a big input. If you missed a base case, you'll see it immediately because trivial (literally!) input will make your solution fail to terminate.
In production, the main problem with recursion is stack size limits (or more generally memory limits) if you can't/don't use tail-call elimination.
What’s complicated about a recursion?
> If you see problems, its because something is modifying it between runs, but that wasn't a fault of the iterative strategy, it was the fault of a bad programmer.
> Conversely, you must always make sure the stopping condition and all base cases are met during recursion.
You seem to be applying a double standard here.
> Forget one corner base case and you got a rare production bug.
Base cases are usually much easier to reason about.
How about unknown potential stack size?
How about factoring a large number with recursion?
Everything recursive can be transformed to iterative and yea sometimes it’s not as sexy but neither is a helmet
https://www.reddit.com/r/programming/comments/3dnsh1/nasas_t...
They also proscribe unbounded iterations (point 2). In any case, NASA’s guidelines for mission-critical code are not necessarily good guidelines for general software engineering, given the constraints involved.
It’s also worth noting that recursive solutions are probably more amenable to static analysis and automated theorem proving.
> How about unknown potential stack size?
If stack size is a problem, try an iterative solution.
> How about factoring a large number with recursion?
Go with iteration.
You keep editing your answer to add more cases where iteration is the way to go. I’m not disputing there are use cases where iteration is appropriate.
More like they're using an old Fortran 77 environment which doesn't support recursive functions.
"Give all loops a fixed upper bound. It must be trivially possible for a checking tool to prove statically that the loop cannot exceed a preset upper bound on the number of iterations. If a tool cannot prove the loop bound statically, the rule is considered violated."
https://pdfs.semanticscholar.org/ad40/26510beb1a309902704583...
This isn't just a NASA thing. Pretty much any embedded coding standard says the same thing. The JSF C++ standard, and MISRA-C I know both do as well, just off the top of my head.
NASA's rules, the ones being referenced above, are designed for safety. They require code to be easy to statically analyze and to have absolutely predictable behavior.
Also to be avoided: memory allocation, unbounded loops, function pointers, preprocessor macros.
https://en.wikipedia.org/wiki/The_Power_of_10:_Rules_for_Dev...
This is in addition to not using recursive functions being pretty standard in anything embedded. Early computers and embedded systems had very limited stack space or had calling conventions that made recursion impossible.
The rationale they used for these rules was written down. It has nothing to do with Fortran. I've offered links that you can read. You're making more assumptions. If there's C-to-Fortran calling at all, then recursion presents zero extra difficulty. Once you can make any function call, you can make all function calls.
> This is in addition to not using recursive functions being pretty standard in anything embedded.
It's true that for small embedded devices, recursion is not used often. It's also true that function pointers and heap allocations and unbounded loops are generally avoided too. Though, often main() in an embed is a white(true){} loop. I wouldn't be surprised to see that at NASA.
One could argue that all of these 10 NASA rules represent some standard practice in embedded code and/or some degree of common sense. They're not claiming to be new or non-standard or unintuitive or innovative; they simply wrote down what people agreed are best practices.
That's a really good trade-off for them but it does not necessarily help readability.
You shouldn't have to know about the implementation when writing portable code. If you introduce recursion, you now need to worry about implementation since the machine max stack size is now an issue and you've broken the abstraction. And what exactly did you gain that outweigh's the cons?
You started with the assertion iterative implementations were more intuitive and easier to read so this is a bit of goalpoast-moving. Write an iterative pseudocode DFS or quicksort. How 'intuitive' does that look?
" I'm willing to bet most people if shown 10 recursive and 10 iterative solutions to the same problems would admit the iterative approach is more intuitive. "
Now you are at NASA sending probes to asteroid Weasel 39812.
> What’s complicated about a recursion?
Especially as iteration is just a special case of recursion :)
If you are working on any kind of tree structure, graph, parse tree, etc., recursion can be really beautiful and clear.
My theory: folks like iteration because 90% of the "for" loops they write are really just "foreach".
I didn't understand this comment. What do you mean by "for vs foreach."? Can you elaborate?
So, intuitive is not so valuable unless you get correctness out of it.
If you need to return values for processing each child, and integrate them at the parent, then your solution gets tougher to reason about, as there's an ordering constraint and a dependency.
Recursion doesn't come up super often in most domains, but it's not rare. E.g. doing anything non-trivial with the DOM in a web front end, parsing an XML or JSON document, etc.
Having both tools in your toolbox and knowing when to use each is part and parcel of developing yourself as a craftsman or craftswomen programmer.
In addition, being able to know when to use memoing in producing your solution is another tool to be put in your toolbox.
Yes, every recursive function has an iterative solution, but the iterative solution can be far more complex. The best example of this is that lovely little function - Ackermann-Peter function. The recursive version is just a few lines long. The iterative version is quite a few pages long.
There are specific schemas in which the recursive form should be rewritten as an iterative solution. You can find these detailed in such old gems of books like "Algorithms + Data Structures = Programs".
DP is fancy caching, but you have to think about the space of the solution to do it right. It's not just easier to cache the results and use the recursive solution, but the code is often smaller and clearer too.
I spent some time understanding and coding up edit distance between trees DP-style, which is a fair bit trickier than edit distance between strings. At the end of the whole project, I wished I had simply memoized.
But I noticed that 2/3 of them ended up with recursive solutions. Meanwhile, I spend less than 1% of my real professional programming time writing recursive code, and it's a bit silly that so much focus is on such relatively obscure technique.
They can show that the person is prepared (they studied), generally knowledgable (they remember obscure stuff), or just clever (they come up with interesting approaches to the problem).
I'm not surprised you see both excessively simple (make sure they aren't ridiculously unqualified) and excessively obscure problems, since the first one essentially tests your reflexes and the second one tries to determine if you learned your job "by rote"
Unless you work for a major tech company where optimizing the false positive rate is your primary concern, using these problems is counterproductive.
But I think the simpler explanation is that these interviewers mostly had picked "cool" recursion problems.
I did get the job, and seeing $BigCompany's hiring process from the inside didn't contradict this.
At this point, balloons and confetti fall from the ceiling as Donald Knuth jumps out from under the table to hand the candidate an award for being the first known example of a candidate using "dynamic programming" correctly in a sentence.
Rather, they're picky because they (think they) need to be.
Note that I'm not judging whether they are right or not.
Google-esque companies figure "Let's just ask these hard puzzles to filter by IQ, everything practical (e.g. databases) can be learned"
However, some companies tend not to see these specialized puzzles as an IQ test, but rather a memorization-based learned skill (learn these 10 algorithms and their performance metrics). To them, asking questions that represent day-to-day job challenges is a better predictor.
However, they're a reality for many interview loops, so it's better to be prepared.
Btw, what are some things that your company tests for, if you don't mind sharing?
In an eng. interview you want to maximize information divided by time, i.e. you want to learn as much as possible about whether the candidate would be a good fit for the company and spend as little time as possible doing so (because you have other things to do -- such as interviewing more candidates).
In my experience these kind of interview questions have a very poor information by time ratio. They are poor on information because they may give you an idea how well the candidate can do on puzzle questions but not so much how the candidate would do on actual real-world assignments. And they are especially poor on the denominator (time) because you are probably going to spend at least 1h with the candidate before you get past the obvious stuff.
Also I guess about 70% of (pre-qualified) candidates would outright fail the question, so if you let this influence your hiring decision, given that the question is really quite "puzzly", you're inevitably going to miss out on a lot of talent (the kind that does well on actual work assignments).
This is probably right. Companies still use these questions, though, because they do a good job failing candidates who are not technical enough for the role.
What you're essentially doing is filtering out bad candidates and selecting from good ones based on luck.
I think our process is guided far more by tradition than deliberate optimization for anything in particular. :)
Most companies in bay area have 3-4 whiteboard interview rounds and I have experienced at least 1 interview, at every place I interviewed(FANG and other top bay area tech companies), where the interviewer wasted enough time either explaining the problem.
As an interviewer, it is really important to keep the time aspect in mind and choose a problem which could be easily explained. The problem itself could be hard, but story based problems waste candidate's time and have little value in assessing the ability of the candidate.
PS: I interviewed at one of the tech companies(the one you all know and I won't name), and in one of the technical rounds, it took the interviewer 20 minutes explaining the problem. The problem basically boiled down to finding largest number at any time in a given sequence without sorting the array. The problem had a background story of some cell towers where each tower had a strength and blah blah. The interviewer was also had communication issues.
That tells me a lot of concerning things about the organization. If you're considering that it's "wasted time." You're missing out on a lot of important information there.
At that point though, what I'm really interested in, and what I think tells me a ton of valuable information about the candidate, is how capably they are then able to turn the algorithm into actual code. With many folks you can basically tell them the entire recursive steps that are necessary and they still can't translate this into workable code. "How fast can you turn algorithm into code" is one of the critical skills for all developers, and these kinds of problems give me good insight into that skill.
Crucially, I don't think it's important to have critical insight into the problem and come up with a solution unaided. We don't work alone - if we can come up with a solution together, and the candidate can be trusted to implement the solution, it's what we need.
> "How fast can you turn algorithm into code" is one of the critical skills of all developers.
I don't understand this industry anymore. If I have anything to say about software is that solving the right problems is the main skill in an Engineer. Then, figuring out an algorithm is the hard part of solving any problem, turning it into code is usually never as hard (except for technical nuances) and especially, not how quickly it becomes code. Not sure how someone can value "how fast can you turn algorithm into code" over "understanding/solving the right problem".
I agree with you quite a bit, but to me it looks like there's some assumption buried in there that the only reason to ask interview questions is to evaluate individual performance on heads-down coding problems, which is not necessarily representative of a real work environment.
The information I look for when interviewing includes: How do people behave when asked questions they don't know? How will a candidate act in meetings? How curious is the candidate when faced with a tough question? Do they verbalize their thought process? Do they start making things up and/or try to appear like they know the answer when they don't? Do they gravitate towards certain kinds of problems? Do they ask questions or try to tough it out alone?
I've never asked a DP problem in an interview, but I do like to try to get an idea of the candidate's limits and boundaries, so I try to ramp up the difficulty until we hit questions they have trouble with. (I do warn them in advance.) I don't really want to hear correct answers to simple questions, I want to see how far they can get before they get stuck. I also want to hire people smarter than me.
If you only look for coding efficiency in a candidate, then yes, your information over time ratio might be low. (And it might be surprisingly low for all your questions.) But if you expand the kinds of information you collect to include social factors, behavior, knowledge limits, and more, then it's really not that bad.
Next time on interview just for fun try to ace all technical questions but contradict some interviewer's notions held in high regard (those could be usually inferred pretty quickly during initial conversation); I am 99% sure you won't get the job. Then on another one make yourself just average tech performer but amplify agreeability with the interviewer's ideas. What would you guess would give you (much) better success ratio?
When I got a job at Google (in a previous life), two of the questions in my interview loop were ones that I had seen in previous interviews. I kept my mouth shut about that and faked brilliance in the moment. That is, I pretended to be stumped for a second, then I created a narrative where I had a sequence of 2 or 3 "Ah-ha!" moments where I figured out how to refine my solution.
I cued off the interviewer, waiting until they seemed just about to blurt out a hint, when I raised my hand and said, "WAIT! Maaaybe.... I can use a BFS instead of a DFS here and label the cells!" Then the interviewer would usually smile and nod in satisfaction.
Finally, I "stumbled on" the "right answer" and slammed out the code that I had pretty much memorized up to that point.
Make a stupid game, I'll play the stupid game, and have fun doing it.
For the record, I kicked ass at Google (getting promoted twice) before moving on to greener pastures.
Doesn't say much for the usefulness of such an interviewing paradigm but that's a whole other conversation.
Step 2. ur sub problems better overlap
Step 3. time to table dat dag
Step 4. solve ur problems and build ur table graph the way a dag would : to-po-lo-gi-cal-ly
and the interviewer said "STOP! Stop, every time someone says that, they end up flopping and never getting anywhere. Don't go down that path, I'm telling you."
I think it had more to do with the interviewer being a poor interviewer, however.
Unfortunately my DP was really bad so I knew right then I'm going to flop. And flop I did.
For me the two weakest points are DP, and coming up with the right O() estimate for an algorithm that I just created on the whiteboard, and am looking at it for the first time in my life. Would love advice on how to get good at both.
For Big O notation? Just think about how many times you're iterating through things (in the worst possible case).
e.g. Got two nested for loops each going to N.. we're going to loop N on the outer loop, so and each iteration of the inner loop we go through N times? that's N x N so O(N^2).. (easy example obviously).
Interviewer had already decided that somehow the crazy rules I related to him about the industry I was coming from were somehow personally my fault to he had fun letting me twist in the wind.
Personally, I think that given how small the industry is, one of the goals of the interview process should be not to make an enemy of the candidate. Candidates have friends, and sometimes candidates come back in a few years after they've gotten more experience or you're looking for different skills. None of this will matter to Google until they find themselves in a MS-style hiring crisis in another five years when they aren't cool anymore.
Did they say that they don't even want to listen to O(n^2) solution?
I didn't get further along in that process because of that stupidity and have never even considered them as a place to work since, and I am an SRE/PE these days.
If the naive solution is O(n!) then describing an O(n^2) solution is perfectly acceptable.
For example, here is how you can use Prolog to solve the task from the article. The following Prolog predicate is true iff a given runway (represented as a list of "t" and "f" elements) is safe with a given speed:
:- use_module(library(clpfd)).
safe_runway(0, [t|_]).
safe_runway(Speed0, Rs) :-
Speed0 #> 0,
Rs = [t|_],
( Speed = Speed0
; Speed #= Speed0 - 1
; Speed #= Speed0 + 1
),
length(Prefix, Speed),
append(Prefix, Rest, Rs),
safe_runway(Speed, Rest).
Sample query and answer: ?- safe_runway(4, [t,f,t,t,t,f,t,t,f,t,t]).
true .
One interesting aspect of this solution is that we can generalize this query, and also use the same program to answer the question: Which speeds are actually safe for a given runway?For example:
?- safe_runway(Speed, [t,f,t,t,t,f,t,t,f,t,t]).
Speed = 0 ;
Speed = 2 ;
etc.
To enable memoization for this task, you only have to use your Prolog system's tabling mechanism. For example, in SWI-Prolog, you turn this into a dynamic programming solution by adding the directive :- table safe_runway/2.
This makes the Prolog engine automatically remember and recall solutions it has already computed.> Dynamic Programming – 7 Steps to Solve any DP Interview Problem
Here I see "any"!!!
Dynamic programming is a huge field from work of R. Bellman, G. Nemhauser, R. Rockafellar, R. Wetts, D. Bertsekas, E. Dynkin, W. Fleming, S. Shreve, and more.
E.g., there is, with TeX markup,
Stuart E.\ Dreyfus and Averill M.\ Law, {\it The Art and Theory of Dynamic Programming,\/} ISBN 0-12-221860-4, Academic Press, New York, 1977.\ \
Dimitri P.\ Bertsekas, {\it Dynamic Programming: Deterministic and Stochastic Models,\/} ISBN 0-13-221581-0, Prentice-Hall, Englewood Cliffs, NJ, 1987.\ \
George L.\ Nemhauser, {\it Dynamic Programming,\/} ISBN 0-471-63150-7, John Wiley and Sons, New York, 1966.\ \
E.\ B.\ Dynkin and A.\ A.\ Yushkevich, {\it Controlled Markov Processes,\/} ISBN 0-387-90387-9, Springer-Verlag, Berlin, 1979.\ \
Dimitri P.\ Bertsekas and Steven E.\ Shreve, {\it Stochastic Optimal Control: The Discrete Time Case,\/} ISBN 0-12-093260-1, Academic Press, New York, 1978.\ \
Wendell H.\ Fleming and Raymond W.\ Rishel, {\it Deterministic and Stochastic Optimal Control,\/} ISBN 0-387-90155-8, Springer-Verlag, Berlin, 1979.\ \
some of my work, etc.
Dynamic programming has been and is a major interest of the Department of Operations Research and Financial Engineering (ORFE) at Princeton.
Uh, "any" seems a bit optimistic!
Now, if I were doing an interview asking about dynamic programming, how about scenario aggregation, multi-variate spline approximations, neural net approximations, certainty equivalence with the Gaussian, non-inferior sets, measurable selection, etc.!!!!
One prof of mine wanted me to think about the role of potentials!
That is, unless you're being hazed, the sort of questions to show up in an interview might be at the shallow end of the pool.
Only superman will do, that is the only thing we know for sure.
It's a toy problem, not something you'll ever need to solve in real life. Maybe if you squint hard enough it's close to pathfinding algorithms, but be serious. I hate questions that aren't remotely relatable to something the candidate might experience. I get that interviews are short so you need tiny problems, but making them somewhat relevant will make comprehending the problem that much easier and give plenty of time for working on a solution.
There's also not much depth to it. Either they can get a naive solution, get the DP solution, or just can't solve it. Maybe I'm just not creative enough but the only follow up I can think of is the typical 'how to test' and this isn't even a good question for that. For me as an interviewer, it is better to start with an easy problem, and then later on additional complexity. For example dealing with concurrency, how to generalize the solution for other cases, etc. These follow ups don't even usually need full code written out so you can get much deeper since it's faster. Whereas if you start from a hard/tricky problem and have to keep explaining it and hinting at how to solve it, both candidate and interviewer feel bad and you haven't learned much.
Not that this is a particularly hard problem, it will fit within an interview slot if they are on top of things. But it's similar enough to questions I hate asking/getting (e.g. min of maxes of sliding windows) that I would definitely never ask it.
I found out the hard way in a recent Google CodeJam problem[1] that even that wasn't enough and sometimes you really do need the iterative solution to not time out. (I still believe that the limits for python for this problem was set too low since even the iterative solution required hand optimizing of the memory usage to pass but the equivalent C or C++ solution didn't require any tweaks)
[1] https://codejam.withgoogle.com/2018/challenges/0000000000007...
struct BinTree {
long value;
BinTree *left;
BinTree *right;
};
long long RecursiveDFSSum(BinTree *node) {
if (NULL == node) {
return 0;
}
return (long long)value + RecursiveDFSSum(node->left) + RecursiveDFSSum(node->right);
}
long long IterativeDFSSum(BinTree *tree) {
std::vector<BinTree *> custom_stack;
custom_stack.push_back(tree);
long long value = 0;
while (!custom_stack.empty()) {
BinTree *node = *custom_stack.rbegin();
custom_stack.pop_back();
if (NULL != node) {
value += node->value;
custom_stack.push_back(node->left);
custom_stack.push_back(node->right);
}
}
return value;
}
Did not check this actually compiles etc. but you get the point. Both ways will give you the same solution in the same way, time complexity, space complexity etc. but the second one is not bound by max call stack size (only by max heap size). Additionally, the second one is slightly more space efficient, since the recursive solution requires saving an entire call frame into the stack (e.g. stack pointer, return address) whereas the iterative solution just stores one pointer per stack item.If you were coding a DP problem, then custom_stack might have a fixed size you can pre-allocate, and it might also be 2 or 3-dimensional.
For some image-based recursion, your backtracking doesn’t even need to store real pointers in the stack frame. For example when I’ve written a flood fill, I can store the return pointer as a one pixel offset in as little as 2 or 3 bits, depending on whether I include diagonal pixels (4-surround vs 8-surround).
Python memory management is automatic though, discussing stack vs heap doesn't make sense in the context of Python,well for CPython at least. I'm not sure about other Python implementations.
I'm not sure I know what you mean about stack vs heap not making sense because of Python's memory manager. Will you elaborate?
The primary issue is that the default stack limit in Python is too small for some applications of recursion, which the comment before mine illustrates. This is true not just in Python, but any language, since the stack size is generally a function of the process or OS, not a limit of the language. Heap allocated stacks are a reasonable thing to do in any language.
You're right you can solve that in Python by using a list. Python's memory management doesn't really affect one's ability to do so, right?
A secondary issue is that native recursion sometimes uses more memory than a manually heap-allocated "stack". If I make my own stack, I have complete control and complete understand of what's in memory and how much I use. With the native stack, it can be very opaque, and it's easy to chew up the already-too-small stack very quickly by accidentally having a large stack frame.
In Python everything is an object. Python gives you a reference to that object when you create it. There is no way to tell Python(CPython anyway) in which memory space you would it to create that object.
Ah right, that's because all objects are heap-allocated.
You choose heap by using an object for the stack, and rewriting your recursion to use (superficially) iterative code.
You can choose stack allocation instead by using regular recursion: native function calls with local variables.
What you bring up is an interesting issue that can make recursion harder to understand in Python. Having local objects in the stack frame can cause both stack and heap allocation - pointers for the objects on the stack, and the object contents on the heap. Or, you might have global objects that aren't local to the recursive function call or the stack, in which case it's important to understand you're sharing data across function calls.
Generally speaking, you probably don't want individual heap allocations in a recursive function, so it's best not to have local objects. At least performance-wise.
You can choose stack allocation instead by using regular recursion: native function calls with local variables."
I'm not following you.
I believe these would both result in the same thing in Python. Python gives you a reference to an object. That object is stored in a private heap "somewhere." That reference to the object that Python gave you is stored on the stack. The object that it points to lives in the heap. This should be the same for both of your examples. I'm not sure what you mean by "native function calls." I am not familiar this this term.
What we’re talking about is the difference between calling a function recursively (a function that calls itself) and instead simulating recursion using a data structure posing as a stack and an iterative function that doesn’t call itself but instead pushes and pops into your fake stack data structure.
You can either use the system’s built-in stack (by calling functions), or create your own fake stack (by pushing/popping, writing/reading an array, etc.).
Using sys.setrecursionlimit() as mentioned at the very top of this thread only affects the system stack. By “native function calls”, I just mean regular function calls. These are subject to the system’s stack limit.
When you allocate an object and use it as a fake stack to replace the system stack, the size of the object is not subject to the system’s stack limit (which is small — on PCs often a megabyte or two), it’s only limited by the available size of the heap (which is normally large relative to the system stack limit, often gigabytes).
When you make your own fake stack and use an iterative function, you can achieve a much greater recursion depth because your fake stack size is on the heap and not actually in the system stack.
Does that make more sense? The two cases are very different in Python, and using a fake heap-allocated stack, i.e. a Python object, is super useful.
<h1>Error establishing a database connection</h1> if (position + adjustedSpeed in memo and
adjustedSpeed in memo[position + adjustedSpeed] and
adjustedSpeed in memo[position + adjustedSpeed]):
The middle line is not needed.But essentially you see that the equation is S^2 - S - 2L < 0
from that, you can solve that the roots of the function are: (1) 1/2 + sqrt(2L) and (2) 1/2 - sqrt(2L)
That means that (S-1/2-sqrt(2L)) * (S-1/2+sqrt(2L)) < 0
The second term is always positive, which means that we need to make the first term negative in order for the inequality to hold.
=> S < 1/2 + sqrt(2L) which leads to O(sqrt(L)) when you let L approach infinity.
Does this make sense?
1. existing practices 2. each other
It's a hard problem that requires people to approach it seriously. And it is only getting worse with a high growth in number of people getting into tech.
It's interesting to try to solve it.