■ Data Structures & Algorithms (DSA) – Quick Revision Guide
1. Arrays
Core Concepts:
- Sliding Window, Prefix Sum, Kadane’s Algorithm (Max Subarray)
- Two Pointers (e.g., 2-sum, 3-sum, Dutch National Flag)
Common Snippet (Kadane’s Algorithm):
int maxSubArray(vector<int>& nums) {
int maxSum = nums[0], curr = nums[0];
for(int i=1;i<nums.size();i++){
curr = max(nums[i], curr + nums[i]);
maxSum = max(maxSum, curr);
}
return maxSum;
}
2. Strings
Core Concepts:
- Hashing, Anagrams, Palindromes, KMP/Z Algorithm, Rabin-Karp
Common Snippet (Check Palindrome):
bool isPalindrome(string s) {
int l=0, r=s.size()-1;
while(l<r) {
if(s[l++]!=s[r--]) return false;
}
return true;
}
3. Graphs
Core Concepts:
- BFS, DFS, Topological Sort, Dijkstra, Union-Find
Common Snippet (BFS):
void bfs(int start, vector<vector<int>>& adj) {
vector<bool> vis(adj.size(), false);
queue<int> q; q.push(start); vis[start]=true;
while(!q.empty()) {
int u=q.front(); q.pop();
for(int v: adj[u]) {
if(!vis[v]) { vis[v]=true; q.push(v); }
}
}
}
4. Trees
- Traversals (Inorder, Preorder, Postorder, Level-order)
- LCA, Diameter, Balanced Tree Check
Common Snippet (Inorder Traversal):
void inorder(TreeNode* root) {
if(!root) return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
5. Dynamic Programming (DP)
Patterns:
- 1D DP (Climbing Stairs, House Robber)
- 2D DP (Knapsack, LCS, Matrix Paths)
Common Snippet (0/1 Knapsack):
int knapSack(int W, vector<int>& wt, vector<int>& val, int n) {
vector<vector<int>> dp(n+1, vector<int>(W+1,0));
for(int i=1;i<=n;i++){
for(int w=1;w<=W;w++){
if(wt[i-1]<=w)
dp[i][w] = max(val[i-1]+dp[i-1][w-wt[i-1]], dp[i-1][w]);
else dp[i][w]=dp[i-1][w];
}
}
return dp[n][W];
}
6. Greedy
- Interval Scheduling, Activity Selection, Huffman Coding
7. Bit Manipulation
- Check Power of 2, Count Set Bits, XOR Patterns
// Check if number is power of 2
bool isPowerOfTwo(int n) {
return n>0 && (n&(n-1))==0;
}
8. Custom Sorting
Use custom comparators for sorting problems.
sort(arr.begin(), arr.end(), [](auto &a, auto &b){
return a.second > b.second; // Example: sort by second element desc
});
■ Quick Tips & Edge Cases
- Always check empty input/edge constraints.
- Handle integer overflow with long long.
- In graphs, beware of disconnected components.
- In DP, initialize base cases carefully.
- In recursion, ensure termination to avoid TLE.