? Ultimate DSA Sheet-Tricks, Codes & Optimized Approaches
? Ultimate DSA Sheet-Tricks, Codes & Optimized Approaches
Approaches
💡 Master Data Structures & Algorithms with optimized solutions, tricks, and code
implementations in C++.
BY:Syntax_Error
📌 Topics Covered:
🔹 Arrays
🔹 Strings
🔹 Sorting & Searching
🔹 Hashing
🔹 Linked List
🔹 Stack & Queue
🔹 Recursion & Backtracking
🔹 Binary Tree & BST
🔹 Heap & Priority Queue
🔹 Graph Theory
🔹 Dynamic Programming (DP)
🔹 Greedy Algorithms
🔹 Bit Manipulation
🔹 Math & Number Theory
🔹 Trie & Advanced Data Structures
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {2, 0, 2, 1, 1, 0};
sortColors(nums);
for (int num : nums) cout << num << " ";
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout << maxSubArray(nums);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
if (i >= 0) {
int j = nums.size() - 1;
while (nums[j] <= nums[i]) j--; // Step 2: Find next greater
element
swap(nums[i], nums[j]);
}
reverse(nums.begin() + i + 1, nums.end()); // Step 3: Reverse suffix
}
int main() {
vector<int> nums = {1, 2, 3};
nextPermutation(nums);
for (int num : nums) cout << num << " ";
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {2, 2, 1, 1, 1, 2, 2};
cout << majorityElement(nums);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
string longestPalindrome(string s) {
int start = 0, maxLen = 0;
auto expand = [&](int l, int r) {
while (l >= 0 && r < s.size() && s[l] == s[r]) {
if (r - l + 1 > maxLen) {
start = l;
maxLen = r - l + 1;
}
l--; r++;
}
};
for (int i = 0; i < s.size(); i++) {
expand(i, i); // Odd length palindrome
expand(i, i+1); // Even length palindrome
}
return s.substr(start, maxLen);
}
int main() {
string s = "babad";
cout << longestPalindrome(s);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "listen", t = "silent";
cout << (isAnagram(s, t) ? "Yes" : "No");
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
string text = "hello", pattern = "ll";
cout << strStr(text, pattern);
}
✅ 4. Find the Longest Common Prefix in a List of Strings (Binary Search Approach)
📌 Algorithm: Binary Search / Trie
📌 Trick: Find the minimum length string and compare all prefixes.
💻 Code:
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<string> strs = {"flower", "flow", "flight"};
cout << longestCommonPrefix(strs);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
string countAndSay(int n) {
if (n == 1) return "1";
string prev = countAndSay(n - 1), res = "";
int count = 1;
for (int i = 1; i < prev.size(); i++) {
if (prev[i] == prev[i - 1]) count++;
else {
res += to_string(count) + prev[i - 1];
count = 1;
}
}
res += to_string(count) + prev.back();
return res;
}
int main() {
int n = 5;
cout << countAndSay(n);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
string longestPalindrome(string s) {
int start = 0, maxLen = 0;
auto expand = [&](int l, int r) {
while (l >= 0 && r < s.size() && s[l] == s[r]) {
if (r - l + 1 > maxLen) {
start = l;
maxLen = r - l + 1;
}
l--; r++;
}
};
for (int i = 0; i < s.size(); i++) {
expand(i, i); // Odd length palindrome
expand(i, i+1); // Even length palindrome
}
return s.substr(start, maxLen);
}
int main() {
string s = "babad";
cout << longestPalindrome(s);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "listen", t = "silent";
cout << (isAnagram(s, t) ? "Yes" : "No");
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
string text = "hello", pattern = "ll";
cout << strStr(text, pattern);
}
✅ 4. Find the Longest Common Prefix in a List of Strings (Binary Search Approach)
📌 Algorithm: Binary Search / Trie
📌 Trick: Find the minimum length string and compare all prefixes.
💻 Code:
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<string> strs = {"flower", "flow", "flight"};
cout << longestCommonPrefix(strs);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
string countAndSay(int n) {
if (n == 1) return "1";
string prev = countAndSay(n - 1), res = "";
int count = 1;
for (int i = 1; i < prev.size(); i++) {
if (prev[i] == prev[i - 1]) count++;
else {
res += to_string(count) + prev[i - 1];
count = 1;
}
}
res += to_string(count) + prev.back();
return res;
}
int main() {
int n = 5;
cout << countAndSay(n);
}
int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
vector<int> res = twoSum(nums, target);
cout << res[0] << " " << res[1];
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {100, 4, 200, 1, 3, 2};
cout << longestConsecutive(nums);
}
✅ 3. Subarray Sum Equals K (Using Prefix Sum & HashMap)
📌 Algorithm: Prefix Sum with HashMap
📌 Trick: Store prefix sum frequencies to check for sum - k in O(1).
💻 Code:
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {1, 1, 1};
int k = 2;
cout << subarraySum(nums, k);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {4, 3, 2, 7, 8, 2, 3, 1};
vector<int> res = findDuplicates(nums);
for (int num : res) cout << num << " ";
}
✅ 5. Find First Non-Repeating Character (Using HashMap for Counting)
📌 Algorithm: Hash Map + Order Maintenance
📌 Trick: First store frequency, then check the first element with count = 1.
💻 Code:
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
char firstUniqChar(string s) {
unordered_map<char, int> freq;
for (char c : s) freq[c]++;
for (char c : s) {
if (freq[c] == 1) return c;
}
return '_'; // Return '_' if no unique character exists
}
int main() {
string s = "leetcode";
cout << firstUniqChar(s);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// Iterative Approach
ListNode* reverseList(ListNode* head) {
ListNode *prev = NULL, *curr = head;
while (curr) {
ListNode* nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
// Recursive Approach
ListNode* reverseListRecursive(ListNode* head) {
if (!head || !head->next) return head;
ListNode* newHead = reverseListRecursive(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head = reverseList(head);
printList(head);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
bool hasCycle(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = head->next; // Creating a cycle
✅ 3. Find the Middle of a Linked List (Slow & Fast Pointer Approach)
📌 Algorithm: Two Pointers (Tortoise & Hare)
📌 Trick: Move slow by 1 step and fast by 2 steps, when fast reaches the end, slow is at the
middle.
💻 Code:
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
int main() {
ListNode* l1 = new ListNode(1);
l1->next = new ListNode(3);
l1->next->next = new ListNode(5);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
while (fast) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {2, 1, 3, 5, 4};
vector<int> res = nextGreaterElement(nums);
for (int num : res) cout << num << " ";
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
bool isValid(string s) {
stack<char> st;
unordered_map<char, char> pairs = {{')', '('}, {']', '['}, {'}', '{'}};
for (char c : s) {
if (pairs.count(c)) {
if (st.empty() || st.top() != pairs[c]) return false;
st.pop();
} else {
st.push(c);
}
}
return st.empty();
}
int main() {
string s = "{[()]}";
cout << (isValid(s) ? "Valid" : "Invalid");
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> heights = {2, 1, 5, 6, 2, 3};
cout << largestRectangleArea(heights);
}
🔥 Queue Problems
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
class MyQueue {
stack<int> input, output;
public:
void push(int x) { input.push(x); }
int pop() {
if (output.empty()) {
while (!input.empty()) {
output.push(input.top());
input.pop();
}
}
int val = output.top();
output.pop();
return val;
}
int peek() {
if (output.empty()) {
while (!input.empty()) {
output.push(input.top());
input.pop();
}
}
return output.top();
}
int main() {
MyQueue q;
q.push(1);
q.push(2);
cout << q.peek() << endl; // 1
cout << q.pop() << endl; // 1
cout << q.empty() << endl; // false
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
dq.push_back(i);
if (i >= k - 1) res.push_back(nums[dq.front()]); // Front contains
max
}
return res;
}
int main() {
vector<int> nums = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
vector<int> res = maxSlidingWindow(nums, k);
for (int num : res) cout << num << " ";
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> arr = {1, 2, 3};
vector<int> sub;
printSubsequences(arr, sub, 0);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 3;
generateParentheses("", 0, 0, n);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 3;
towerOfHanoi(n, 'A', 'C', 'B');
}
🔥 Backtracking Problems
✅ 4. N-Queens Problem (Place Queens Safely on Chessboard)
📌 Algorithm: Backtracking with Safe Placement Check
📌 Trick: Use an array to track safe columns & diagonals to optimize backtracking.
💻 Code:
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 4;
vector<string> board(n, string(n, '.'));
solveNQueens(board, 0, n);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<vector<int>> maze = {{1, 0, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0},
{1, 1, 1, 1}};
int n = maze.size();
vector<vector<int>> visited(n, vector<int>(n, 0));
vector<string> paths;
visited[0][0] = 1;
solveMaze(maze, 0, 0, paths, "", visited);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(5);
root->right = new TreeNode(1);
root->left->left = new TreeNode(6);
root->left->right = new TreeNode(2);
root->right->left = new TreeNode(0);
root->right->right = new TreeNode(8);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
queue<TreeNode*> q;
q.push(root);
bool leftToRight = true;
while (!q.empty()) {
int size = q.size();
vector<int> level(size);
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
int index = leftToRight ? i : (size - 1 - i);
level[index] = node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(level);
leftToRight = !leftToRight;
}
return res;
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int maxDiameter = 0;
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
TreeNode* root = new TreeNode(2);
root->left = new TreeNode(1);
root->right = new TreeNode(3);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int main() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(6);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->left->left->left = new TreeNode(1);
int k = 3;
cout << "Kth Smallest: " << kthSmallest(root, k);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {3, 2, 3, 1, 2, 4, 5, 5, 6};
int k = 4;
cout << findKthLargest(nums, k) << endl; // Output: 4
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
struct Compare {
bool operator()(ListNode* a, ListNode* b) {
return a->val > b->val;
}
};
return dummy->next;
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
vector<int> res;
while (!minHeap.empty()) {
res.push_back(minHeap.top().second);
minHeap.pop();
}
return res;
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
class MedianFinder {
priority_queue<int> left; // Max-Heap (Lower half)
priority_queue<int, vector<int>, greater<int>> right; // Min-Heap
(Upper half)
public:
void addNum(int num) {
if (left.empty() || num <= left.top()) left.push(num);
else right.push(num);
double findMedian() {
if (left.size() > right.size()) return left.top();
return (left.top() + right.top()) / 2.0;
}
};
int main() {
MedianFinder mf;
mf.addNum(1);
mf.addNum(2);
cout << mf.findMedian() << endl; // Output: 1.5
mf.addNum(3);
cout << mf.findMedian() << endl; // Output: 2
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
priority_queue<int> maxHeap;
for (auto f : freq) maxHeap.push(f.second);
int cycles = 0;
while (!maxHeap.empty()) {
vector<int> temp;
for (int i = 0; i <= n; i++) {
if (!maxHeap.empty()) {
temp.push_back(maxHeap.top() - 1);
maxHeap.pop();
}
}
for (int t : temp)
if (t > 0) maxHeap.push(t);
return cycles;
}
int main() {
vector<char> tasks = {'A', 'A', 'A', 'B', 'B', 'B'};
int n = 2;
cout << leastInterval(tasks, n) << endl; // Output: 8
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, adj, visited);
count++;
}
}
return count;
}
int main() {
int n = 5;
vector<pair<int, int>> edges = {{0, 1}, {1, 2}, {3, 4}};
cout << countConnectedComponents(n, edges) << endl; // Output: 2
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
recStack[node] = 0;
return false;
}
return false;
}
int main() {
int n = 4;
vector<pair<int, int>> edges = {{0, 1}, {1, 2}, {2, 0}, {2, 3}};
cout << detectCycle(n, edges) << endl; // Output: 1 (true)
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
dist[src] = 0;
q.push(src);
while (!q.empty()) {
int node = q.front();
q.pop();
int main() {
int n = 6;
vector<pair<int, int>> edges = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4},
{4, 5}};
vector<int> dist = shortestPath(n, edges, 0);
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
dist[src] = 0;
pq.push({0, src});
while (!pq.empty()) {
int d = pq.top().first, node = pq.top().second;
pq.pop();
int main() {
int n = 5;
vector<pair<int, int>> adj[5] = {
{{1, 10}, {2, 3}},
{{3, 2}},
{{1, 4}, {3, 8}},
{{4, 7}},
{}
};
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
vector<int> topologicalSort(int n, vector<pair<int, int>>& edges) {
vector<vector<int>> adj(n);
vector<int> inDegree(n, 0), topoSort;
queue<int> q;
for (int i = 0; i < n; i++)
if (inDegree[i] == 0) q.push(i);
while (!q.empty()) {
int node = q.front();
q.pop();
topoSort.push_back(node);
int main() {
int n = 6;
vector<pair<int, int>> edges = {{5, 2}, {5, 0}, {4, 0}, {4, 1}, {2, 3},
{3, 1}};
vector<int> topoOrder = topologicalSort(n, edges);
for (int node : topoOrder) cout << node << " "; // Output: 5 4 2 3 1 0
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
string s1 = "abcde", s2 = "ace";
cout << longestCommonSubsequence(s1, s2) << endl; // Output: 3
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> weights = {2, 3, 4, 5};
vector<int> values = {3, 4, 5, 6};
int W = 5;
cout << knapsack(weights, values, W) << endl; // Output: 7
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> coins = {1, 2, 5};
int amount = 11;
cout << coinChange(coins, amount) << endl; // Output: 3
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {10, 9, 2, 5, 3, 7, 101, 18};
cout << lengthOfLIS(nums) << endl; // Output: 4
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> dp;
int main() {
vector<int> arr = {40, 20, 30, 10, 30};
int n = arr.size();
dp.assign(n, vector<int>(n, -1));
cout << mcm(arr, 1, n - 1) << endl; // Output: 26000
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct Activity {
int start, end;
};
int main() {
vector<Activity> activities = {{1, 3}, {2, 5}, {3, 9}, {6, 8}};
cout << maxActivities(activities) << endl; // Output: 2
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct Node {
char ch;
int freq;
Node *left, *right;
Node(char c, int f) : ch(c), freq(f), left(NULL), right(NULL) {}
};
struct Compare {
bool operator()(Node* a, Node* b) {
return a->freq > b->freq;
}
};
int main() {
vector<char> chars = {'a', 'b', 'c', 'd', 'e', 'f'};
vector<int> freqs = {5, 9, 12, 13, 16, 45};
huffmanCoding(chars, freqs);
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> coins = {1, 5, 10, 25, 100};
int amount = 93;
cout << minCoins(coins, amount) << endl; // Output: 5
(25+25+25+10+5+1+1+1)
}
✅ 4. Fractional Knapsack
📌 Algorithm: Greedy (Sort by Value-to-Weight Ratio)
📌 Trick: Sort items by value/weight and take as much of the most valuable item as
possible.
💻 Code:
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct Item {
int weight, value;
};
int main() {
vector<Item> items = {{10, 60}, {20, 100}, {30, 120}};
int W = 50;
cout << fractionalKnapsack(items, W) << endl; // Output: 240
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct Job {
char id;
int deadline, profit;
};
int maxDeadline = 0;
for (auto& job : jobs) maxDeadline = max(maxDeadline, job.deadline);
int main() {
vector<Job> jobs = {{'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27}, {'d', 1,
25}, {'e', 3, 15}};
cout << jobSequencing(jobs) << endl; // Output: 142
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {4, 3, 2, 4, 2, 3, 7};
cout << findUnique(nums) << endl; // Output: 7
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
bool isPowerOfTwo(int n) {
return (n > 0) && ((n & (n - 1)) == 0);
}
int main() {
cout << isPowerOfTwo(16) << endl; // Output: 1 (true)
cout << isPowerOfTwo(18) << endl; // Output: 0 (false)
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int countSetBits(int n) {
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
int main() {
cout << countSetBits(15) << endl; // Output: 4 (Binary: 1111)
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> nums = {3, 4, 3, 7, 8, 4};
findTwoUnique(nums); // Output: 7 8
}
n % 4 == 0 → result = n
n % 4 == 1 → result = 1
n % 4 == 2 → result = n + 1
n % 4 == 3 → result = 0
💻 Code:
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int xorTillN(int n) {
if (n % 4 == 0) return n;
if (n % 4 == 1) return 1;
if (n % 4 == 2) return n + 1;
return 0;
}
int main() {
cout << xorTillN(10) << endl; // Output: 11
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
bool isPrime(int n) {
if (n < 2) return false;
if (n == 2 || n == 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
vector<bool> sieve(int n) {
vector<bool> isPrime(n + 1, true);
isPrime[0] = isPrime[1] = false;
int main() {
int n = 50;
vector<bool> primes = sieve(n);
for (int i = 2; i <= n; i++) {
if (primes[i]) cout << i << " ";
}
cout << endl;
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
cout << gcd(56, 98) << endl; // Output: 14
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
cout << modExp(2, 10, 1000000007) << endl; // Output: 1024
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
int main() {
cout << modInverse(3, 7) << endl; // Output: 5 (because 3 * 5 ≡ 1 (mod
7))
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct TrieNode {
TrieNode* children[26];
bool isEndOfWord;
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < 26; i++) children[i] = nullptr;
}
};
class Trie {
public:
TrieNode* root;
Trie() { root = new TrieNode(); }
int main() {
Trie trie;
trie.insert("apple");
cout << trie.search("apple") << endl; // Output: 1 (true)
cout << trie.search("app") << endl; // Output: 0 (false)
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
struct TrieNode {
TrieNode* children[26];
int count;
TrieNode() {
count = 0;
for (int i = 0; i < 26; i++) children[i] = nullptr;
}
};
class Trie {
public:
TrieNode* root;
Trie() { root = new TrieNode(); }
string longestCommonPrefix() {
TrieNode* node = root;
string prefix = "";
while (node) {
int nextIndex = -1;
int childrenCount = 0;
for (int i = 0; i < 26; i++) {
if (node->children[i]) {
nextIndex = i;
childrenCount++;
}
}
if (childrenCount != 1) break;
prefix += char('a' + nextIndex);
node = node->children[nextIndex];
}
return prefix;
}
};
int main() {
Trie trie;
vector<string> words = {"flower", "flow", "flight"};
for (string word : words) trie.insert(word);
cout << trie.longestCommonPrefix() << endl; // Output: "fl"
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
class LRUCache {
public:
int capacity;
list<pair<int, int>> lruList;
unordered_map<int, list<pair<int, int>>::iterator> cache;
int main() {
LRUCache lru(2);
lru.put(1, 10);
lru.put(2, 20);
cout << lru.get(1) << endl; // Output: 10
lru.put(3, 30);
cout << lru.get(2) << endl; // Output: -1 (Evicted)
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
class SegmentTree {
vector<int> tree;
int n;
public:
SegmentTree(vector<int>& arr) {
n = arr.size();
tree.resize(4 * n);
build(arr, 1, 0, n - 1);
}
int main() {
vector<int> arr = {1, 2, 3, 4, 5};
SegmentTree segTree(arr);
cout << segTree.rangeSum(1, 3) << endl; // Output: 9
}
cpp
CopyEdit
#include <bits/stdc++.h>
using namespace std;
class FenwickTree {
vector<int> BIT;
int n;
public:
FenwickTree(int size) {
n = size;
BIT.assign(n + 1, 0);
}
int main() {
FenwickTree fen(5);
fen.update(1, 5);
fen.update(3, 7);
cout << fen.query(3) << endl; // Output: 12
}
If you've reached this point, you’ve taken a significant step toward mastering Data
Structures and Algorithms. Completing this entire PDF from start to finish is a testament to
your dedication and hard work. Keep practicing, keep learning, and keep pushing your limits
—your efforts will pay off in coding competitions, interviews, and real-world problem-
solving! 🚀
If this guide helped you, I’d love to hear your feedback! Feel free to connect with me on
Instagram (@Syntax_Error) for more DSA problems, tricks, and full-stack development
content. Let's keep growing together! 💡🔥
⚠ Copyright Notice ⚠
If you wish to share or reference this material, please ensure proper attribution to the
original creator (@Syntax_Error).