๐
Date: Feb 10, 2026
๐ฅ Topic: Array vs Vector & Dynamic Programming (DP) Basics
๐ Day 40 Milestone!
40 Days of Code. From "Hello World" to "Trapping Rainwater". Today, I am bridging the gap between basic storage (Arrays) and advanced logic (DP).
⚔️ The Battle: Array vs Vector
I used to be confused: "If Arrays are faster, why use Vectors?"
Here is the final comparison:
| Feature | Array (`int arr[10]`) | Vector (`vector<int> v`) |
|---|---|---|
| Size | Fixed (Static). Cannot change later. | Dynamic. Grows/Shrinks automatically. |
| Memory | Allocated on Stack (mostly). | Allocated on Heap. |
| Performance | Slightly Faster (No overhead). | Slightly Slower (Manages resizing). |
| Safety | No bounds checking (Risk of garbage values). | Safer (Throws errors if accessed wrongly). |
๐ง Introduction to Dynamic Programming (DP)
"Those who cannot remember the past are condemned to repeat it."
This quote sums up Dynamic Programming.
In Recursion, we often solve the same sub-problem again and again. DP is simply Optimization using Memory.
The Concept: Memoization
Instead of calculating the same thing twice, we calculate it once and store it in a Vector. Next time we need it, we just look it up.
๐ป Day 40 Code: Fibonacci using DP + Vector
Here is how I used a Vector to store previous Fibonacci numbers to calculate the next one instantly.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 10;
// Step 1: Create a DP Vector (Size n+1)
// We use Vector because 'n' can change!
vector<int> dp(n + 1);
// Step 2: Base Cases
dp[0] = 0;
dp[1] = 1;
// Step 3: Fill the Vector (Bottom-Up DP)
cout << "Generating Fibonacci Series using DP: " << endl;
cout << dp[0] << " " << dp[1] << " ";
for(int i = 2; i <= n; i++) {
// Formula: Current = Sum of previous two
dp[i] = dp[i-1] + dp[i-2];
cout << dp[i] << " ";
}
cout << endl << "10th Fibonacci Number: " << dp[n];
return 0;
}
๐ญ Thoughts
This was a simple example, but DP is huge. The fact that I can use a Vector (`dp` array) to optimize time complexity from O(2^n) to O(n) is mind-blowing.
Moving forward, I'll be exploring more STL containers like Lists and Maps!
No comments:
Post a Comment