A quick way to understand the difference is by looking at the program to compute Fibonacci numbers.
One way is just using recursion that runs in O(fib(n)) time. Like, the really really slow way.
Another way would be to use memorization. Just use the same recursive way but everytime that you're about to compute the answer, first check if the answer is in a cache that you have prepared. If yes, use that. If not, recurse. And when you get an answer, put it in the cache. That's memoization. It will run in O(n) time but also use O(n) space for the cache.
The algorithm that you probably know uses dynamic programming to run in O(n) time but constant space. That's DP.
You could also imagine using DP to compute the fewest number of coins to make x cents. If your biggest coin is 25 cents, you only ever need to know the answers for x-24 through x in order to compute the answer for x+1. This lets you solve the problem with linear time and constant storage, like with Fibonacci.
Edit: I meant memoization everywhere. Spell check messed it up.
Fib(n) being used for DP has always been funny example to me. The naive recursive method is worse than the DP method sure... but if you calculate it the way a *human would on paper* it's the non-recursive O(n) time O(1) space solution.
It's even funnier for me because analytic solutions exist. We expect people to have complete mastery of courses in in discrete math and algorithms but then pretend they don't know how to use a generating series for a linear recurrence.
To be honest I wouldn't expect anybody who isn't a specialist to be able to do that off the top of their head. The last time I heard the words "a generating series for a linear recurrence" was in college 10 years ago, and it hasn't been relevant to my software eng career since, including in interviews. I've had to dust off other parts of the math toolkit occasionally, but it's hard to justify analytical solutions in an environment where requirements are expected to change after your solution is live.
Memoization means using a memo to do a task. Memorization means committing something to memory, which is a thing that humans do, not computers. You don't say the computer is memorizing something because you stored it in RAM. They're spelled differently because they're based on two different roots.
Another way would be to use memorization. Just use the same recursive way but everytime that you're about to compute the answer, first check if the answer is in a cache that you have prepared. If yes, use that. If not, recurse. And when you get an answer, put it in the cache. That's memoization. It will run in O(n) time but also use O(n) space for the cache.
Doesn't this ignore cache update and lookup times? I guess O(n_max) (n->infinity makes that hard) would have plain array indexed with n, but otherwise you end with at least multiples of n. And there is a loop or tail recursion that has O(n) time and constant memory use anyway. Point of memoization is that after first time, its cache fetch complexity rather than original complexity, O(1) if we have enough memory and trivial index, and you can do that with the loop and tail recursion as well.
the memoized recursive function is still dynamic programming; it's just top-down whereas the obvious loop implementation (that everyone writes before they even learned what recursion is) is the so-called "bottom up" approach which just shows more how "dynamic programming" is such a stupid nothing burger name
Fun fact: back in the day, programming meant optimization. Richard Bellman, who inflicted DP upon us all, was friends with George Dantzig, who is credited with inventing linear programming. When trying to name his new method, Bellman chose dynamic programming officially because “dynamic” referred to the optimization-over-time aspect of DP—but actually because he thought “dynamic” sounded neat and wanted to one-up his friend.
(Computer science and software industry history is full of stuff like this. I love this job.)
I heard a diffrent story about the name being a result of financial incentives, Bellman didn't one to name it something "mathematical" because it wouldn't have received the money it did with "Dynamic programming".
The story, as quoted on the Wikipedia page, starts with:
The 1950s were not good years for mathematical research. We had a very interesting gentleman in Washington named Wilson. He was Secretary of Defense, and he actually had a pathological fear and hatred of the word "research". I'm not using the term lightly; I'm using it precisely. His face would suffuse, he would turn red, and he would get violent if people used the term research in his presence. You can imagine how he felt, then, about the term mathematical.
Where I work, some TPM was asked why a certain product was named something seemingly random. He said, and I quote, “we’re not allowed to discuss that”. 😂
I was once assured that a bug-tracking system being named "Hydra" was purely coincidental and not, in fact, a reference to the Lernaean Hydra infamous for growing two new heads every time one was cut off
Thankfully, the company had a naming scheme that used ancient Greek mythology, so yeah, it was the Lernaean Hydra, but they denied it being a commentary on the nature of bugs
Programming meant the same as it does today. You can program a machine to do something by filling in a table. Dynamic programming is dynamic, as it fills the table at runtime.
Somewhat related, but not really: In ABAP language, dynamic programming has a different meaning.
It describes all the techniques that use generic types, pointers and casting from type to type as well as using string variables to pass a function to be called, a where clause to a select statement or type of the variable to be created.
Some would call this mechanism a reflection, but it is what it is.
Not only is “dynamic programming“ a terrible name, but it’s also impossible to say “memoize” without sounding like you’re saying “memorize” with a speech impediment.
a lot of design patterns sound scary with all the big words, but they boil down to stuff like "don't put two unrelated things in the same inheritance tree, dumbass". like just don't be stupid and you're probably using them unwittingly
So many programming principles are just reminding people not to put the goddamn oranges in the same bag as the apples, but they don't want to even look at the fruit
yeah like the facade design pattern is incredibly obvious and is partially already covered by "don't repeat yourself". Like, why would you want to write every step of a 12 step process multiple times when you could just write one function that does every step and then just call that? Sometimes these things beget explaining again, but it's certainly something
People often misunderstand the idea of design patterns. Instead of 'here is a pattern you can use', think of them as 'we found a pattern that lots of people already use (because it makes sense), and we gave it a name so everyone can talk about it easier'
yeah that makes sense. I've really only been exposed to them mostly in an academic environment so it always felt like the former to me (I never actually read the book either)
All these design patterns are nice and all until you are on a cheap microcontroller with 8k of flash and, if lucky, 1k of RAM and you begin to think about using bare assembler instead of C. ;)
A lot of the design patterns come from the lack of certain features in the language.
In the OOP Smalltalk language many of those patterns are a waste of time. Because they can be replaced with a simple Closure or Lambda. Smalltalk was based on Lisp. Java and C++ did not have that at the start. So we have visitor-pattern, iterator-pattern, etc.
yeah that too, i was specifically talking about the bridge design pattern, which i really feel like is what most people would do even without being taught it.
It's like the Art of War. It has basic things like "the army needs food" in it. When a field is new, someone has to write down and name the obvious things so everyone can then build on a shared understanding of the basics.
I have had similar problem in a different field once; chatting to someone who's an expert in economics and knows a lot of fancy terms for statistical analyses, while I knew hardly any as a student in maths.
Turns out, they have a dozen terms to describe different ways to use basic-ass linear regression to test if somethings' statistically significantly different.
No, it’s worse than that. Can I share a little secret with you? I’m a software engineer with 8 years of intermittent experience. If that sounds weird, it’s because it is.
I took an online class for DSA and got some things, but really started falling apart at DP. This was a year ago, I remember nothing. Everyone who said that you have to review chapters is right, but I stopped doing it because I was lazy, I spent all my life studying and waiting for comfort, well I got it and now there’s absolutely NO carrot to follow anymore. Senior SWE is a contender, but I’m so unimpressive in my work, consideration is an ever distant prospect.
And the worst part? Nobody else is calling me out on it! I vibe code 100 percent of what I commit. And yeah, I proof read it all, talk through alternatives, sic coding agents on it for review, but still - somehow - end up missing things. How I haven’t caused an incident yet is beyond me.
And so here I am, a mid 30s mid level engineer who has no idea how any of this shit is gonna pan out. So I read that documentation here and make my changes there knowing full well that the other shoe will drop someday, maybe today, maybe next year.
So tell me I don’t understand shit and I’ll tell you you’re absolutely right. Maybe someday I will.
You may be the kind of person who is way too anxious and strict with themselves.
Let's be completely honest with yourself - would you say your colleagues all understand everything? Like the amount of senior devs I actually look up to over my career is a single digit number, even though I have worked at plenty places.
Most devs suck, that's the average/mainline. Compare yourself to that - you may also suck a bit, but it's entirely possible that you suck way less than your average college and you could just go for that senior position.
We are in crazy times, but you do have a stable job and it usually means that you are in a good position in life. It's also entirely possible that you are not that into IT, and just do it as a thing that puts bread on that table, and that's completely fine! Do your thing, go for the senior position if it's coming with higher salary, but only if it's not that much more stress for you, and just do your hobby or spend time with your family/friends. It's all good, don't be too strict with yourself.
Thanks for letting me dump all that man, I appreciate the feedback too. I’m frequently told that I’m my own worst critic. Progression happens 1% at a time.
My colleagues may not understand everything, but they kick some serious ass. I’ve got one guy on my team who’s an actual 50x developer, I’ve never seen anything like it before, so I learn as much from him as I can.
True that most developers suck, I was on an interview panel a while back and learned first hand how rare it is to find someone who can code an HTTP request on the spot. I do take a little bit of solace in that.
I was into the profession at first, was one of the last viable creative professions out there, LLMs have turned it into paper pushing. That being said I’m grateful every day I can pay off my mortgage.
I think I just needed to unload a little bit. Thanks again for caring!
It is, but memoisation has the specific meaning of caching the result of an (expensive) pure function, like factorisation. To me the difference is that a memoised result can never be wrong and you only have to consider the memory impact, whereas caching implies that the result may become out of date if you hold it for too long, e.g. get the comments on this reddit post.
My previous job had a very nice memoization decorator that you could apply to arbitrary functions in python. Of course, it evolved to be a generic caching mechanism and had settings for (1) expiring memoized results after a timeout, (2) memoizing based on only some of the function inputs (e.g., memoize based on the parameters and not the database handle that you passed in), (3) limiting the total size of memoized objects, &c.
Invalidation of another entry, updating counters, in a distr system eg for CDN it means transferring data to the CDN, and potentially needing to invalidate it.
I shit you not, I’m 10 years into my professional career as a software engineer, and to this day I have no idea how to write a DP algorithm. My job has never asked me to. Only LeetCode asks me to and I skip those interviews lol.
I’ve used dictionaries/hash maps as a cache and front end memoized data hundreds of times. It’s just the combination of recursion + memoization that I’ve almost never used.
Well, the problem is that I have a bunch of timeseries data and I need to find the first data point before a specific moment in time. Are you sure that I need a HashMap?
Sure. That's the underlying structure in both C++'s std::map and Java's TreeMap. They're super useful for dealing with timeseries data--especially when you have data coming from sources that may not give you the data already ordered for you or when you need to combine data from a bunch of sources.
Dynamic programming can be done bottom up as well as top down and personally I find that makes way more sense.
Who would write a recursive function to calculate Fibonacci numbers when you can just start at the lowest two Fibonacci numbers and calculate them in sequence and obviously do each one once.
Scene with merge sort Vs quicksort. Don't mess around with recursively splitting the array, just split it into arrays of length 1 and then merge them back together in a sorted way.
Would probably been better if it was focused on the Optimal Substructure property of the underlying problem and noting that makes it amenable to memoization.
39
u/Illustrious-Ebb8815 1d ago edited 1d ago
A quick way to understand the difference is by looking at the program to compute Fibonacci numbers.
One way is just using recursion that runs in O(fib(n)) time. Like, the really really slow way.
Another way would be to use memorization. Just use the same recursive way but everytime that you're about to compute the answer, first check if the answer is in a cache that you have prepared. If yes, use that. If not, recurse. And when you get an answer, put it in the cache. That's memoization. It will run in O(n) time but also use O(n) space for the cache.
The algorithm that you probably know uses dynamic programming to run in O(n) time but constant space. That's DP.
You could also imagine using DP to compute the fewest number of coins to make x cents. If your biggest coin is 25 cents, you only ever need to know the answers for x-24 through x in order to compute the answer for x+1. This lets you solve the problem with linear time and constant storage, like with Fibonacci.
Edit: I meant memoization everywhere. Spell check messed it up.
1.3k
u/TheFirstDogSix 1d ago
Fun fact: back in the day, programming meant optimization. Richard Bellman, who inflicted DP upon us all, was friends with George Dantzig, who is credited with inventing linear programming. When trying to name his new method, Bellman chose dynamic programming officially because “dynamic” referred to the optimization-over-time aspect of DP—but actually because he thought “dynamic” sounded neat and wanted to one-up his friend.
(Computer science and software industry history is full of stuff like this. I love this job.)
840
u/ShakaUVM 1d ago
Yeah one of the worst names ever
When I first heard it I thought it had something to do with dynamic arrays
319
u/NomaTyx 1d ago
a lot of design patterns sound scary with all the big words, but they boil down to stuff like "don't put two unrelated things in the same inheritance tree, dumbass". like just don't be stupid and you're probably using them unwittingly
40
u/lucklesspedestrian 1d ago
I mean what else are you supposed to do, just run the brute force recursion?
150
u/nicuramar 1d ago
Memoization is not exactly the same as DP.
22
u/Necessary-Meeting-28 1d ago
Me adding @cache on top of my recursive Python function.
48
u/Ok-Boysenberry-5090 1d ago
May all future generations be free from DP beyond knowing it exists
56
u/rahvan 1d ago
I shit you not, I’m 10 years into my professional career as a software engineer, and to this day I have no idea how to write a DP algorithm. My job has never asked me to. Only LeetCode asks me to and I skip those interviews lol.
8
u/GoldAcanthisitta7777 1d ago
spong bob
14
u/caiteha 1d ago
After many years of leetocding, it finally clipped. To me, It is just some storage + recursion -> later changing it to for loop to look better
4
u/scheimong 1d ago
Yeah easily the worst technical term ever invented in the entirety of compsci.
Although, there are some close competitors in non-English languages.
3
u/P-Jean 1d ago
Good olde reverse recursion
3
u/SignoreBanana 1d ago
Yeeeeup.
A while back I realized the solution to like 90% of DSA problems is insert sorting, bisecting, mapping, reducing, or some combination thereof.
2
u/parkway_parkway 1d ago
Dynamic programming can be done bottom up as well as top down and personally I find that makes way more sense.
Who would write a recursive function to calculate Fibonacci numbers when you can just start at the lowest two Fibonacci numbers and calculate them in sequence and obviously do each one once.
Scene with merge sort Vs quicksort. Don't mess around with recursively splitting the array, just split it into arrays of length 1 and then merge them back together in a sorted way.
Recursive functions are as tricksy as hobbitses.
2
u/Rough_Priority_9294 1d ago
I remember someone telling me that dynamic programming is like recursion + cache
3
u/Mephistophanes 1d ago
Well it's a funny story where täht name comes from, which you read from wiki
2
u/RyanCargan 1d ago
Everything is just a graph op of some kind if you squint hard enough.
EVERYTHING.
DP, greedy algos, cellular automata, matrix multiplication, RL...
1
u/Knaapje 1d ago
That's not dynamic programming, that's memoization.
1
u/justinleona 1d ago
Would probably been better if it was focused on the Optimal Substructure property of the underlying problem and noting that makes it amenable to memoization.
1
u/bythenumbers10 1d ago
And here I am thinking about LinAlg & optimization algorithm loops. Oops.
1
u/devilquak 1d ago
Now you’re gettin’ it. The universe is ordered chaos.
1
u/CoshgunC 1d ago
terrible naming.
at first I thought it meant value of variables can't be changed in static programming
1
u/ProgrammersPain123 1d ago
I thought dynamic programming was about rewriting executable memory?
1
u/klimmesil 1d ago
You still have to build it up instead of down (reverse the algorithm) and do cache aware blocking to make it efficient
1
u/ortmesh 1d ago
Seems very scary and sophisticated. Just means keep it in memory and reuse it
1
u/Gio_Cri 7h ago
i have known dydnamic programming for over a decade and i don't think i had a use for it yet lol.
only time i tried to use it the problem had my cache grow beyond reason and was actually solvable with a simple analytical formula lol
there are definetly uses for it but they are way rarer than courses would make you think lol
1
u/the_horse_gamer 2h ago
that's true for top down DP, but not for bottom up
1
u/Connect-Bowler-2917 1d ago
Thank you!