๐
Date: Feb 12, 2026
๐ฅ Topic: Difference between Subarray & Subsequence
๐ง Are they the same?
No! This is the most common confusion in interviews.
| Feature | Subarray | Subsequence |
|---|---|---|
| Definition | Contiguous part of array. | Derived by deleting elements, Order matters. |
| Continuity | Must be continuous. | Can be non-continuous. |
| Total Count | N * (N+1) / 2 |
2^N (Power Set) |
๐ง Visual Example
Let Array = [1, 2, 3, 4]
✅ Valid Subarrays
- [1, 2] (Connected)
- [2, 3, 4] (Connected)
- [3] (Single element is also contiguous)
❌ Invalid Subarray
- [1, 3] (Skipped 2, so NOT a subarray)
✅ Valid Subsequences
- [1, 2]
- [1, 3] (Valid! We just deleted 2)
- [1, 2, 4] (Valid! We deleted 3)
๐ป Day 42 Code: Printing All Subarrays
Printing subsequences requires Recursion (coming soon). Printing subarrays just needs 3 loops.
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4};
int n = 4;
cout << "All Subarrays:" << endl;
for(int start=0; start<n; start++) {
for(int end=start; end<n; end++) {
// Print elements between start and end
cout << "[ ";
for(int k=start; k<=end; k++) {
cout << arr[k] << " ";
}
cout << "]" << endl;
}
}
return 0;
}
๐ญ Thoughts
Subarray = Slices of bread (Connected).
Subsequence = Picking toppings (Can skip, but order stays same).
Clear concept helps in solving Hard DP problems later.
No comments:
Post a Comment