0% found this document useful (0 votes)
48 views400 pages

Striver A2z CPP Part 2

The document contains a collection of C++ programming problems and their solutions, including tasks like rotating a matrix, printing in spiral order, counting subarrays with a given sum, generating Pascal's triangle, and finding majority elements. Each problem is accompanied by code snippets and brief explanations of the algorithms used. The solutions emphasize efficient techniques such as prefix sums, hash maps, and the two-pointer method.

Uploaded by

yashamhm19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views400 pages

Striver A2z CPP Part 2

The document contains a collection of C++ programming problems and their solutions, including tasks like rotating a matrix, printing in spiral order, counting subarrays with a given sum, generating Pascal's triangle, and finding majority elements. Each problem is accompanied by code snippets and brief explanations of the algorithms used. The solutions emphasize efficient techniques such as prefix sums, hash maps, and the two-pointer method.

Uploaded by

yashamhm19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 400

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

Step 1 : Learn the basics


The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

PROBLEM:51

Question:

C++ Code to Rotate Matrix by 90 Degrees Clockwise

cpp

CopyEdit

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

void rotate90Clockwise(vector<vector<int>>& matrix) {

int n = matrix.size();

// Step 1: Transpose the matrix

for(int i = 0; i < n; i++) {

for(int j = i; j < n; j++) {

swap(matrix[i][j], matrix[j][i]);

// Step 2: Reverse each row

for(int i = 0; i < n; i++) {

reverse(matrix[i].begin(), matrix[i].end());

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

void printMatrix(const vector<vector<int>>& matrix) {

for(const auto& row : matrix) {

for(int val : row)

cout << val << " ";

cout << endl;

int main() {

vector<vector<int>> matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

cout << "Matrix after 90-degree rotation:\n";

rotate90Clockwise(matrix);

printMatrix(matrix);

return 0;

Explanation

1. First, transpose the matrix by swapping elements across the diagonal.


2. Then, reverse each row to complete the clockwise rotation.
3. These two operations rotate the matrix by 90° in-place, without extra space.
4. This method is efficient and works only for square matrices.

PROBLEM:52

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

Question:Print a Matrix in Spiral Order


C++ Code to Print Matrix in Spiral Order

cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

void printSpiral(const vector<vector<int>>& matrix) {

int top = 0, bottom = matrix.size() - 1;

int left = 0, right = matrix[0].size() - 1;

while(top <= bottom && left <= right) {

for(int i = left; i <= right; i++)

cout << matrix[top][i] << " ";

top++;

for(int i = top; i <= bottom; i++)

cout << matrix[i][right] << " ";

right--;

if(top <= bottom) {

for(int i = right; i >= left; i--)

cout << matrix[bottom][i] << " ";

bottom--;

if(left <= right) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for(int i = bottom; i >= top; i--)

cout << matrix[i][left] << " ";

left++;

int main() {

vector<vector<int>> matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

cout << "Spiral order of the matrix:\n";

printSpiral(matrix);

return 0;

� 4-Line Explanation

1.Use four pointers to track the top, bottom, left, and right boundaries.

2.Traverse the matrix in layers, printing rows and columns in a clockwise spiral.

3.After printing each side, update the respective boundary inward.

4.Repeat the process until all elements are printed in spiral order.

PROBLEM:53

Question: Count Subarrays with Given Sum

C++ Code

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


CopyEdit

#include <iostream>

#include <unordered_map>

#include <vector>

using namespace std;

int countSubarraysWithSum(const vector<int>& nums, int k) {

unordered_map<int, int> prefixSumFreq;

int sum = 0, count = 0;

prefixSumFreq[0] = 1;

for(int num : nums) {

sum += num;

if(prefixSumFreq.find(sum - k) != prefixSumFreq.end()) {

count += prefixSumFreq[sum - k];

prefixSumFreq[sum]++;

return count;

int main() {

vector<int> nums = {1, 1, 1};

int k = 2;

cout << "Total subarrays with sum " << k << ": " << countSubarraysWithSum(nums, k) <<
endl;

return 0;

� 4-Line Explanation

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1.Maintain a hash map to track how many times each prefix sum occurs.

2.Keep a running sum while traversing the array to represent the current prefix sum.

3.For each step, check if (sum - k) exists in the map to count valid subarrays.

4.This method provides an efficient linear-time solution using prefix sums.

PROBLEM:54

Question: Generate Pascal's Triangle

C++ Code

cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

vector<vector<int>> generatePascal(int n) {

vector<vector<int>> triangle;

for(int i = 0; i < n; ++i) {

vector<int> row(i + 1, 1);

for(int j = 1; j < i; ++j) {

row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];

triangle.push_back(row);

return triangle;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

int n = 5;

vector<vector<int>> pascal = generatePascal(n);

for(const auto& row : pascal) {

for(int val : row) cout << val << " ";

cout << endl;

return 0;

� 4-Line Explanation

1. Each row starts and ends with 1, and inner values are the sum of two elements above.
2. Use a 2D vector to construct each row iteratively based on the previous row.
3. The value at position j in row i is calculated from row i-1 values j-1 and j.
4. Build all rows up to n to complete Pascal’s Triangle efficiently.

PROBLEM:55

Question: Majority Element (Appearing More Than ⌊n/3⌋ Times)

C++ Code

cpp

CopyEdit

#include <iostream>#include <vector>using namespace std;

vector<int> majorityElement(vector<int>& nums) {

int count1 = 0, count2 = 0;

int candidate1 = 0, candidate2 = 1;

for (int num : nums) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (num == candidate1) count1++;

else if (num == candidate2) count2++;

else if (count1 == 0) {

candidate1 = num;

count1 = 1;

else if (count2 == 0) {

candidate2 = num;

count2 = 1;

else {

count1--;

count2--;

count1 = count2 = 0;

for (int num : nums) {

if (num == candidate1) count1++;

else if (num == candidate2) count2++;

vector<int> result;

int n = nums.size();

if (count1 > n / 3) result.push_back(candidate1);

if (count2 > n / 3) result.push_back(candidate2);

return result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

vector<int> nums = {1, 2, 3, 2, 2, 1, 1};

vector<int> res = majorityElement(nums);

cout << "Majority elements (> n/3 times): ";

for (int num : res)

cout << num << " ";

cout << endl;

return 0;

� 4-Line Explanation

1. At most two elements can appear more than ⌊n/3⌋ times in an array.
2. Use a modified Boyer-Moore algorithm to find two potential candidates.
3. Re-count frequencies of these candidates to validate their majority status.
4. Return those whose counts exceed ⌊n/3⌋, achieving linear time and constant space.

PROBLEM:56

Question: 3-Sum Problem

C++ Code (Using Two Pointer Technique)

cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

vector<vector<int>> threeSum(vector<int>& nums) {

vector<vector<int>> result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


sort(nums.begin(), nums.end()); // Step 1: Sort the array

for (int i = 0; i < nums.size(); i++) {

// Skip duplicate elements for the first number

if (i > 0 && nums[i] == nums[i - 1]) continue;

int target = -nums[i]; // Because a + b + c = 0 => b + c = -a

int left = i + 1;

int right = nums.size() - 1;

while (left < right) {

int sum = nums[left] + nums[right];

if (sum == target) {

result.push_back({nums[i], nums[left], nums[right]});

// Skip duplicates for second and third number

while (left < right && nums[left] == nums[left + 1]) left++;

while (left < right && nums[right] == nums[right - 1]) right--;

left++;

right--;

} else if (sum < target) {

left++;

} else {

right--;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return result;

// Example usageint main() {

vector<int> nums = {-1, 0, 1, 2, -1, -4};

vector<vector<int>> result = threeSum(nums);

cout << "Unique triplets that sum to 0:\n";

for (auto triplet : result) {

for (int num : triplet)

cout << num << " ";

cout << endl;

return 0;

� 4-Line Explanation

 Sort the array to easily handle duplicates and use the two-pointer technique.

 Fix one element at a time and find the other two using left and right pointers.

 Skip duplicates for all three elements to avoid repeating triplets.

 Store valid triplets when their sum is zero, and adjust pointers accordingly.

PROBLEM:57

Question: 4-Sum Problem

C++ Code (Optimized with Sorting + Two Pointers)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

CopyEdit

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

vector<vector<int>> fourSum(vector<int>& nums, int target) {

vector<vector<int>> result;

int n = nums.size();

sort(nums.begin(), nums.end());

for (int i = 0; i < n; i++) {

if (i > 0 && nums[i] == nums[i - 1]) continue;

for (int j = i + 1; j < n; j++) {

if (j > i + 1 && nums[j] == nums[j - 1]) continue;

long long target2 = (long long)target - nums[i] - nums[j];

int left = j + 1;

int right = n - 1;

while (left < right) {

long long sum = nums[left] + nums[right];

if (sum == target2) {

result.push_back({nums[i], nums[j], nums[left], nums[right]});

while (left < right && nums[left] == nums[left + 1]) left++;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (left < right && nums[right] == nums[right - 1]) right--;

left++;

right--;

} else if (sum < target2) {

left++;

} else {

right--;

return result;

// Example usageint main() {

vector<int> nums = {1, 0, -1, 0, -2, 2};

int target = 0;

vector<vector<int>> result = fourSum(nums, target);

cout << "Unique quadruplets that sum to " << target << ":\n";

for (auto quad : result) {

for (int num : quad)

cout << num << " ";

cout << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation in 4 Lines

1. Sort the array, then fix two elements (i and j) and use two pointers (left and right) to
find remaining two.
2. Skip duplicates at every level (i, j, left, right) to avoid repeated quadruplets.
3. Check if sum of all four elements equals the target, if yes, store the combination.
4. Move pointers accordingly: left/right for narrowing down the pair that satisfies the target.

PROBLEM:58

Question: Largest Subarray with 0 Sum

C++ Code (Using Hash Map)

cpp

#include <iostream>

#include <vector>

#include <unordered_map>

using namespace std;

int maxLenZeroSumSubarray(vector<int>& nums) {

unordered_map<int, int> sumIndex;

int maxLen = 0, sum = 0;

for (int i = 0; i < nums.size(); i++) {

sum += nums[i];

if (sum == 0)

maxLen = i + 1;

else if (sumIndex.find(sum) != sumIndex.end())

maxLen = max(maxLen, i - sumIndex[sum]);

else

sumIndex[sum] = i;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return maxLen;

// Example usageint main() {

vector<int> nums = {15, -2, 2, -8, 1, 7, 10, 23};

cout << "Length of largest subarray with 0 sum: " << maxLenZeroSumSubarray(nums) <<
endl;

return 0;

� Code Explanation in 4 Lines

1.Traverse the array and keep track of cumulative sum at each index.

2.If the sum becomes 0, update the maximum subarray length.

3Use a hash map to store the first occurrence of each sum.

5. If a sum repeats, the subarray between indices sums to 0 — update max length.

PROBLEM:59

Question: Count Number of Subarrays with Given XOR K

C++ Code (Using Hash Map for Prefix XORs)

cpp

#include <iostream>

#include <vector>

#include <unordered_map>

using namespace std;

int countSubarraysWithXOR(vector<int>& nums, int K) {

unordered_map<int, int> freq;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int count = 0, xorSum = 0;

for (int num : nums) {

xorSum ^= num;

if (xorSum == K) count++;

int required = xorSum ^ K;

if (freq.find(required) != freq.end())

count += freq[required];

freq[xorSum]++;

return count;

// Example usageint main() {

vector<int> nums = {4, 2, 2, 6, 4};

int K = 6;

cout << "Count of subarrays with XOR " << K << ": " << countSubarraysWithXOR(nums, K)
<< endl;

return 0;

� Code Explanation in 4 Lines

1.Use prefix XOR to calculate XOR of subarrays efficiently while traversing the array.

2.If current prefix XOR is equal to K, increment the count (entire subarray from start).

3.Use a hash map to store frequency of prefix XORs seen so far.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


4.For each prefix XOR, check if (current XOR ^ K) exists in map — it gives subarrays
ending at current index.

PROBLEM:60

Question:Merge Overlapping Intervals

C++ Code (Greedy + Sorting)

cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

vector<vector<int>> mergeIntervals(vector<vector<int>>& intervals) {

if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end()); // Sort by start time

vector<vector<int>> merged;

merged.push_back(intervals[0]);

for (int i = 1; i < intervals.size(); i++) {

if (intervals[i][0] <= merged.back()[1]) {

merged.back()[1] = max(merged.back()[1], intervals[i][1]);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


} else {

merged.push_back(intervals[i]);

return merged;

// Example usageint main() {

vector<vector<int>> intervals = {{1,3},{2,6},{8,10},{15,18}};

vector<vector<int>> result = mergeIntervals(intervals);

cout << "Merged intervals:\n";

for (auto interval : result) {

cout << "[" << interval[0] << "," << interval[1] << "] ";

cout << endl;

return 0;

� Code Explanation in 4 Lines

1.Sort intervals based on start times to bring overlaps together.

2.Initialize the merged list with the first interval.

3.For each interval, check if it overlaps with the last merged interval.

4.Merge if overlapping, otherwise just add it as a new interval.

PROBLEM:61

Question: Merge Two Sorted Arrays Without Extra Space


The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)
C++ Code (Using Gap Method - Shell Sort Idea)

cpp

#include <iostream>#include <vector>#include <cmath>using namespace std;

void merge(vector<int>& arr1, vector<int>& arr2) {

int n = arr1.size(), m = arr2.size();

int gap = ceil((double)(n + m) / 2);

while (gap > 0) {

int i = 0, j = gap;

while (j < n + m) {

int a = (i < n) ? arr1[i] : arr2[i - n];

int b = (j < n) ? arr1[j] : arr2[j - n];

if (a > b) {

if (i < n && j < n)

swap(arr1[i], arr1[j]);

else if (i < n)

swap(arr1[i], arr2[j - n]);

else

swap(arr2[i - n], arr2[j - n]);

i++; j++;

gap = (gap == 1) ? 0 : ceil(gap / 2.0);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Example usageint main() {

vector<int> arr1 = {1, 4, 7, 8, 10};

vector<int> arr2 = {2, 3, 9};

merge(arr1, arr2);

cout << "Merged arr1: ";

for (int num : arr1) cout << num << " ";

cout << "\nMerged arr2: ";

for (int num : arr2) cout << num << " ";

cout << endl;

return 0;

� Code Explanation

1.Use the gap method (like Shell Sort) to compare and swap elements across
arrays.

2.Initially set gap = ceil((n+m)/2), and reduce gap in each pass.

3.Compare elements at index pairs (i, i+gap) in the combined virtual array.

4.Swap if out of order, and repeat until gap becomes 0 (fully sorted).

PROBLEM:62

Question : Find the Repeating and Missing Number


C++ Code (Using Math Formula Approach)

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


CopyEdit

#include <iostream>

#include <vector>

using namespace std;

pair<int, int> findMissingAndRepeating(const vector<int>& nums) {

int n = nums.size();

long long sum_n = (n * (n + 1)) / 2;

long long sum_sq_n = (n * (n + 1) * (2 * n + 1)) / 6;

long long actual_sum = 0, actual_sq_sum = 0;

for (int num : nums) {

actual_sum += num;

actual_sq_sum += (long long)num * num;

long long diff = sum_n - actual_sum; // M - R

long long sq_diff = sum_sq_n - actual_sq_sum; // M^2 - R^2

long long sum = sq_diff / diff; // M + R

int missing = (diff + sum) / 2;

int repeating = missing - diff;

return {repeating, missing};

// Example usageint main() {

vector<int> nums = {3, 1, 2, 5, 3};

auto [repeating, missing] = findMissingAndRepeating(nums);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Repeating number: " << repeating << endl;

cout << "Missing number: " << missing << endl;

return 0;

� Code Explanation

1. Calculate expected sum and sum of squares from 1 to n.


2. Compute actual sum and sum of squares from the array.
3. Use equations:

M - R = expected_sum - actual_sum

M + R = (expected_sq_sum - actual_sq_sum) / (M - R)

4.Solve for missing (M) and repeating (R) using these two equations.

PROBLEM:63

Question : Count Inversions in an Array


C++ Code (Modified Merge Sort Approach - O(n log n))

cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

long long merge(vector<int>& arr, int left, int mid, int right) {

vector<int> temp;

int i = left, j = mid + 1;

long long inv_count = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (i <= mid && j <= right) {

if (arr[i] <= arr[j]) {

temp.push_back(arr[i++]);

} else {

temp.push_back(arr[j++]);

inv_count += (mid - i + 1); // Count inversions

while (i <= mid) temp.push_back(arr[i++]);

while (j <= right) temp.push_back(arr[j++]);

for (int k = left; k <= right; k++) arr[k] = temp[k - left];

return inv_count;

long long mergeSort(vector<int>& arr, int left, int right) {

long long inv_count = 0;

if (left < right) {

int mid = (left + right) / 2;

inv_count += mergeSort(arr, left, mid);

inv_count += mergeSort(arr, mid + 1, right);

inv_count += merge(arr, left, mid, right);

return inv_count;

int countInversions(vector<int>& arr) {

return mergeSort(arr, 0, arr.size() - 1);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Example usageint main() {

vector<int> arr = {2, 4, 1, 3, 5};

cout << "Number of inversions: " << countInversions(arr) << endl;

return 0;

� Code Explanation

1.Use modified merge sort to divide the array and count inversions during
merge.

2.While merging, if left[i] > right[j], it contributes (mid - i + 1) inversions.

3.Recursively count inversions in left, right, and merged parts.

4.Total inversions = left inversions + right inversions + cross (merge) inversions.

PROBLEM:64

Question:Reverse Pairs

C++ Code (Modified Merge Sort - O(n log n))

cpp

CopyEdit

#include <iostream>#include <vector>using namespace std;

int countPairs(vector<int>& nums, int low, int mid, int high) {

int count = 0, j = mid + 1;

for (int i = low; i <= mid; i++) {

while (j <= high && nums[i] > 2LL * nums[j]) j++;

count += (j - (mid + 1));

return count;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


void merge(vector<int>& nums, int low, int mid, int high) {

vector<int> temp;

int i = low, j = mid + 1;

while (i <= mid && j <= high) {

if (nums[i] <= nums[j]) temp.push_back(nums[i++]);

else temp.push_back(nums[j++]);

while (i <= mid) temp.push_back(nums[i++]);

while (j <= high) temp.push_back(nums[j++]);

for (int k = low; k <= high; k++) nums[k] = temp[k - low];

int mergeSort(vector<int>& nums, int low, int high) {

if (low >= high) return 0;

int mid = (low + high) / 2;

int count = mergeSort(nums, low, mid);

count += mergeSort(nums, mid + 1, high);

count += countPairs(nums, low, mid, high);

merge(nums, low, mid, high);

return count;

int reversePairs(vector<int>& nums) {

return mergeSort(nums, 0, nums.size() - 1);

// Example usageint main() {

vector<int> nums = {1, 3, 2, 3, 1};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Number of reverse pairs: " << reversePairs(nums) << endl;

return 0;

� Code Explanation

1. Use modified merge sort to divide the array and count reverse pairs during merging.
2. For each i in left half, count js in right half where nums[i] > 2 * nums[j].
3. After counting, merge the halves to maintain sorted order for correctness.
4. Final result is the sum of reverse pairs from all recursive calls.

PROBLEM:65

Question : Maximum Product Subarray

C++ Code (Dynamic Programming - O(n))

cpp

CopyEdit

#include <iostream>#include <vector>#include <algorithm>using namespace std;

int maxProductSubarray(vector<int>& nums) {

int maxProd = nums[0], minProd = nums[0], result = nums[0];

for (int i = 1; i < nums.size(); i++) {

if (nums[i] < 0) swap(maxProd, minProd);

maxProd = max(nums[i], maxProd * nums[i]);

minProd = min(nums[i], minProd * nums[i]);

result = max(result, maxProd);

return result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Example usageint main() {

vector<int> nums = {2, 3, -2, 4};

cout << "Maximum product subarray: " << maxProductSubarray(nums) << endl;

return 0;

� Code Explanation in 4 Lines

1.Keep track of both max and min products at each index (to handle negatives).

2.If current number is negative, swap max and min before updating.

3.Update maxProd and minProd as the max/min of current number or product with previous
values.

4.Continuously update the result with the current max product.

PROBLEM:66

Question :Binary Search to Find X in a Sorted Array

C++ Code (Iterative Binary Search - O(log n))

cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

int binarySearch(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1;

while (low <= high) {

int mid = low + (high - low) / 2;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (arr[mid] == X) return mid;

else if (arr[mid] < X) low = mid + 1;

else high = mid - 1;

return -1; // X not found

// Example usageint main() {

vector<int> arr = {1, 3, 5, 7, 9, 11};

int X = 7;

int index = binarySearch(arr, X);

if (index != -1)

cout << "Element found at index: " << index << endl;

else

cout << "Element not found." << endl;

return 0;

� Code Explanation in 4 Lines

1. Set two pointers low and high to the start and end of the array.
2. While low <= high, compute mid = (low + high)/2.
3. If arr[mid] == X, return the index; else move the low or high pointer.
4. If not found after loop, return -1.

PROBLEM:67

Question : Implement Lower Bound

C++ Code (Custom Lower Bound Using Binary Search)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

int lowerBound(const vector<int>& arr, int X) {

int low = 0, high = arr.size(), ans = arr.size();

while (low < high) {

int mid = low + (high - low) / 2;

if (arr[mid] >= X) {

ans = mid;

high = mid;

} else {

low = mid + 1;

return ans;

// Example usageint main() {

vector<int> arr = {1, 3, 3, 5, 7};

int X = 3;

int index = lowerBound(arr, X);

cout << "Lower bound index of " << X << " is: " << index << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Code Explanation

1.Use binary search to find the first index where arr[mid] ≥ X.

2.If condition is met, store index and search left half.

3.Otherwise, search in the right half.

4.After loop, ans holds the lower bound index or arr.size() if not found.

PROBLEM:68

Question : Implement Upper Bound

C++ Code (Custom Upper Bound Using Binary Search)

cpp

#include <iostream>

#include <vector>

using namespace std;

int upperBound(const vector<int>& arr, int X) {

int low = 0, high = arr.size(), ans = arr.size();

while (low < high) {

int mid = low + (high - low) / 2;

if (arr[mid] > X) {

ans = mid;

high = mid;

} else {

low = mid + 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return ans;

// Example usageint main() {

vector<int> arr = {1, 3, 3, 5, 7};

int X = 3;

int index = upperBound(arr, X);

cout << "Upper bound index of " << X << " is: " << index << endl;

return 0;

� Code Explanation in 4 Lines

1.Use binary search to find the first index where arr[mid] > X.

2.If condition is true, store index and move left.

3.If not, continue searching in the right half.

4.After loop, ans gives the upper bound index or arr.size() if not found.

PROBLEM:69

Question : Search Insert Position

C++ Code (Binary Search Approach)

cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int searchInsert(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1, ans = arr.size();

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == X) return mid;

else if (arr[mid] < X) low = mid + 1;

else {

ans = mid;

high = mid - 1;

return low;

// Example usageint main() {

vector<int> arr = {1, 3, 5, 6};

int X = 2;

int index = searchInsert(arr, X);

cout << "Insert position for " << X << " is: " << index << endl;

return 0;

� Code Explanation

1. Use binary search to look for the target value X in the sorted array.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2. If found, return its index directly.
3. If not found, keep track of the smallest index where arr[mid] > X.
4. The final value of low will be the correct insert position.

PROBLEM:70

Question : Floor / Ceil in Sorted Array

C++ Code (Binary Search Approach)

cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

pair<int, int> findFloorCeil(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1;

int floor = -1, ceil = -1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == X) return {X, X};

else if (arr[mid] < X) {

floor = arr[mid];

low = mid + 1;

} else {

ceil = arr[mid];

high = mid - 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return {floor, ceil};

// Example usageint main() {

vector<int> arr = {1, 2, 4, 6, 10};

int X = 5;

pair<int, int> result = findFloorCeil(arr, X);

cout << "Floor: " << result.first << ", Ceil: " << result.second << endl;

return 0;

� Code Explanation in 4 Lines

1.

Use binary search to efficiently find floor and ceil.

2.
3.

If arr[mid] < X, it could be the floor, so update and move right.

4.
5.

If arr[mid] > X, it could be the ceil, so update and move left.

6.
7.

If exact match found, both floor and ceil are X; otherwise, return tracked values.

PROBLEM:71

Question : Find the First or Last Occurrence in a Sorted Array

C++ Code (Modified Binary Search)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

int firstOccurrence(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1, ans = -1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == X) {

ans = mid;

high = mid - 1; // Keep looking to the left

} else if (arr[mid] < X) low = mid + 1;

else high = mid - 1;

return ans;

int lastOccurrence(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1, ans = -1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == X) {

ans = mid;

low = mid + 1; // Keep looking to the right

} else if (arr[mid] < X) low = mid + 1;

else high = mid - 1;

return ans;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Example usageint main() {

vector<int> arr = {1, 2, 2, 2, 3};

int X = 2;

cout << "First occurrence: " << firstOccurrence(arr, X) << endl;

cout << "Last occurrence: " << lastOccurrence(arr, X) << endl;

return 0;

� Code Explanation

1. Use binary search to find first or last position of X in the array.


2. For first occurrence, when arr[mid] == X, move high to mid - 1.
3. For last occurrence, when arr[mid] == X, move low to mid + 1.
4. Keep updating ans when arr[mid] == X, return -1 if not found.

PROBLEM:72

Question : Count Occurrences of a Number in a Sorted Array with Duplicates

C++ Code (Using Modified Binary Search)

cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

int firstOccurrence(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1, ans = -1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == X) {

ans = mid;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


high = mid - 1;

} else if (arr[mid] < X) low = mid + 1;

else high = mid - 1;

return ans;

int lastOccurrence(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1, ans = -1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == X) {

ans = mid;

low = mid + 1;

} else if (arr[mid] < X) low = mid + 1;

else high = mid - 1;

return ans;

int countOccurrences(const vector<int>& arr, int X) {

int first = firstOccurrence(arr, X);

if (first == -1) return 0;

int last = lastOccurrence(arr, X);

return last - first + 1;

// Example usageint main() {

vector<int> arr = {1, 2, 2, 2, 3, 4};

int X = 2;

cout << "Count of " << X << ": " << countOccurrences(arr, X) << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Code Explanation

1.Use binary search to find the first occurrence of X.

2.Use binary search again to find the last occurrence of X.

3.If X is found, return last - first + 1 as the total count.

4.If not found, return 0.

PROBLEM:73

Question : Search in Rotated Sorted Array I

C++ Code (Binary Search on Rotated Array)

cpp

CopyEdit

#include <iostream>#include <vector>using namespace std;

int searchInRotatedSortedArray(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == X) return mid;

// Left half is sorted

if (arr[low] <= arr[mid]) {

if (arr[low] <= X && X < arr[mid])

high = mid - 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


else

low = mid + 1;

// Right half is sorted

else {

if (arr[mid] < X && X <= arr[high])

low = mid + 1;

else

high = mid - 1;

return -1;

// Example usageint main() {

vector<int> arr = {4, 5, 6, 7, 0, 1, 2};

int X = 0;

cout << "Index of " << X << ": " << searchInRotatedSortedArray(arr, X) << endl;

return 0;

� Code Explanation

1.Use binary search to find the mid-point in the rotated array.

2.Determine which half (left or right) is sorted.

3.Check if the target lies in that half and adjust search range.

4.Repeat until found or return -1 if the target is not proper

PROBLEM:74

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Search in Rotated Sorted Array II

C++ Code (Binary Search with Duplicate Handling)

cpp

#include <iostream>#include <vector>using namespace std;

bool search(const vector<int>& arr, int X) {

int low = 0, high = arr.size() - 1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == X) return true;

// Handle duplicates

if (arr[low] == arr[mid] && arr[mid] == arr[high]) {

++low;

--high;

// Left half is sorted

else if (arr[low] <= arr[mid]) {

if (arr[low] <= X && X < arr[mid])

high = mid - 1;

else

low = mid + 1;

// Right half is sorted

else {

if (arr[mid] < X && X <= arr[high])

low = mid + 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


else

high = mid - 1;

return false;

// Example usageint main() {

vector<int> arr = {2, 5, 6, 0, 0, 1, 2};

int X = 0;

cout << (search(arr, X) ? "Found" : "Not Found") << endl;

return 0;

� Code Explanation

1. Use binary search but handle duplicates by shrinking boundaries when low == mid ==
high.
2. Identify if the left or right half is sorted.
3. Narrow search range based on whether target X lies within the sorted half.
4. Return true if found, else continue; finally return false if not found.

PROBLEM:75

Question :Find Minimum in Rotated Sorted Array

C++ Code (Binary Search Approach)

cpp

#include <iostream>#include <vector>using namespace std;

int findMin(const vector<int>& arr) {

int low = 0, high = arr.size() - 1;

while (low < high) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int mid = low + (high - low) / 2;

// Minimum is in the unsorted half

if (arr[mid] > arr[high])

low = mid + 1;

else

high = mid;

return arr[low];

// Example usageint main() {

vector<int> arr = {4, 5, 6, 7, 0, 1, 2};

cout << "Minimum element is: " << findMin(arr) << endl;

return 0;

� Code Explanation

1.Use binary search to locate the pivot point (minimum element).

2.If arr[mid] > arr[high], minimum is in the right half.

3.Otherwise, it's in the left half or at mid, so move high = mid.

4.Loop ends when low == high, and arr[low] is the minimum.

PROBLEM:76

Question :Find Out How Many Times a Sorted Array Has Been Rotated

C++ Code (Binary Search Approach)

cpp

#include <iostream>#include <vector>using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int countRotations(const vector<int>& arr) {

int low = 0, high = arr.size() - 1;

while (low < high) {

int mid = low + (high - low) / 2;

// Minimum is in the unsorted half

if (arr[mid] > arr[high])

low = mid + 1;

else

high = mid;

return low; // Index of the minimum element = rotation count

// Example usageint main() {

vector<int> arr = {4, 5, 6, 7, 0, 1, 2};

cout << "Array is rotated " << countRotations(arr) << " times." << endl;

return 0;

� Code Explanation

1. Use binary search to find the index of the minimum element.


2. If arr[mid] > arr[high], minimum lies to the right.
3. Else, it lies to the left (or is at mid), so adjust high = mid.
4. Loop ends when low == high; the index low is the rotation

PROBLEM:77

Question : Single Element in a Sorted Array

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

using namespace std;

int singleNonDuplicate(const vector<int>& arr) {

int low = 0, high = arr.size() - 1;

while (low < high) {

int mid = low + (high - low) / 2;

// Make sure mid is even

if (mid % 2 == 1) mid--;

// Check the pair

if (arr[mid] == arr[mid + 1])

low = mid + 2; // unique is in right half

else

high = mid; // unique is in left half including mid

return arr[low];

// Example usageint main() {

vector<int> arr = {1, 1, 2, 2, 3, 4, 4, 5, 5};

cout << "Single element is: " << singleNonDuplicate(arr) << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation in 4 Lines

1.Use binary search and always keep mid even for pairing check.

2.If arr[mid] == arr[mid + 1], unique is in the right half.

3.Else, it's in the left half including mid.

4.Loop ends at the unique element, return arr[low].

PROBLEM:78

Question : Find Peak Element

C++ Code (Binary Search Approach)

cpp

#include <iostream>#include <vector>using namespace std;

int findPeakElement(const vector<int>& arr) {

int low = 0, high = arr.size() - 1;

while (low < high) {

int mid = low + (high - low) / 2;

// If the middle element is greater than its next element,

// peak lies on the left half or could be mid itself.

if (arr[mid] > arr[mid + 1])

high = mid;

else

low = mid + 1;

return arr[low]; // The peak element is at index 'low'

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Example usageint main() {

vector<int> arr = {1, 3, 20, 4, 1, 0};

cout << "Peak element is: " << findPeakElement(arr) << endl;

return 0;

� Code Explanation

1. Use binary search to reduce the search range for the peak.
2. If arr[mid] > arr[mid + 1], the peak lies in the left half or at mid.
3. Otherwise, the peak is in the right half.
4. When low == high, return arr[low] as the peak.

PROBLEM:79

Question : Find Square Root of a Number in O(log n)

C++ Code (Binary Search Approach)

cpp

#include <iostream>#include <cmath>using namespace std;

double squareRoot(int n) {

if (n == 0 || n == 1) return n;

double low = 0, high = n, mid;

double precision = 1e-6; // Desired precision

while (high - low > precision) {

mid = low + (high - low) / 2;

if (mid * mid == n) return mid; // Exact square root found

else if (mid * mid < n) low = mid; // Square root lies in the right half

else high = mid; // Square root lies in the left half

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return low; // The approximation is the square root of n

// Example usageint main() {

int n = 16;

cout << "Square root of " << n << " is: " << squareRoot(n) << endl;

return 0;

� Code Explanation

1. Use binary search between 0 and n to find the square root


2. In each iteration, compute mid = (low + high) / 2 and check if mid * mid ==
n.
3. If mid * mid < n, move the low pointer to mid, else move high to mid.
4. Loop continues until the difference between high and low is smaller than a
desired precision

PROBLEM:80

Question : Find the Nth Root of a Number Using Binary Search

C++ Code (Binary Search Approach)

cpp

CopyEdit

#include <iostream>

#include <cmath>

using namespace std;

double nthRoot(int x, int n) {

if (x == 0) return 0; // nth root of 0 is 0

double low = 0, high = x, mid;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


double precision = 1e-6; // Desired precision

while (high - low > precision) {

mid = low + (high - low) / 2;

// Check if mid^n is close enough to x

double midToThePower = pow(mid, n);

if (midToThePower == x) return mid;

else if (midToThePower < x) low = mid;

else high = mid;

return low; // Return the approximate value

// Example usageint main() {

int x = 16, n = 4;

cout << "The " << n << "th root of " << x << " is: " << nthRoot(x, n) << endl;

return 0;

� Code Explanation

1. Perform binary search between 0 and x to find the Nth root.


2. For each mid, compute mid^n using pow(mid, n) and check if it matches x.
3. If mid^n < x, adjust the search to the right half by setting low = mid.
4. Repeat until the difference between high and low is smaller than the desired
precision.

PROBLEM:81

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Koko Eating Bananas

C++ Code (Binary Search Approach)

cpp

#include <iostream>#include <vector>#include <cmath>using namespace std;

bool canEatAllBananas(const vector<int>& piles, int k, int h) {

int hours = 0;

for (int pile : piles) {

hours += (pile + k - 1) / k; // Equivalent to ceil(pile / k)

return hours <= h;

int minEatingSpeed(const vector<int>& piles, int h) {

int low = 1, high = *max_element(piles.begin(), piles.end()), mid;

int result = high;

while (low <= high) {

mid = low + (high - low) / 2;

if (canEatAllBananas(piles, mid, h)) {

result = mid;

high = mid - 1;

} else {

low = mid + 1;

return result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Example usageint main() {

vector<int> piles = {3, 6, 7, 11};

int h = 8;

cout << "Minimum speed required: " << minEatingSpeed(piles, h) << endl;

return 0;

� Code Explanation

1.Use binary search to find the minimum speed k by searching between 1 and the maximum
number of bananas in any pile.

2.For each candidate speed k, calculate if Koko can eat all piles in h hours using the
canEatAllBananas() function.

3.If Koko can finish within h hours, adjust the search to check for smaller speeds (high =
mid - 1).

4.Continue searching until the smallest speed k is found that allows Koko to eat all bananas
in time.

PROBLEM:82

Question : Minimum Days to Make M Bouquets

C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Function to check if we can make M bouquets in 'days' daysbool canMakeBouquets(const


vector<int>& bloom, int M, int k, int days) {

int count = 0, flowers = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int i = 0; i < bloom.size(); i++) {

if (bloom[i] <= days) {

flowers++;

if (flowers == k) {

count++;

flowers = 0;

} else {

flowers = 0;

return count >= M;

// Function to find minimum days to make M bouquetsint minDaysToMakeBouquets(const


vector<int>& bloom, int M, int k) {

int low = *min_element(bloom.begin(), bloom.end());

int high = *max_element(bloom.begin(), bloom.end());

int result = -1;

while (low <= high) {

int mid = low + (high - low) / 2;

if (canMakeBouquets(bloom, M, k, mid)) {

result = mid;

high = mid - 1; // try to find smaller days

} else {

low = mid + 1; // we need more days

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return result;

// Example usageint main() {

vector<int> bloom = {1, 10, 3, 10, 2};

int M = 3, k = 1;

cout << "Minimum days to make " << M << " bouquets: " <<
minDaysToMakeBouquets(bloom, M, k) << endl;

return 0;

� Code Explanation

1.The binary search is conducted between the minimum and maximum bloom times in the
array.

2.For each midpoint mid, the canMakeBouquets function checks if it is possible to make M
bouquets in mid days.

3.If it's possible to make M bouquets in mid days, adjust the binary search to check for a
smaller number of days by reducing the upper bound (high = mid - 1).

4.Continue the search until the smallest number of days is found that allows the formation of
M bouquets.

PROBLEM:83

Question : Find the Smallest Divisor

C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

#include <cmath>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to calculate the sum of elements after dividing by d and rounding upint
getSum(const vector<int>& nums, int d) {

int sum = 0;

for (int num : nums) {

sum += (num + d - 1) / d; // This is equivalent to ceiling(num / d)

return sum;

// Function to find the smallest divisorint smallestDivisor(const vector<int>& nums, int


threshold) {

int low = 1, high = *max_element(nums.begin(), nums.end()), mid;

int result = high;

while (low <= high) {

mid = low + (high - low) / 2;

if (getSum(nums, mid) <= threshold) {

result = mid; // We found a divisor that satisfies the condition

high = mid - 1; // Try to find a smaller divisor

} else {

low = mid + 1; // We need a larger divisor

return result;

// Example usageint main() {

vector<int> nums = {1, 2, 5, 9};

int threshold = 6;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Smallest divisor is: " << smallestDivisor(nums, threshold) << endl;

return 0;

� Code Explanation

1.Binary search is conducted between 1 and the maximum value in the array
to find the smallest divisor.

2.For each mid value (possible divisor), compute the sum of (nums[i] / mid) using the
getSum() function.

3.If the sum is less than or equal to the threshold, update the answer (result) and continue
searching for smaller divisors by adjusting the upper bound (high = mid - 1).

4.If the sum exceeds the threshold, we increase the divisor by adjusting the lower bound (low
= mid + 1).

PROBLEM:84

Question : Capacity to Ship Packages Within D Days

C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Function to check if it's possible to ship with a given capacity in D daysbool


canShipInDays(const vector<int>& weights, int capacity, int D) {

int days = 1, currentWeight = 0;

for (int weight : weights) {

currentWeight += weight;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// If current weight exceeds capacity, start a new day

if (currentWeight > capacity) {

days++;

currentWeight = weight; // start with the current package

return days <= D; // Can ship in D days?

// Function to find the minimum ship capacity required to ship in D daysint


shipWithinDays(const vector<int>& weights, int D) {

int low = *max_element(weights.begin(), weights.end());

int high = accumulate(weights.begin(), weights.end(), 0);

int result = high;

while (low <= high) {

int mid = low + (high - low) / 2;

if (canShipInDays(weights, mid, D)) {

result = mid; // Update result as this capacity can ship in D days

high = mid - 1; // Try for a smaller capacity

} else {

low = mid + 1; // Need a larger capacity

return result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Example usageint main() {

vector<int> weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int D = 5;

cout << "Minimum capacity to ship packages: " << shipWithinDays(weights, D) << endl;

return 0;

� Code Explanation

1.Binary search is performed between the maximum package weight (max(weights)) and
the total sum of weights (sum(weights)).

2.For each mid-value (capacity), the canShipInDays() function checks if it is possible to


ship all packages within D days without exceeding the capacity.

3.If it is possible to ship within D days, adjust the binary search to try for a smaller capacity
(high = mid - 1).

4.If it's not possible, increase the ship's capacity (low = mid + 1).

PROBLEM:85

Question : Kth Missing Positive Number

C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

using namespace std;

int findKthPositive(vector<int>& arr, int k) {

int left = 0, right = arr.size();

// Binary search to find the kth missing number

while (left < right) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int mid = left + (right - left) / 2;

// If the number of missing elements up to arr[mid] is less than k,

// we need to search on the right side (increasing the missing count)

if (arr[mid] - (mid + 1) < k) {

left = mid + 1;

} else {

right = mid;

// The missing number is k + left, because `left` represents the index

// after which we have exactly k missing numbers.

return left + k;

// Example usageint main() {

vector<int> arr = {2, 3, 4, 7, 11};

int k = 5;

cout << "The " << k << "th missing positive number is: " << findKthPositive(arr, k) << endl;

return 0;

� Code Explanation

1.Binary search is performed to find the position left in the array where the kth missing
positive number would fit.

2.The condition arr[mid] - (mid + 1) < k checks how many numbers are missing up to
the index mid. If fewer than k numbers are missing, the search continues on the right half.

3.Once the binary search concludes, the missing number is found at position left + k
because that many numbers are missing up to left.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


4.The result is the kth missing positive number.

PROBLEM:86

Question : Aggressive Cows

C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Function to check if it is possible to place cows with at least 'dist' distancebool


canPlaceCows(const vector<int>& stalls, int c, int dist) {

int count = 1, lastPos = stalls[0];

for (int i = 1; i < stalls.size(); i++) {

if (stalls[i] - lastPos >= dist) {

count++;

lastPos = stalls[i];

if (count == c) return true;

return false;

// Function to find the largest minimum distance between cowsint aggressiveCows(vector<int>&


stalls, int c) {

sort(stalls.begin(), stalls.end()); // Sort the stall positions

int low = 1, high = stalls.back() - stalls[0];

int result = -1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (low <= high) {

int mid = low + (high - low) / 2;

if (canPlaceCows(stalls, c, mid)) {

result = mid; // We can place cows with at least 'mid' distance

low = mid + 1; // Try for a larger distance

} else {

high = mid - 1; // Try for a smaller distance

return result;

// Example usageint main() {

vector<int> stalls = {1, 2, 8, 4, 9};

int c = 3;

cout << "The largest minimum distance is: " << aggressiveCows(stalls, c) << endl;

return 0;

� Code Explanation

1.Sort the stall positions to make sure we are placing cows in increasing order of stall
positions.

2.Binary search between the minimum possible distance (1) and the maximum possible
distance (distance between the first and last stall) to find the largest minimum distance.

3.For each mid (possible distance), use the canPlaceCows() function to check if it's possible
to place all cows with at least mid distance.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


4.Adjust the binary search range (low and high) based on whether placing cows with the
current mid distance is possible.

PROBLEM:87

Question : Book Allocation Problem

C++ Code (Binary Search Approach)

cpp

CopyEdit

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Function to check if it is possible to allocate books to students with 'maxPages' pagesbool


canAllocateBooks(const vector<int>& books, int m, int maxPages) {

int studentsRequired = 1, currentSum = 0;

for (int pages : books) {

currentSum += pages;

// If the current sum exceeds maxPages, assign the next book to the next student

if (currentSum > maxPages) {

studentsRequired++;

currentSum = pages; // Start with the current book

// If more students are needed than available, return false

if (studentsRequired > m) return false;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return true;

// Function to find the minimum maximum pages to allocate to a studentint bookAllocation(const


vector<int>& books, int m) {

int low = *max_element(books.begin(), books.end()); // The least possible max pages is the
max pages of a single book

int high = accumulate(books.begin(), books.end(), 0); // The highest possible max pages is the
total sum of all books

int result = high;

while (low <= high) {

int mid = low + (high - low) / 2;

if (canAllocateBooks(books, m, mid)) {

result = mid; // We can allocate books with 'mid' max pages, try for a smaller value

high = mid - 1; // Try for a smaller maximum

} else {

low = mid + 1; // We need a larger max number of pages

return result;

// Example usageint main() {

vector<int> books = {12, 34, 67, 90};

int m = 2;

cout << "Minimum pages the most burdened student will read: " << bookAllocation(books, m)
<< endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� Code Explanation

1. Binary search is performed between the largest single book's page count (max(books))
and the total sum of all books (sum(books)) to find the smallest maximum number of pages
any student will have to read.
2. For each midpoint mid, the function canAllocateBooks() checks if it's possible to assign
books to students such that no student reads more than mid pages.
3. If it's possible to allocate books with mid pages as the maximum, adjust the binary search
to check smaller values (high = mid - 1).
4. If it's not possible, we need to increase the number of pages allowed per student (low =
mid +1)

PROBLEM:88

Question : Split Array Largest Sum

C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

#include <numeric>

#include <algorithm>

using namespace std;

// Function to check if we can split the array into 'm' subarrays with a given max sumbool
canSplit(const vector<int>& nums, int m, int maxSum) {

int currentSum = 0, subarrays = 1;

for (int num : nums) {

currentSum += num;

if (currentSum > maxSum) {

subarrays++;

currentSum = num; // Start a new subarray with the current number

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

if (subarrays > m) return false;

return true;

// Function to find the smallest largest sum when splitting the array into 'm' subarraysint
splitArray(vector<int>& nums, int m) {

int low = *max_element(nums.begin(), nums.end()); // At least one subarray needs to be the


largest element

int high = accumulate(nums.begin(), nums.end(), 0); // The sum of all elements is the largest
sum

int result = high;

while (low <= high) {

int mid = low + (high - low) / 2;

if (canSplit(nums, m, mid)) {

result = mid; // We can split with 'mid' as the largest sum, try to minimize it

high = mid - 1; // Try for a smaller maximum sum

} else {

low = mid + 1; // We need a larger max sum to be able to split

return result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Example usageint main() {

vector<int> nums = {7, 2, 5, 10, 8};

int m = 2;

cout << "The smallest largest sum is: " << splitArray(nums, m) << endl;

return 0;

� Code Explanation

1.Binary search is performed between the maximum single element in the array (max(nums))
and the sum of all elements (sum(nums)) to find the smallest largest sum.

2.For each mid (potential largest subarray sum), the canSplit() function checks if it's
possible to split the array into m subarrays where each subarray's sum does not exceed mid.

3.If it's possible to split, we update the result and adjust the binary search to find a smaller
sum (high = mid - 1).

4.If it's not possible, we increase the allowed sum (low = mid + 1).

PROBLEM:89

Question : Painter's Partition Problem

C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

#include <numeric>

#include <algorithm>

using namespace std;

// Function to check if it's possible to allocate boards to painters with 'maxTime' time limitbool
canPaintBoards(const vector<int>& boards, int k, int maxTime) {

int paintersRequired = 1, currentSum = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int length : boards) {

currentSum += length;

// If the current sum exceeds maxTime, start a new painter

if (currentSum > maxTime) {

paintersRequired++;

currentSum = length; // Start with the current board

if (paintersRequired > k) return false;

return true;

// Function to find the minimum time required to paint all boardsint paintersPartition(const
vector<int>& boards, int k) {

int low = *max_element(boards.begin(), boards.end()); // At least one painter must handle the
largest board

int high = accumulate(boards.begin(), boards.end(), 0); // The total sum of all boards is the
highest possible time

int result = high;

while (low <= high) {

int mid = low + (high - low) / 2;

if (canPaintBoards(boards, k, mid)) {

result = mid; // We can paint with 'mid' as the maximum time, try for a smaller value

high = mid - 1; // Try for a smaller maximum time

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


} else {

low = mid + 1; // We need a larger maximum time to be able to split

return result;

// Example usageint main() {

vector<int> boards = {10, 20, 30, 40};

int k = 2;

cout << "The minimum time to paint all the boards is: " << paintersPartition(boards, k) <<
endl;

return 0;

� Code Explanation

1.Binary search is performed between the maximum board length (max(boards)) and the
sum of all board lengths (sum(boards)) to find the smallest maximum time.

2.For each midpoint mid, the canPaintBoards() function checks if it's possible to allocate
boards such that no painter works more than mid time.

3.If it's possible to paint all boards in mid time, we attempt to minimize the maximum time
(high = mid - 1).

4.If it's not possible, we increase the time (low = mid + 1).

PROBLEM:90

Question : Minimize Max Distance to Gas Station

C++ Code (Binary Search Approach)

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


CopyEdit

#include <iostream>

#include <vector>

#include <algorithm>

#include <cmath>

using namespace std;

// Function to check if it's possible to place 'k' gas stations such that the max distance is
'dist'bool canPlaceGasStations(const vector<int>& stations, int k, double dist) {

int count = 0;

// Iterate through the station positions

for (int i = 1; i < stations.size(); i++) {

// Calculate the distance between consecutive stations

double gap = stations[i] - stations[i - 1];

// Calculate how many new gas stations are needed to divide the gap into 'dist' intervals

count += (int)(gap / dist) - 1;

return count <= k;

// Function to find the minimum possible maximum distance between any two gas stationsdouble
minMaxGasDist(vector<int>& stations, int k) {

// Sort the positions of the stations

sort(stations.begin(), stations.end());

double low = 0.0, high = stations.back() - stations.front();

double result = high;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Binary search for the minimum maximum distance

while (high - low > 1e-6) {

double mid = low + (high - low) / 2;

if (canPlaceGasStations(stations, k, mid)) {

result = mid;

high = mid; // Try to minimize the max distance

} else {

low = mid; // Try to increase the max distance

return result;

// Example usageint main() {

vector<int> stations = {1, 2, 3, 4, 5};

int k = 1;

cout << "The minimum possible maximum distance is: " << minMaxGasDist(stations, k) <<
endl;

return 0;

� Code Explanation

1. Binary search is performed between the minimum possible distance (0) and the
maximum possible distance (stations.back() - stations.front()) to minimize the
maximum distance between consecutive gas stations.
2. For each midpoint mid, the canPlaceGasStations() function checks if it's possible to
insert k gas stations such that no gap between two consecutive stations exceeds mid.
3. If it's possible to place the new gas stations with mid as the maximum gap, the binary
search adjusts to find a smaller value (high = mid).
4. If it's not possible, the gap is increased (low = mid).

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:91

Question : Median of Two Sorted Arrays

C++ Code (Binary Search Approach)

cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Function to find the median of two sorted arrays

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {

if (nums1.size() > nums2.size()) {

swap(nums1, nums2); // Ensure nums1 is the smaller array

int n = nums1.size();

int m = nums2.size();

int low = 0, high = n;

while (low <= high) {

int partition1 = (low + high) / 2;

int partition2 = (n + m + 1) / 2 - partition1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Edge cases when partition1 or partition2 is at the ends of the arrays

int maxLeft1 = (partition1 == 0) ? INT_MIN : nums1[partition1 - 1];

int minRight1 = (partition1 == n) ? INT_MAX : nums1[partition1];

int maxLeft2 = (partition2 == 0) ? INT_MIN : nums2[partition2 - 1];

int minRight2 = (partition2 == m) ? INT_MAX : nums2[partition2];

if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {

// Found the correct partition

if ((n + m) % 2 == 0) {

return (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) / 2.0;

} else {

return max(maxLeft1, maxLeft2);

} else if (maxLeft1 > minRight2) {

// Move partition1 to the left

high = partition1 - 1;

} else {

// Move partition1 to the right

low = partition1 + 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


throw invalid_argument("Input arrays are not sorted.");

// Example usage

int main() {

vector<int> nums1 = {1, 3};

vector<int> nums2 = {2};

cout << "Median: " << findMedianSortedArrays(nums1, nums2) << endl;

vector<int> nums3 = {1, 2};

vector<int> nums4 = {3, 4};

cout << "Median: " << findMedianSortedArrays(nums3, nums4) << endl;

return 0;

Code Explanation

1.The algorithm first ensures that the first array (nums1) is always the smaller
array to optimize the binary search.

2.A binary search is performed on the smaller array (nums1), where we partition both arrays
such that the elements on the left side are smaller than the elements on the right.

3.If the partition is valid (i.e., all elements on the left are smaller than those on the right), we
compute the median based on whether the total length of the merged arrays is odd or even.

4.If the partition is invalid, adjust the binary search boundaries to find the correct partition.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:92

Question : Kth Element of Two Sorted Arrays

C++ Code (Binary Search Approach)

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Function to find the Kth element of two sorted arrays

int findKthElement(const vector<int>& nums1, const vector<int>& nums2, int k) {

// Ensure nums1 is the smaller array

if (nums1.size() > nums2.size()) {

return findKthElement(nums2, nums1, k);

int n = nums1.size();

int m = nums2.size();

int low = 0, high = min(n, k); // Binary search range for nums1

while (low <= high) {

int partition1 = (low + high) / 2;

int partition2 = k - partition1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Boundary conditions for nums1 and nums2

int maxLeft1 = (partition1 == 0) ? INT_MIN : nums1[partition1 - 1];

int minRight1 = (partition1 == n) ? INT_MAX : nums1[partition1];

int maxLeft2 = (partition2 == 0) ? INT_MIN : nums2[partition2 - 1];

int minRight2 = (partition2 == m) ? INT_MAX : nums2[partition2];

// Check if partition is correct

if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {

// The correct partition has been found

return max(maxLeft1, maxLeft2);

} else if (maxLeft1 > minRight2) {

// Move partition1 to the left

high = partition1 - 1;

} else {

// Move partition1 to the right

low = partition1 + 1;

throw invalid_argument("Input arrays are not sorted.");

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Example usage

int main() {

vector<int> nums1 = {1, 3, 8};

vector<int> nums2 = {7, 9, 10, 11};

int k = 5;

cout << "The " << k << "th smallest element is: " << findKthElement(nums1, nums2, k) <<
endl;

return 0;

Code Explanation in 4 Lines

1. Binary search is applied on the smaller array (nums1), and the partition index
(partition1) is adjusted based on the value of k to maintain a valid partition between both
arrays.
2. At each step, the algorithm compares elements at the partition boundaries to ensure that
the left side of the partition contains smaller elements than the right side.
3. If the partition is valid (i.e., the largest element on the left is smaller than the smallest
element on the right), the Kth element is found.
4. If the partition is not valid, the binary search continues to adjust the partition on nums1 by
modifying the search range (low and high).

PROBLEM:93

Question : Find the Row with Maximum Number of 1's

C++ Code

cpp

#include <iostream>

#include <vector>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to find the row with maximum number of 1's

int rowWithMax1s(vector<vector<int>>& matrix) {

int n = matrix.size();

int m = matrix[0].size();

int maxRowIndex = -1;

int maxOnes = -1;

// Start from the first row and the last column

int j = m - 1; // start from the last column

for (int i = 0; i < n; i++) {

// Move left if we encounter a 1

while (j >= 0 && matrix[i][j] == 1) {

j--;

// The number of 1's in the current row

int countOnes = m - 1 - j;

if (countOnes > maxOnes) {

maxOnes = countOnes;

maxRowIndex = i;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return maxRowIndex;

// Example usage

int main() {

vector<vector<int>> matrix = {

{0, 1, 1, 0},

{1, 1, 1, 1},

{0, 0, 1, 1}

};

cout << "Row with maximum number of 1's: " << rowWithMax1s(matrix) << endl;

return 0;

Code Explanation

1. Initialization: We initialize maxRowIndex and maxOnes to keep track of the row with the
maximum number of 1s.
2. Start from the last column: For each row, we begin from the last column and move left
if we encounter a 1.
3. Count the number of 1's: The number of 1s in a row is simply the number of columns to
the right of the last 1 we encounter.
4. Update the result: If the current row has more 1s than the previous maximum, we update
maxRowIndex and maxOnes.

PROBLEM:94

Question : Search in 2D Matrix

C++ Code

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <iostream>

#include <vector>

using namespace std;

// Function to search for the target in the 2D matrix

bool searchMatrix(vector<vector<int>>& matrix, int target) {

if (matrix.empty() || matrix[0].empty()) return false;

int n = matrix.size(); // number of rows

int m = matrix[0].size(); // number of columns

// Start from the top-right corner

int row = 0;

int col = m - 1;

while (row < n && col >= 0) {

if (matrix[row][col] == target) {

return true; // Target found

} else if (matrix[row][col] > target) {

col--; // Move left if current element is greater than target

} else {

row++; // Move down if current element is smaller than target

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return false; // If we exit the loop, the target is not in the matrix

// Example usage

int main() {

vector<vector<int>> matrix = {

{1, 4, 7, 11},

{2, 5, 8, 12},

{3, 6, 9, 16},

{10, 13, 14, 17}

};

int target = 5;

if (searchMatrix(matrix, target)) {

cout << "Target " << target << " is found in the matrix." << endl;

} else {

cout << "Target " << target << " is not found in the matrix." << endl;

return 0;

Code Explanation

1.We start from the top-right corner of the matrix (matrix[0][m-1]).

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2.If the current element is equal to the target, we return true.

3.If the current element is greater than the target, we move left by decreasing the column
index.

4.If the current element is smaller than the target, we move down by increasing the row index.
If the target is not found after traversing the matrix, we return false.

PROBLEM:95

Question : Search in a Row and Column Wise Sorted Matrix

C++ Code

cpp

#include <iostream>

#include <vector>

using namespace std;

// Function to search for the target in the matrix

bool searchMatrix(vector<vector<int>>& matrix, int target) {

if (matrix.empty() || matrix[0].empty()) return false;

int n = matrix.size(); // number of rows

int m = matrix[0].size(); // number of columns

// Start from the top-right corner of the matrix

int row = 0;

int col = m - 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (row < n && col >= 0) {

if (matrix[row][col] == target) {

return true; // Target found

} else if (matrix[row][col] > target) {

col--; // Move left if the current element is greater than target

} else {

row++; // Move down if the current element is smaller than target

return false; // Target not found

// Example usage

int main() {

vector<vector<int>> matrix = {

{1, 4, 7, 11},

{2, 5, 8, 12},

{3, 6, 9, 16},

{10, 13, 14, 17}

};

int target = 5;

if (searchMatrix(matrix, target)) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Target " << target << " is found in the matrix." << endl;

} else {

cout << "Target " << target << " is not found in the matrix." << endl;

return 0;

Code Explanation

1.Start from the top-right corner: The search begins at matrix[0][m-1], which
is the top-right corner.

2.If the current element is equal to the target, return true.

3.If the current element is greater than the target, move left by decrementing the column
index.

4.If the current element is smaller than the target, move down by incrementing the row
index. If no match is found, return false.

PROBLEM:96

Question : Find Peak Element in 2D Matrix

C++ Code

cpp

#include <iostream>

#include <vector>

using namespace std;

// Function to find the peak element in a 2D matrix

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int findPeakUtil(vector<vector<int>>& matrix, int low, int high, int n, int m) {

// Find the middle column

int mid = low + (high - low) / 2;

// Find the maximum element in the middle column

int maxRow = 0;

for (int i = 0; i < n; i++) {

if (matrix[i][mid] > matrix[maxRow][mid]) {

maxRow = i;

// Check if the middle element is a peak

if ((mid == 0 || matrix[maxRow][mid] >= matrix[maxRow][mid - 1]) &&

(mid == m - 1 || matrix[maxRow][mid] >= matrix[maxRow][mid + 1])) {

return matrix[maxRow][mid];

// If the left neighbor is greater, search the left half

if (mid > 0 && matrix[maxRow][mid - 1] > matrix[maxRow][mid]) {

return findPeakUtil(matrix, low, mid - 1, n, m);

// If the right neighbor is greater, search the right half

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return findPeakUtil(matrix, mid + 1, high, n, m);

// Wrapper function to call the recursive function

int findPeak(vector<vector<int>>& matrix) {

int n = matrix.size();

int m = matrix[0].size();

return findPeakUtil(matrix, 0, m - 1, n, m);

// Example usage

int main() {

vector<vector<int>> matrix = {

{10, 20, 15},

{21, 30, 14},

{7, 16, 32}

};

int peak = findPeak(matrix);

cout << "Peak element is: " << peak << endl;

return 0;

Code Explanation

1. The function findPeakUtil recursively divides the matrix by selecting a middle column
and finding the maximum element in that column.
2. If the middle element is greater than its neighbors, it is returned as the peak element.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


3. If the left neighbor is greater, we search in the left half of the matrix.
4. If the right neighbor is greater, we search in the right half of the matrix.

PROBLEM:97

Question : Matrix Median

C++ Code Implementation

cpp

CopyEdit

#include <iostream>

#include <vector>

using namespace std;

// Function to count how many numbers are <= mid in a rowint countLessEqual(const
vector<vector<int>>& matrix, int mid) {

int count = 0;

int n = matrix.size();

int m = matrix[0].size();

for (int i = 0; i < n; i++) {

// Use binary search to find the count of elements <= mid in the row

int low = 0, high = m;

while (low < high) {

int midCol = low + (high - low) / 2;

if (matrix[i][midCol] <= mid) {

low = midCol + 1;

} else {

high = midCol;

count += low;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return count;

// Function to find the median of the matrixint findMedian(vector<vector<int>>& matrix) {

int n = matrix.size();

int m = matrix[0].size();

int low = matrix[0][0]; // The smallest element in the matrix

int high = matrix[n - 1][m - 1]; // The largest element in the matrix

int desiredCount = (n * m + 1) / 2; // This is the middle element's position

while (low < high) {

int mid = low + (high - low) / 2;

// Count how many elements are <= mid

int count = countLessEqual(matrix, mid);

if (count < desiredCount) {

low = mid + 1; // We need to look for larger numbers

} else {

high = mid; // Mid could be the median, look for smaller or equal numbers

return low;

// Example usageint main() {

vector<vector<int>> matrix = {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


{1, 3, 5},

{2, 6, 9},

{3, 6, 9}

};

int median = findMedian(matrix);

cout << "Median is: " << median << endl;

return 0;

� Code Explanation

1. We define a helper function countLessEqual to count how many elements in the matrix
are less than or equal to a given value using binary search on each row.
2. The function findMedian performs binary search on the range from the smallest element
to the largest element of the matrix, adjusting the search space based on the count of elements
less than or equal to the middle value.
3. The desired median is the element at the position (n * m + 1) / 2 in the sorted list of
all elements in the matrix.
4. The binary search narrows down the median by progressively adjusting the low and high
bounds based on the count of elements in the current range.

PROBLEM:98

Question :Remove outermost Paranthesis

C++ Code Implementation

cpp

#include <iostream>

#include <string>

using namespace std;

string removeOuterParentheses(string s) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


string result = "";

int balance = 0;

for (char ch : s) {

if (ch == '(') {

if (balance > 0) result += ch; // Ignore outermost '('

balance++;

} else if (ch == ')') {

balance--;

if (balance > 0) result += ch; // Ignore outermost ')'

return result;

// Example usageint main() {

string s = "(()())(())";

cout << "Result: " << removeOuterParentheses(s) << endl;

return 0;

� Code Explanation

1. Use a balance variable to track nested parentheses, increasing on '(' and decreasing on
')'.
2. Add characters to the result only if they are not outermost parentheses.
3. Ignore the first '(' and last ')' of every primitive substring.
4. Return the modified string after removing outermost parentheses.

PROBLEM:99

Question : Reverse words in a given string / Palindrome Check

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code for Reversing Words

cpp

#include <iostream>

#include <sstream>

#include <vector>

using namespace std;

string reverseWords(string s) {

vector<string> words;

stringstream ss(s);

string word, result = "";

while (ss >> word) words.push_back(word); // Extract words

for (int i = words.size() - 1; i >= 0; i--) {

result += words[i] + (i == 0 ? "" : " ");

return result;

int main() {

string s = " Hello World! ";

cout << "Reversed: \"" << reverseWords(s) << "\"" << endl;

return 0;

� Code Explanation

1. Use stringstream to extract words, ignoring extra spaces.


2. Store words in a vector.
3. Traverse the vector in reverse order, adding words to the result string.
4. Return the reversed sentence.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1.

⏳ Time Complexity: O(n) (One pass for extraction, one for reversing).

� Space Complexity: O(n) (Storing words in a vector).

2️⃣ Palindrome Check


� Problem Statement

Check if a given string (ignoring case and non-alphanumeric characters) is a palindrome


(reads the same forward and backward).

Example

� Input: "A man, a plan, a canal: Panama"


� Output: true

✅ C++ Code for Palindrome Check

cpp

CopyEdit

#include <iostream>#include <cctype>using namespace std;

bool isPalindrome(string s) {

int left = 0, right = s.size() - 1;

while (left < right) {

while (left < right && !isalnum(s[left])) left++; // Ignore non-alphanumeric

while (left < right && !isalnum(s[right])) right--;

if (tolower(s[left]) != tolower(s[right])) return false; // Case insensitive check

left++, right--;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return true;

int main() {

string s = "A man, a plan, a canal: Panama";

cout << "Palindrome: " << (isPalindrome(s) ? "true" : "false") << endl;

return 0;

� Code Explanation

1. Use two pointers (left, right) to traverse from both ends.


2. Ignore non-alphanumeric characters.
3. Convert to lowercase and compare characters.
4. If all match, return true; otherwise, return false.

⏳ Time Complexity: O(n) (Single pass).

� Space Complexity: O(1) (In-place checks).

PROBLEM:100

Question : Largest Odd Number in a String

C++ Code Implementation

cpp

#include <iostream>using namespace std;

string largestOddNumber(string s) {

for (int i = s.size() - 1; i >= 0; i--) {

if ((s[i] - '0') % 2 == 1) // Check if the digit is odd

return s.substr(0, i + 1);

return ""; // No odd number found

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

string s = "4206";

cout << "Largest Odd Number: \"" << largestOddNumber(s) << "\"" << endl;

return 0;

� Code Explanation

1. Traverse the string from right to left.


2. Check for the first odd digit; return the substring up to that digit.
3. If no odd digit is found, return an empty string.
4. The largest odd number is simply the longest prefix ending at an odd digit.

1.

⏳ Time Complexity: O(n) (Scan the string once).

� Space Complexity: O(1) (No extra storage needed).

PROBLEM:101

Question : Longest Common Prefix

C++ Code Implementation

cpp

#include <iostream>

#include <vector>

using namespace std;

string longestCommonPrefix(vector<string>& strs) {

if (strs.empty()) return "";

string prefix = strs[0]; // Start with the first word

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int i = 1; i < strs.size(); i++) {

while (strs[i].find(prefix) != 0) { // Check if prefix is in the beginning

prefix = prefix.substr(0, prefix.size() - 1); // Shorten prefix

if (prefix.empty()) return "";

return prefix;

int main() {

vector<string> strs = {"flower", "flow", "flight"};

cout << "Longest Common Prefix: \"" << longestCommonPrefix(strs) << "\"" << endl;

return 0;

� Code Explanation

1.Start with the first string as the initial prefix.

2.Iterate through the words, trimming the prefix if it doesn't match the start of the current
word.

3.Keep shortening the prefix until a match is found or it's empty.

4.Return the longest matching prefix at the end.

⏳ Time Complexity: O(n × m) (where n = number of strings, m = average


length of strings).

� Space Complexity: O(1) (Modifying in place).

PROBLEM:102

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Isomorphic Strings

C++ Code Implementation


cpp

#include <iostream>

#include <unordered_map>

using namespace std;

bool isIsomorphic(string s, string t) {

if (s.length() != t.length()) return false;

unordered_map<char, char> s_to_t, t_to_s;

for (int i = 0; i < s.size(); i++) {

char c1 = s[i], c2 = t[i];

if ((s_to_t.count(c1) && s_to_t[c1] != c2) ||

(t_to_s.count(c2) && t_to_s[c2] != c1))

return false;

s_to_t[c1] = c2;

t_to_s[c2] = c1;

return true;

int main() {

string s = "egg", t = "add";

cout << (isIsomorphic(s, t) ? "true" : "false") << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Code Explanation in 4 Lines:


1. Use two hash maps to track character mappings from s → t and t → s.
2. Iterate through each character, checking if the mapping is consistent.
3. If any character is mapped to multiple different characters, return false.
4. If no mismatches are found, return true.

⏳ Time Complexity: O(n) (Single pass over the string).


� Space Complexity: O(1) (Only 256 possible characters).

PROBLEM:103

Question : Check if One String is a Rotation of Another

C++ Code Implementation


cpp

#include <iostream>

using namespace std;

bool isRotation(string s1, string s2) {

if (s1.length() != s2.length()) return false;

string concat = s1 + s1; // Concatenating s1 with itself

return concat.find(s2) != string::npos; // Check if s2 is a substring

int main() {

string s1 = "abcde", s2 = "cdeab";

cout << (isRotation(s1, s2) ? "true" : "false") << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Code Explanation in 4 Lines:


1. If the lengths differ, return false (rotations must have the same length).
2. Concatenate s1 with itself (this will contain all possible rotations).
3. Check if s2 exists as a substring in s1 + s1.
4. Return true if found, otherwise false.

⏳ Time Complexity: O(n) (Substring search in a string of


length 2n).
� Space Complexity: O(n) (Extra space for s1 + s1 ).
PROBLEM:104

Question : Check if Two Strings Are Anagrams


C++ Code Implementation
cpp

#include <iostream>

#include <algorithm>

using namespace std;

bool isAnagram(string s1, string s2) {

if (s1.length() != s2.length()) return false;

sort(s1.begin(), s1.end());

sort(s2.begin(), s2.end());

return s1 == s2;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

string s1 = "listen", s2 = "silent";

cout << (isAnagram(s1, s2) ? "true" : "false") << endl;

return 0;

� Code Explanation
1. Check if the lengths are equal, otherwise return false.
2. Sort both strings (Anagrams will have identical sorted order).
3. Compare the sorted versions of the strings.
4. If they match, return true, otherwise return false.

⏳ Time Complexity: O(n log n) (Sorting the strings).


� Space Complexity: O(1) (Sorting in-place).
� Optimized Approach Using Frequency Count (O(n) Time)

If you need an O(n) solution, use a frequency array instead of sorting:

cpp

#include <iostream>

#include <vector>

using namespace std;

bool isAnagram(string s1, string s2) {

if (s1.length() != s2.length()) return false;

vector<int> freq(26, 0);

for (int i = 0; i < s1.length(); i++) {

freq[s1[i] - 'a']++; // Count characters in s1

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


freq[s2[i] - 'a']--; // Remove characters in s2

for (int count : freq) {

if (count != 0) return false; // If any count is non-zero, not an anagram

return true;

int main() {

string s1 = "listen", s2 = "silent";

cout << (isAnagram(s1, s2) ? "true" : "false") << endl;

return 0;

� Optimized Approach Explanation:


1. Use a frequency array of size 26 (for lowercase letters).
2. Count character occurrences in s1 and decrease for s2.
3. If any frequency is non-zero, return false.
4. Otherwise, return true (strings are anagrams).

Time Complexity: O(n) (Single pass).

Space Complexity: O(1) (Fixed 26-size array).

PROBLEM:105

Question : Sort Characters by Frequency


C++ Code Implementation
cpp

#include <iostream>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <unordered_map>

#include <vector>

#include <algorithm>

using namespace std;

string frequencySort(string s) {

unordered_map<char, int> freq;

for (char c : s) freq[c]++; // Count character frequency

vector<pair<int, char>> chars;

for (auto& p : freq) chars.push_back({p.second, p.first}); // Store {freq, char}

sort(chars.rbegin(), chars.rend()); // Sort in descending order of frequency

string result = "";

for (auto& p : chars) result.append(p.first, p.second); // Append characters

return result;

int main() {

string s = "tree";

cout << "Sorted by frequency: " << frequencySort(s) << endl;

return 0;

� Code Explanation
1. Count frequency of each character using an unordered map.
2. Store frequency-character pairs in a vector.
3. Sort the vector in descending order based on frequency.
4. Rebuild the string by repeating characters according to their frequency.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


⏳ Time Complexity: O(n log n) (Sorting takes O(n log n) ,
counting takes O(n)).
� Space Complexity: O(n) (Storing frequency counts and
sorted results).
PROBLEM:106

Question : Maximum Nesting Depth of Paranthesis


C++ Code Implementation
cpp

#include <iostream>

using namespace std;

int maxDepth(string s) {

int depth = 0, maxDepth = 0;

for (char c : s) {

if (c == '(') {

depth++; // Increase depth when '(' is found

maxDepth = max(maxDepth, depth); // Update max depth

else if (c == ')') {

depth--; // Decrease depth when ')' is found

return maxDepth;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

string s = "((1+(2*3))+((8)/4))+1";

cout << "Maximum Nesting Depth: " << maxDepth(s) << endl;

return 0;

� Code Explanation
1. Use depth to track open parentheses (() and decrement it for closing ones ()).
2. Update maxDepth whenever a new max depth is reached.
3. Decrease depth on encountering ) to ensure balanced tracking.
4. Return the highest recorded depth at the end.

⏳ Time Complexity: O(n) (Single pass through the


string).
� Space Complexity: O(1) (Only a few integer variables
used).
PROBLEM:107

Question : Roman Number to Integer & Integer to Roman


1.Roman to Integer: Convert a Roman numeral string (e.g., "XIV") into an
integer (14).

2. Integer to Roman: Convert an integer (14) into its Roman numeral


representation ("XIV").

✅ C++ Code Implementation


1. Convert Roman Numeral to Integer

cpp

#include <iostream>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <unordered_map>

using namespace std;

int romanToInt(string s) {

unordered_map<char, int> roman = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},

{'C', 100}, {'D', 500}, {'M', 1000}};

int result = 0;

for (int i = 0; i < s.length(); i++) {

if (i < s.length() - 1 && roman[s[i]] < roman[s[i + 1]]) {

result -= roman[s[i]]; // Subtract smaller value if next is larger

} else {

result += roman[s[i]];

return result;

int main() {

string roman = "XIV";

cout << "Integer value: " << romanToInt(roman) << endl;

return 0;

2.Convert Integer to Roman Numeral

cpp

#include <iostream>

using namespace std;

string intToRoman(int num) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


pair<int, string> values[] = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},

{100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"},

{10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}};

string result = "";

for (auto& [value, symbol] : values) {

while (num >= value) {

result += symbol;

num -= value;

return result;

int main() {

int number = 14;

cout << "Roman numeral: " << intToRoman(number) << endl;

return 0;

� Code Explanation
1. Roman to Integer: Use a hash map to store values, traverse the string, and subtract
smaller values if a larger value follows.
2. Integer to Roman: Use a predefined list of Roman values, repeatedly subtracting the
largest possible value.
3. Loop through each Roman symbol until the number is reduced to zero.
4. Return the result after all conversions.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


⏳ Time Complexity:
Roman to Integer: O(n) (Single pass through the string).

Integer to Roman: O(1) (Max 13 operations for the largest number).

� Space Complexity: O(1) (Constant extra space used).


PROBLEM:108

Question : Implement atoi() Function


C++ Code Implementation
cpp

#include <iostream>

#include <climits> // For INT_MAX and INT_MINusing namespace std;

int myAtoi(string s) {

int i = 0, sign = 1;

long result = 0; // Use long to handle overflow before clamping

// 2!⃣ Ignore leading spaces

while (i < s.length() && s[i] == ' ') i++;

// 3!⃣ Check for optional '+' or '-'

if (i < s.length() && (s[i] == '+' || s[i] == '-')) {

sign = (s[i] == '-') ? -1 : 1;

i++;

// 4!⃣ Convert valid digits to an integer

while (i < s.length() && isdigit(s[i])) {

result = result * 10 + (s[i] - '0');

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// 5!⃣ Handle overflow

if (result * sign >= INT_MAX) return INT_MAX;

if (result * sign <= INT_MIN) return INT_MIN;

i++;

return sign * result;

int main() {

string s = " -42";

cout << "Converted Integer: " << myAtoi(s) << endl;

return 0;

� Code Explanation
1. Skip leading spaces and check for a sign (+ or -).
2. Convert numeric digits to an integer (result = result * 10 + digit).
3. Check for integer overflow and clamp the result to INT_MAX or INT_MIN.
4. Return the final result with the correct sign.

⏳ Time Complexity: O(n) (Single pass through the


string).
� Space Complexity: O(1) (Only a few integer variables
used).
PROBLEM:109

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Count Number of Substrings
C++ Code Implementation
1.Count All Substrings (Brute Force) – O(n²)

cpp

#include <iostream>

using namespace std;

int countSubstrings(string s) {

int n = s.length();

return (n * (n + 1)) / 2; // Total substrings formula

int main() {

string s = "abc";

cout << "Total substrings: " << countSubstrings(s) << endl;

return 0;

Explanation:

For a string of length n, the number of substrings is given by:

n(n+1)2\frac{n (n + 1)}{2}2n(n+1)​

For "abc" (n=3):"a", "b", "c", "ab", "bc", "abc" → Total: 6

2. Count Palindromic Substrings – O(n²)

cpp

#include <iostream>using namespace std;

int countPalindromicSubstrings(string s) {

int n = s.length(), count = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Expand from the center for both odd and even length palindromes

auto expand = [&](int left, int right) {

while (left >= 0 && right < n && s[left] == s[right]) {

count++;

left--; right++;

};

for (int i = 0; i < n; i++) {

expand(i, i); // Odd length palindromes

expand(i, i + 1); // Even length palindromes

return count;

int main() {

string s = "aaa";

cout << "Palindromic substrings: " << countPalindromicSubstrings(s) << endl;

return 0;

Explanation:

For "aaa", palindromic substrings are: "a", "a", "a", "aa", "aa", "aaa" → Total: 6

� Code Explanation
1.Total substrings is calculated using the formula O(1).

2.Palindromic substrings are counted using center expansion O(n²).

3.Expand around each character for both odd and even-length palindromes.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


4.Return the total count of substrings or palindromic substrings.

⏳ Time Complexity:
All substrings: O(1) (Mathematical formula).

Palindromic substrings: O(n²) (Center expansion method).

� Space Complexity: O(1) (Only a few integer variables


used).
PROBLEM:110

Question : Longest Palindromic Substring (Without DP)


C++ Code Implementation (Expand Around Center)
cpp

#include <iostream>

using namespace std;

string longestPalindrome(string s) {

int n = s.length();

if (n == 0) return "";

int start = 0, maxLength = 1;

// Function to expand around the center and find the longest palindrome

auto expand = [&](int left, int right) {

while (left >= 0 && right < n && s[left] == s[right]) {

if (right - left + 1 > maxLength) {

start = left;

maxLength = right - left + 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


left--; right++;

};

for (int i = 0; i < n; i++) {

expand(i, i); // Odd length palindrome

expand(i, i + 1); // Even length palindrome

return s.substr(start, maxLength);

int main() {

string s = "babad";

cout << "Longest Palindromic Substring: " << longestPalindrome(s) << endl;

return 0;

� Code Explanation
1. Expand from the center for both odd and even length palindromes.
2. Update maxLength and start indices whenever a longer palindrome is found.
3. Check each index as a potential center, expanding around it.
4. Return the longest palindromic substring found.

⏳ Time Complexity: O(n²) (Each character is expanded


up to O(n)).
� Space Complexity: O(1) (Only a few integer variables
used).
PROBLEM:111

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Sum of Beauty of All Substrings
C++ Code Implementation (Brute Force - O(n³))
cpp

#include <iostream>

#include <vector>

using namespace std;

int beautySum(string s) {

int n = s.length(), totalBeauty = 0;

// Generate all substrings

for (int i = 0; i < n; i++) {

vector<int> freq(26, 0); // Frequency array for characters

for (int j = i; j < n; j++) {

freq[s[j] - 'a']++; // Increment frequency of current character

int maxFreq = 0, minFreq = n;

for (int f : freq) {

if (f > 0) {

maxFreq = max(maxFreq, f);

minFreq = min(minFreq, f);

totalBeauty += (maxFreq - minFreq);

return totalBeauty;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

string s = "aabcb";

cout << "Sum of Beauty of All Substrings: " << beautySum(s) << endl;

return 0;

� Code Explanation in 4 Lines:


1. Generate all substrings using two nested loops.
2. Track character frequency using an array for the current substring.
3. Find max and min frequency in the substring.
4. Add the beauty value (maxFreq - minFreq) to the total sum.

⏳ Time Complexity: O(n³) (Nested loops to generate


substrings and compute frequencies).
� Space Complexity: O(1) (Fixed array for character
frequencies).
PROBLEM:112

Question : Reverse Every Word in a String


C++ Code Implementation
cpp

#include <iostream>

#include <sstream>

#include <algorithm>

using namespace std;

string reverseWords(string s) {

stringstream ss(s);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


string word, result = "";

while (ss >> word) {

reverse(word.begin(), word.end()); // Reverse individual word

if (!result.empty()) result += " ";

result += word;

return result;

int main() {

string s = "Hello World";

cout << "Reversed Words: " << reverseWords(s) << endl;

return 0;

� Code Explanation
1. Use stringstream to split words from the input string.
2. Reverse each word individually using reverse() function.
3. Maintain word order while appending reversed words to the result.
4. Return the final string with reversed words.

⏳ Time Complexity: O(n) (Each character is processed


once).
� Space Complexity: O(n) (Extra space for storing words).

PROBLEM:113

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Introduction to Linked List
A Linked List is a linear data structure in which elements (nodes) are linked using
pointers. Unlike arrays, linked lists do not require contiguous memory, making them
efficient for dynamic memory allocation.

� Structure of a Linked List Node in C++


Each node in a linked list contains:
1️⃣ Data – Stores the actual value.
2️⃣ Pointer (next) – Stores the address of the next node.

� C++ Representation Using struct

cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data; // Data stored in the node

Node* next; // Pointer to the next node

// Constructor to initialize a new node

Node(int value) {

data = value;

next = nullptr;

};

// Function to print linked listvoid printList(Node* head) {

while (head != nullptr) {

cout << head->data << " -> ";

head = head->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "NULL" << endl;

int main() {

// Creating nodes

Node* head = new Node(10);

head->next = new Node(20);

head->next->next = new Node(30);

// Printing Linked List

printList(head);

return 0;

� Key Concepts
1.struct Node – Defines the structure of a linked list node.

2.Pointer (next) – Links to the next node in the sequence.

3.Dynamic Memory Allocation – Nodes are created using new (stored in heap memory).

4.Traversing the List – Use a while loop to visit each node until nullptr.

⏳ Time Complexity
Creation: O(1) per node

Traversal: O(n)

PROBLEM:114

Question : Inserting a Node in a Linked List

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Insertion in a linked list can be done in three ways:
1️⃣ At the beginning (Head Insertion)
2️⃣ At the end (Tail Insertion)
3️⃣ At a specific position (Middle Insertion)

C++ Implementation of Inserting a Node


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

// Constructor

Node(int value) {

data = value;

next = nullptr;

};

// Function to insert at the beginningvoid insertAtHead(Node*& head, int value) {

Node* newNode = new Node(value);

newNode->next = head;

head = newNode;

// Function to insert at the endvoid insertAtTail(Node*& head, int value) {

Node* newNode = new Node(value);

if (!head) {

head = newNode;

return;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

Node* temp = head;

while (temp->next) temp = temp->next;

temp->next = newNode;

// Function to insert at a specific positionvoid insertAtPosition(Node*& head, int value, int pos)
{

if (pos == 1) {

insertAtHead(head, value);

return;

Node* temp = head;

for (int i = 1; temp != nullptr && i < pos - 1; i++)

temp = temp->next;

if (!temp) return; // If position is out of bounds

Node* newNode = new Node(value);

newNode->next = temp->next;

temp->next = newNode;

// Function to print the linked listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "NULL" << endl;

int main() {

Node* head = nullptr;

insertAtHead(head, 10);

insertAtTail(head, 20);

insertAtTail(head, 30);

insertAtPosition(head, 25, 3);

printList(head);

return 0;

� Key Points
1. Head Insertion (O(1)) – Adjust the head pointer to the new node.
2. Tail Insertion (O(n)) – Traverse to the last node and link a new node.
3. Middle Insertion (O(n)) – Traverse to the position and adjust pointers.

� Code Explanation:

1.Define a Node struct with data and a next pointer to link nodes dynamically.
2.Insert at head, tail, or a specific position by updating next pointers accordingly.
3.Traverse and print the list using a loop until NULL is reached.
4.In main(), create an empty list, insert nodes, and print the final linked list.

PROBLEM:115

Question : Deleting a Node in a Linked List

Deletion in a singly linked list can be done in three ways:


1️⃣ Delete the head (first node)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2️⃣ Delete the tail (last node)
3️⃣ Delete a node at a specific position

C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Function to delete the head nodevoid deleteHead(Node*& head) {

if (!head) return; // If list is empty

Node* temp = head;

head = head->next; // Move head to the next node

delete temp;

// Function to delete the last nodevoid deleteTail(Node*& head) {

if (!head) return;

if (!head->next) { // If only one node

delete head;

head = nullptr;

return;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

Node* temp = head;

while (temp->next->next) temp = temp->next; // Move to second last node

delete temp->next;

temp->next = nullptr;

// Function to delete node at a given positionvoid deleteAtPosition(Node*& head, int pos) {

if (!head) return;

if (pos == 1) {

deleteHead(head);

return;

Node* temp = head;

for (int i = 1; temp && i < pos - 1; i++)

temp = temp->next;

if (!temp || !temp->next) return; // If position is invalid

Node* toDelete = temp->next;

temp->next = temp->next->next;

delete toDelete;

// Function to print linked listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

cout << "NULL" << endl;

int main() {

Node* head = new Node(10);

head->next = new Node(20);

head->next->next = new Node(30);

head->next->next->next = new Node(40);

cout << "Original List: ";

printList(head);

deleteHead(head);

cout << "After deleting head: ";

printList(head);

deleteTail(head);

cout << "After deleting tail: ";

printList(head);

deleteAtPosition(head, 2);

cout << "After deleting position 2: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)
1️⃣ Delete the head by moving head to head->next and freeing the old node.
2️⃣ Delete the tail by traversing to the second last node and setting next = nullptr.
3️⃣ Delete a node at a specific position by adjusting pointers and freeing memory.
4️⃣ Print the linked list after each deletion to verify the changes.

� Output
Original List: 10 -> 20 -> 30 -> 40 -> NULL

After deleting head: 20 -> 30 -> 40 -> NULL

After deleting tail: 20 -> 30 -> NULL

After deleting position 2: 20 -> NULL

PROBLEM:116

Question : Find the Length of a Linked List (Using


Traversal)
C++ Code Implementation
cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Function to find the length of a linked listint getLength(Node* head) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int count = 0;

while (head) { // Traverse until we reach NULL

count++;

head = head->next;

return count;

// Function to print linked listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(10);

head->next = new Node(20);

head->next->next = new Node(30);

head->next->next->next = new Node(40);

printList(head);

cout << "Length of the linked list: " << getLength(head) << endl;

return 0;

� Code Explanation in 4 Lines:


The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)
1️⃣ Start from the head and initialize count = 0.
2️⃣ Traverse each node using a loop while head != NULL, incrementing count.
3️⃣ When traversal ends, return the final count.
4️⃣ Print the linked list and its length in main().

� Output
10 -> 20 -> 30 -> 40 -> NULL

Length of the linked list: 4

⏳ Time Complexity
Traversal takes O(n) since we visit each node once.

PROBLEM:117

Question : Searching an Element in a Linked List

C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Function to search an element in the linked listbool search(Node* head, int key) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (head) { // Traverse until NULL

if (head->data == key)

return true; // Found the element

head = head->next;

return false; // Element not found

// Function to print linked listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(10);

head->next = new Node(20);

head->next->next = new Node(30);

head->next->next->next = new Node(40);

printList(head);

int key = 30;

if (search(head, key))

cout << key << " is found in the linked list." << endl;

else

cout << key << " is not found in the linked list." << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Code Explanation in 4 Lines:


1️⃣ Traverse the list from head to tail using a while loop.
2️⃣ Compare each node's value with the search key.
3️⃣ If a match is found, return true; otherwise, continue traversal.
4️⃣ If the loop ends, return false (element not found).

� Output
10 -> 20 -> 30 -> 40 -> NULL30 is found in the linked list.

⏳ Time Complexity
Best case O(1) (if found at head).

Worst case O(n) (if not found or at the end).

PROBLEM:118

Question : Introduction to Doubly Linked List (DLL)

A Doubly Linked List (DLL) is a type of linked list where each node contains two pointers:

One pointer points to the next node.

Another pointer points to the previous node.

This allows bi-directional traversal (both forward and backward).

Doubly Linked List Node Representation in C++


cpp

#include <iostream>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Structure of a Doubly Linked List Nodestruct Node {

int data; // Stores the value

Node* next; // Pointer to next node

Node* prev; // Pointer to previous node

// Constructor to initialize a new node

Node(int value) {

data = value;

next = nullptr;

prev = nullptr;

};

� Explanation of Node Structure


1️⃣ Each node stores an integer data (value of the node).
2️⃣ Two pointers are used: next (points to next node) and prev (points to previous node).
3️⃣ A constructor initializes the node with data, setting next and prev to nullptr.
4️⃣ This allows bidirectional traversal, unlike singly linked lists (SLL).

Visual Representation of a Doubly Linked List


NULL <- [10] <-> [20] <-> [30] -> NULL

prev pointer helps in backward traversal.

next pointer helps in forward traversal.

⏳ Time Complexity of DLL Operations


Operation Time Complexity

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Operation Time Complexity

Insert at head O(1)

Insert at tail O(1)

Delete a node O(1) (if pointer is given)

Search an element O(n)

Forward traversal O(n)

Backward traversal O(n)

� DLL is useful when you need quick deletions and bidirectional access

PROBLEM:119

Question : Insert a Node in a Doubly Linked List (DLL)

Insertion in a Doubly Linked List (DLL) can be done in three ways:


1️⃣ At the beginning (head)
2️⃣ At the end (tail)
3️⃣ At a specific position

✅ C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structure for DLLstruct Node {

int data;

Node* next;

Node* prev;

Node(int value) {

data = value;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


next = nullptr;

prev = nullptr;

};

// Insert at the beginning of DLLvoid insertAtHead(Node*& head, int value) {

Node* newNode = new Node(value);

if (head) {

newNode->next = head;

head->prev = newNode;

head = newNode;

// Insert at the end of DLLvoid insertAtTail(Node*& head, int value) {

Node* newNode = new Node(value);

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) temp = temp->next;

temp->next = newNode;

newNode->prev = temp;

// Insert at a specific position in DLLvoid insertAtPosition(Node*& head, int pos, int value) {

if (pos == 1) {

insertAtHead(head, value);

return;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* newNode = new Node(value);

Node* temp = head;

for (int i = 1; temp && i < pos - 1; i++)

temp = temp->next;

if (!temp) return; // Invalid position

newNode->next = temp->next;

if (temp->next) temp->next->prev = newNode;

temp->next = newNode;

newNode->prev = temp;

// Function to print DLLvoid printList(Node* head) {

while (head) {

cout << head->data << " <-> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = nullptr;

insertAtHead(head, 10);

insertAtHead(head, 20);

insertAtTail(head, 30);

insertAtPosition(head, 2, 25);

printList(head); // Output: 20 <-> 25 <-> 10 <-> 30 <-> NULL

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Code Explanation in 4 Lines:


1️⃣ Insert at head: Update next of new node and prev of old head.
2️⃣ Insert at tail: Traverse to last node, update next and prev pointers.
3️⃣ Insert at position: Traverse to (pos-1) node, adjust next and prev links.
4️⃣ Print the list to verify the structure.

� Output
20 <-> 25 <-> 10 <-> 30 <-> NULL

⏳ Time Complexity

Operation Time Complexity

Insert at head O(1)

Insert at tail O(n)

Insert at position O(n)

PROBLEM:120
The PDF created by Abhishek Rathor (Instagram:SYNTAX
ERROR)

Question : Deleting a Node in a Doubly Linked List (DLL)

Deletion in a Doubly Linked List (DLL) can be done in three ways:


1️⃣ Delete the head (first node)
2️⃣ Delete the tail (last node)
3️⃣ Delete a node at a specific position

✅ C++ Code Implementation


cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <iostream>

using namespace std;

// Node structure for DLLstruct Node {

int data;

Node* next;

Node* prev;

Node(int value) {

data = value;

next = nullptr;

prev = nullptr;

};

// Function to delete the head nodevoid deleteHead(Node*& head) {

if (!head) return; // If list is empty

Node* temp = head;

head = head->next; // Move head to next node

if (head) head->prev = nullptr;

delete temp;

// Function to delete the last nodevoid deleteTail(Node*& head) {

if (!head) return; // If list is empty

if (!head->next) { // If only one node

delete head;

head = nullptr;

return;

Node* temp = head;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (temp->next) temp = temp->next; // Move to last node

temp->prev->next = nullptr;

delete temp;

// Function to delete a node at a specific positionvoid deleteAtPosition(Node*& head, int pos) {

if (!head) return;

if (pos == 1) {

deleteHead(head);

return;

Node* temp = head;

for (int i = 1; temp && i < pos; i++)

temp = temp->next;

if (!temp) return; // Invalid position

temp->prev->next = temp->next;

if (temp->next) temp->next->prev = temp->prev;

delete temp;

// Function to print DLLvoid printList(Node* head) {

while (head) {

cout << head->data << " <-> ";

head = head->next;

cout << "NULL" << endl;

int main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* head = new Node(10);

head->next = new Node(20);

head->next->prev = head;

head->next->next = new Node(30);

head->next->next->prev = head->next;

cout << "Original List: ";

printList(head);

deleteHead(head);

cout << "After deleting head: ";

printList(head);

deleteTail(head);

cout << "After deleting tail: ";

printList(head);

deleteAtPosition(head, 1);

cout << "After deleting position 1: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Delete the head: Move head to head->next and update prev pointer.
2️⃣ Delete the tail: Traverse to the last node and adjust prev->next.
3️⃣ Delete a specific position: Adjust prev->next and next->prev pointers.
4️⃣ Print the list to verify changes after deletion.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Output
Original List: 10 <-> 20 <-> 30 <-> NULLAfter deleting head: 20 <-> 30 <-> NULLAfter
deleting tail: 20 <-> NULLAfter deleting position 1: NULL

⏳ Time Complexity

Operation Time Complexity

Delete head O(1)

Delete tail O(n)

Delete at position O(n)

PROBLEM:121

Question : Reverse a Doubly Linked List (DLL)

Reversing a Doubly Linked List (DLL) involves swapping the next and prev pointers for
every node.

C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structure for DLLstruct Node {

int data;

Node* next;

Node* prev;

Node(int value) {

data = value;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


next = nullptr;

prev = nullptr;

};

// Function to reverse a DLLvoid reverseDLL(Node*& head) {

Node* current = head;

Node* temp = nullptr;

while (current) {

// Swap next and prev pointers

temp = current->prev;

current->prev = current->next;

current->next = temp;

// Move to the next node in the original list

current = current->prev;

// Update the head to the last node (previously the tail)

if (temp)

head = temp->prev;

// Function to print DLLvoid printList(Node* head) {

while (head) {

cout << head->data << " <-> ";

head = head->next;

cout << "NULL" << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

Node* head = new Node(10);

head->next = new Node(20);

head->next->prev = head;

head->next->next = new Node(30);

head->next->next->prev = head->next;

cout << "Original List: ";

printList(head);

reverseDLL(head);

cout << "Reversed List: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Traverse each node and swap its next and prev pointers.
2️⃣ Move current to prev (since next and prev are swapped).
3️⃣ After traversal, update head to the last node.
4️⃣ Print the list before and after reversal.

� Output
Original List: 10 <-> 20 <-> 30 <-> NULL

Reversed List: 30 <-> 20 <-> 10 <-> NULL

⏳ Time Complexity

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Operation Time Complexity

Reverse DLL O(n)

PROBLEM:122

Question : Find the Middle of a Linked List (Tortoise-


Hare Method)
The Tortoise-Hare Method (Slow & Fast Pointer Approach) is an efficient way to find the
middle of a Singly Linked List in O(n) time and O(1) space.

C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structure for Linked Liststruct Node {

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Function to find the middle of the Linked ListNode* findMiddle(Node* head) {

if (!head) return nullptr; // If list is empty

Node* slow = head; // Moves one step at a time

Node* fast = head; // Moves two steps at a time

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (fast && fast->next) {

slow = slow->next; // Move slow by 1 step

fast = fast->next->next; // Move fast by 2 steps

return slow; // Slow is now at the middle

// Function to print Linked Listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(1);

head->next = new Node(2);

head->next->next = new Node(3);

head->next->next->next = new Node(4);

head->next->next->next->next = new Node(5);

cout << "Original List: ";

printList(head);

Node* middle = findMiddle(head);

if (middle) cout << "Middle Node: " << middle->data << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation in 4 Lines:
1️⃣ Use two pointers: slow moves one step, fast moves two steps.
2️⃣ When fast reaches the end, slow is at the middle of the list.
3️⃣ If the list has an even number of nodes, slow points to the second middle node.
4️⃣ Print the middle node's value after traversal.

� Output
Original List: 1 -> 2 -> 3 -> 4 -> 5 -> NULL

Middle Node: 3

⏳ Time Complexity

Operation Time Complexity

Find Middle O(n)

PROBLEM:123

Question : Reverse a Singly Linked List (Iterative


Approach)
C++ Code Implementation
cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int value) {

data = value;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


next = nullptr;

};

// Iterative function to reverse a Linked ListNode* reverseList(Node* head) {

Node* prev = nullptr;

Node* curr = head;

while (curr) {

Node* nextNode = curr->next; // Save next node

curr->next = prev; // Reverse pointer

prev = curr; // Move prev ahead

curr = nextNode; // Move curr ahead

return prev; // New head

// Function to print the listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(1);

head->next = new Node(2);

head->next->next = new Node(3);

head->next->next->next = new Node(4);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Original List: ";

printList(head);

head = reverseList(head);

cout << "Reversed List: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Initialize prev as NULL, and curr as head.
2️⃣ For each node, store next, reverse curr->next to point to prev.
3️⃣ Move prev and curr one step forward.
4️⃣ Finally, return prev as the new head.

� Output
Original List: 1 -> 2 -> 3 -> 4 -> NULL

Reversed List: 4 -> 3 -> 2 -> 1 -> NULL

PROBLEM:124

Question : Reverse a Singly Linked List (Recursive Approach)

C++ Code Implementation


cpp

#include <iostream>using namespace std;

// Node structurestruct Node {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Recursive function to reverse a linked listNode* reverseRecursive(Node* head) {

if (!head || !head->next) return head; // Base case

Node* newHead = reverseRecursive(head->next); // Reverse the rest

head->next->next = head; // Point next node's next to current

head->next = nullptr; // Set current node's next to null

return newHead; // Return new head

// Function to print the listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(1);

head->next = new Node(2);

head->next->next = new Node(3);

head->next->next->next = new Node(4);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Original List: ";

printList(head);

head = reverseRecursive(head);

cout << "Reversed List: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Base case: If head is NULL or one node, return it.
2️⃣ Recursively reverse the rest of the list.
3️⃣ Make the next node point back to current: head->next->next = head.
4️⃣ Set head->next = NULL and return the new head.

� Output
Original List: 1 -> 2 -> 3 -> 4 -> NULL

Reversed List: 4 -> 3 -> 2 -> 1 -> NULL

PROBLEM:125

Question : Detect a Loop in a Linked List (Floyd’s Cycle Detection Algorithm)

C++ Code Implementation


cpp

#include <iostream>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Node structurestruct Node {

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Function to detect loop in linked listbool hasCycle(Node* head) {

Node* slow = head;

Node* fast = head;

while (fast && fast->next) {

slow = slow->next; // Move slow by 1

fast = fast->next->next; // Move fast by 2

if (slow == fast) return true; // Cycle detected

return false; // No cycle

// Function to create a loop for testingvoid createLoop(Node* head, int pos) {

if (pos == -1) return;

Node* temp = head;

Node* loopNode = nullptr;

int count = 0;

while (temp->next) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (count == pos) loopNode = temp;

temp = temp->next;

count++;

temp->next = loopNode;

int main() {

Node* head = new Node(1);

head->next = new Node(2);

head->next->next = new Node(3);

head->next->next->next = new Node(4);

head->next->next->next->next = new Node(5);

createLoop(head, 1); // Creates a loop at node with value 2

if (hasCycle(head))

cout << "Loop detected!" << endl;

else

cout << "No loop." << endl;

return 0;

� Code Explanation in 4 Lines:


1️⃣ Initialize slow and fast pointers to head.
2️⃣ Move slow by 1 and fast by 2 steps in a loop.
3️⃣ If slow == fast, a loop exists.
4️⃣ If loop ends without match, there’s no cycle.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Output
Loop detected!

PROBLEM:126

Question : Find the Starting Point of a Loop in a Linked List

C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Detects loop and returns meeting point (if any)Node* detectCycle(Node* head) {

Node* slow = head;

Node* fast = head;

while (fast && fast->next) {

slow = slow->next;

fast = fast->next->next;

if (slow == fast) return slow; // Loop detected

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return nullptr; // No loop

// Function to find start of the loopNode* findStartOfLoop(Node* head) {

Node* intersection = detectCycle(head);

if (!intersection) return nullptr; // No loop

Node* start = head;

while (start != intersection) {

start = start->next;

intersection = intersection->next;

return start;

// Function to create a loop for testingvoid createLoop(Node* head, int pos) {

if (pos == -1) return;

Node* temp = head;

Node* loopNode = nullptr;

int count = 0;

while (temp->next) {

if (count == pos) loopNode = temp;

temp = temp->next;

count++;

temp->next = loopNode;

int main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* head = new Node(3);

head->next = new Node(2);

head->next->next = new Node(0);

head->next->next->next = new Node(-4);

createLoop(head, 1); // Creates loop at node with value 2

Node* loopStart = findStartOfLoop(head);

if (loopStart)

cout << "Loop starts at node with value: " << loopStart->data << endl;

else

cout << "No loop detected." << endl;

return 0;

� Code Explanation in 4 Lines:


1️⃣ Use Floyd’s cycle detection to get the intersection point in the loop.
2️⃣ Initialize a new pointer at head, and keep the other at the intersection.
3️⃣ Move both pointers one step at a time until they meet.
4️⃣ The meeting point is the starting node of the loop.

� Output
Loop starts at node with value: 2

PROBLEM:127

Question : Find the Length of a Loop in a Linked List

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code Implementation
cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

// Function to detect cycle and return meeting nodeNode* detectCycle(Node* head) {

Node* slow = head;

Node* fast = head;

while (fast && fast->next) {

slow = slow->next;

fast = fast->next->next;

if (slow == fast) return slow; // Cycle found

return nullptr;

// Function to find length of the loopint loopLength(Node* head) {

Node* meetingPoint = detectCycle(head);

if (!meetingPoint) return 0; // No loop

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int length = 1;

Node* temp = meetingPoint->next;

while (temp != meetingPoint) {

length++;

temp = temp->next;

return length;

// Helper to create a loopvoid createLoop(Node* head, int pos) {

if (pos == -1) return;

Node* temp = head;

Node* loopNode = nullptr;

int count = 0;

while (temp->next) {

if (count == pos) loopNode = temp;

temp = temp->next;

count++;

temp->next = loopNode;

int main() {

Node* head = new Node(10);

head->next = new Node(20);

head->next->next = new Node(30);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


head->next->next->next = new Node(40);

head->next->next->next->next = new Node(50);

createLoop(head, 2); // Create loop starting at node with value 30

int len = loopLength(head);

if (len)

cout << "Loop length is: " << len << endl;

else

cout << "No loop detected." << endl;

return 0;

� Code Explanation in 4 Lines:


1️⃣ Use Floyd’s algorithm to detect the cycle and get the meeting node.
2️⃣ From the meeting node, start moving one step at a time.
3️⃣ Count steps until you return to the meeting node.
4️⃣ That count is the length of the loop.

� Output
Loop length is: 3

PROBLEM:128

Question : Check if a Linked List is a Palindrome

To check if a linked list is a palindrome, we:

1. Find the middle of the list,


2. Reverse the second half,

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


3. Compare both halves.

✅ C++ Code Implementation


cpp

#include <iostream>using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

// Function to reverse a linked listNode* reverse(Node* head) {

Node* prev = nullptr;

while (head) {

Node* nextNode = head->next;

head->next = prev;

prev = head;

head = nextNode;

return prev;

// Function to check if list is palindromebool isPalindrome(Node* head) {

if (!head || !head->next) return true;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Step 1: Find middle using slow-fast

Node* slow = head;

Node* fast = head;

while (fast->next && fast->next->next) {

slow = slow->next;

fast = fast->next->next;

// Step 2: Reverse second half

Node* secondHalf = reverse(slow->next);

// Step 3: Compare both halves

Node* firstHalf = head;

Node* temp = secondHalf;

while (temp) {

if (firstHalf->data != temp->data)

return false;

firstHalf = firstHalf->next;

temp = temp->next;

return true;

int main() {

Node* head = new Node(1);

head->next = new Node(2);

head->next->next = new Node(2);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


head->next->next->next = new Node(1);

if (isPalindrome(head))

cout << "Linked List is a Palindrome." << endl;

else

cout << "Linked List is NOT a Palindrome." << endl;

return 0;

� Code Explanation in 4 Lines:


1️⃣ Use slow-fast pointers to reach the middle of the list.
2️⃣ Reverse the second half of the list.
3️⃣ Compare both halves node by node.
4️⃣ If all nodes match, it's a palindrome; otherwise, it's not.

� Output
Linked List is a Palindrome.

PROBLEM:129

Question : Segregate Odd and Even Nodes in a Linked List

Rearrange the linked list such that all odd-positioned nodes (not values) come before even-
positioned nodes, maintaining their original relative order.

✅ C++ Code Implementation


cpp

#include <iostream>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

// Function to segregate odd and even positioned nodesNode* segregateOddEven(Node* head) {

if (!head || !head->next) return head;

Node* odd = head;

Node* even = head->next;

Node* evenStart = even;

while (even && even->next) {

odd->next = even->next;

odd = odd->next;

even->next = odd->next;

even = even->next;

odd->next = evenStart; // Attach even list at end of odd list

return head;

// Function to print listvoid printList(Node* head) {

while (head) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(1);

head->next = new Node(2);

head->next->next = new Node(3);

head->next->next->next = new Node(4);

head->next->next->next->next = new Node(5);

cout << "Original List: ";

printList(head);

head = segregateOddEven(head);

cout << "Modified List: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Use two pointers: one for odd nodes, one for even.
2️⃣ Link odd nodes skipping even ones and move the odd pointer.
3️⃣ Do the same for even nodes.
4️⃣ After loop, attach even list after the last odd node.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Output
Original List: 1 -> 2 -> 3 -> 4 -> 5 -> NULL

Modified List: 1 -> 3 -> 5 -> 2 -> 4 -> NULL

PROBLEM:130

Question : Remove N-th Node from the End of a Linked List

To remove the N-th node from the end, we use the two-pointer approach:
1️⃣ Move the first pointer N steps ahead.
2️⃣ Move both pointers one step at a time until the first pointer reaches the end.
3️⃣ The second pointer will now be at the node just before the one to be deleted.

✅ C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

// Function to remove N-th node from endNode* removeNthFromEnd(Node* head, int n) {

Node* dummy = new Node(0);

dummy->next = head;

Node* first = dummy;

Node* second = dummy;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Move first pointer `n+1` steps ahead

for (int i = 0; i <= n; i++) {

first = first->next;

// Move both pointers until first reaches end

while (first) {

first = first->next;

second = second->next;

// Delete the nth node

Node* toDelete = second->next;

second->next = second->next->next;

delete toDelete;

return dummy->next; // Return new head

// Function to print listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(1);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


head->next = new Node(2);

head->next->next = new Node(3);

head->next->next->next = new Node(4);

head->next->next->next->next = new Node(5);

cout << "Original List: ";

printList(head);

head = removeNthFromEnd(head, 2); // Remove 2nd node from end

cout << "Modified List: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Move the first pointer n+1 steps ahead.
2️⃣ Move both pointers until the first reaches NULL.
3️⃣ The second pointer stops just before the node to delete.
4️⃣ Delete the node and adjust the links.

� Output
Original List: 1 -> 2 -> 3 -> 4 -> 5 -> NULL

Modified List: 1 -> 2 -> 3 -> 5 -> NULL

PROBLEM:131
The PDF created by Abhishek Rathor (Instagram:SYNTAX
ERROR)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question : Sorting a Linked List (Merge Sort Approach)
Sorting a linked list efficiently requires Merge Sort, as it works well with linked lists and has
a time complexity of O(N log N).

Approach:

1️⃣ Find the middle of the list using the slow-fast pointer method.
2️⃣ Recursively sort both halves.
3️⃣ Merge the two sorted halves using the two-pointer technique.

✅ C++ Code Implementation


cpp

#include <iostream>using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

// Function to merge two sorted linked listsNode* merge(Node* left, Node* right) {

if (!left) return right;

if (!right) return left;

Node* result = nullptr;

if (left->data <= right->data) {

result = left;

result->next = merge(left->next, right);

} else {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


result = right;

result->next = merge(left, right->next);

return result;

// Function to find the middle nodeNode* findMiddle(Node* head) {

Node* slow = head;

Node* fast = head->next; // To ensure we pick the correct middle in even-length lists

while (fast && fast->next) {

slow = slow->next;

fast = fast->next->next;

return slow;

// Merge Sort functionNode* mergeSort(Node* head) {

if (!head || !head->next) return head; // Base case

Node* mid = findMiddle(head);

Node* left = head;

Node* right = mid->next;

mid->next = nullptr; // Split the list

left = mergeSort(left);

right = mergeSort(right);

return merge(left, right);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to print listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(4);

head->next = new Node(2);

head->next->next = new Node(1);

head->next->next->next = new Node(3);

cout << "Original List: ";

printList(head);

head = mergeSort(head);

cout << "Sorted List: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Find the middle of the list to split it into two halves.
2️⃣ Recursively sort both halves using Merge Sort.
3️⃣ Merge the two sorted halves back together.
4️⃣ The final merged list is fully sorted.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Output
Original List: 4 -> 2 -> 1 -> 3 -> NULL

Sorted List: 1 -> 2 -> 3 -> 4 -> NULL

PROBLEM:132

Question : Sort a Linked List of 0’s, 1’s, and 2’s (Dutch National Flag Algorithm)

C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

// Function to sort the linked list of 0s, 1s, and 2sNode* sortList(Node* head) {

if (!head || !head->next) return head;

Node *zeroHead = new Node(-1), *oneHead = new Node(-1), *twoHead = new Node(-1);

Node *zero = zeroHead, *one = oneHead, *two = twoHead;

// Split the nodes into three lists

Node* curr = head;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (curr) {

if (curr->data == 0) {

zero->next = curr;

zero = zero->next;

} else if (curr->data == 1) {

one->next = curr;

one = one->next;

} else {

two->next = curr;

two = two->next;

curr = curr->next;

// Connect the three lists

zero->next = oneHead->next ? oneHead->next : twoHead->next;

one->next = twoHead->next;

two->next = nullptr;

Node* sortedHead = zeroHead->next;

// Free dummy nodes

delete zeroHead;

delete oneHead;

delete twoHead;

return sortedHead;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to print listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = new Node(2);

head->next = new Node(1);

head->next->next = new Node(0);

head->next->next->next = new Node(2);

head->next->next->next->next = new Node(1);

head->next->next->next->next->next = new Node(0);

cout << "Original List: ";

printList(head);

head = sortList(head);

cout << "Sorted List: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1️⃣ Create three separate linked lists for 0s, 1s, and 2s.
2️⃣ Traverse the original list, placing nodes into the corresponding lists.
3️⃣ Merge the three lists together in order: 0s → 1s → 2s.
4️⃣ Return the head of the sorted list without using extra space for sorting.

� Output
Original List: 2 -> 1 -> 0 -> 2 -> 1 -> 0 -> NULL

Sorted List: 0 -> 0 -> 1 -> 1 -> 2 -> 2 -> NULL

PROBLEM:133

Question : Find the Intersection Point of Two Y-Shaped


Linked Lists
We have two linked lists that merge at some point (Y-shaped). We need to find the node
where they intersect.
1️⃣ Find lengths of both linked lists.
2️⃣ Move the pointer of the longer list ahead by the difference in lengths.
3️⃣ Traverse both lists together until they meet at the intersection point.

✅ C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to find the length of a linked listint getLength(Node* head) {

int length = 0;

while (head) {

length++;

head = head->next;

return length;

// Function to find the intersection pointNode* getIntersectionNode(Node* head1, Node* head2)


{

int len1 = getLength(head1);

int len2 = getLength(head2);

// Move the pointer of the longer list ahead by the difference

while (len1 > len2) {

head1 = head1->next;

len1--;

while (len2 > len1) {

head2 = head2->next;

len2--;

// Move both pointers together until they meet

while (head1 && head2) {

if (head1 == head2) return head1; // Intersection found

head1 = head1->next;

head2 = head2->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return nullptr; // No intersection

// Function to print the listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

// Creating two linked lists with an intersection

Node* common = new Node(8);

common->next = new Node(10);

Node* head1 = new Node(3);

head1->next = new Node(6);

head1->next->next = common;

Node* head2 = new Node(4);

head2->next = common;

cout << "List 1: ";

printList(head1);

cout << "List 2: ";

printList(head2);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* intersection = getIntersectionNode(head1, head2);

if (intersection)

cout << "Intersection Point: " << intersection->data << endl;

else

cout << "No Intersection Point" << endl;

return 0;

� Code Explanation in 4 Lines:


1️⃣ Find lengths of both linked lists.
2️⃣ Move the longer list’s pointer ahead by the difference in lengths.
3️⃣ Traverse both lists together until they meet at a common node.
4️⃣ Return the intersection node, or NULL if no intersection exists.

� Output
List 1: 3 -> 6 -> 8 -> 10 -> NULL

List 2: 4 -> 8 -> 10 -> NULL

Intersection Point: 8

PROBLEM:134

Question : Add 1 to a Number Represented as a Linked List

Approach:

1️⃣ Reverse the linked list to process digits from the least significant.
2️⃣ Add 1 to the first node, handling carry if needed.
3️⃣ Reverse the list again to restore the original order.
4️⃣ Return the updated list.

✅ C++ Code Implementation

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

// Function to reverse the linked listNode* reverseList(Node* head) {

Node* prev = nullptr;

Node* curr = head;

while (curr) {

Node* nextNode = curr->next;

curr->next = prev;

prev = curr;

curr = nextNode;

return prev;

// Function to add 1 to the linked list numberNode* addOne(Node* head) {

head = reverseList(head); // Step 1: Reverse the list

Node* curr = head;

int carry = 1; // Start with adding 1

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (curr) {

int sum = curr->data + carry;

curr->data = sum % 10;

carry = sum / 10;

if (!carry) break; // No more carry, stop early

if (!curr->next && carry) { // If carry remains at the last node, add a new node

curr->next = new Node(carry);

carry = 0;

curr = curr->next;

return reverseList(head); // Step 3: Reverse the list again to restore order

// Function to print listvoid printList(Node* head) {

while (head) {

cout << head->data;

head = head->next;

cout << endl;

int main() {

Node* head = new Node(9);

head->next = new Node(9);

head->next->next = new Node(9);

cout << "Original Number: ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


printList(head);

head = addOne(head);

cout << "Number after Adding 1: ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Reverse the linked list so we process from the least significant digit.
2️⃣ Add 1, handling carry propagation through the list.
3️⃣ If the last digit has a carry, append a new node with value 1.
4️⃣ Reverse the list back to maintain the original number order.

� Output
Original Number: 999 Number after Adding 1: 1000

PROBLEM:135

Question : Add Two Numbers Represented as Linked


Lists
Approach:

1️⃣ Traverse both lists while adding corresponding digits.


2️⃣ Handle carry if the sum exceeds 9.
3️⃣ Create a new linked list for the sum.
4️⃣ If carry remains after the final digits, add a new node.

✅ C++ Code Implementation

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

};

// Function to add two numbers represented as linked listsNode* addTwoNumbers(Node* l1,


Node* l2) {

Node* dummy = new Node(0); // Dummy node to simplify list construction

Node* temp = dummy;

int carry = 0;

// Traverse both lists

while (l1 || l2 || carry) {

int sum = carry;

if (l1) {

sum += l1->data;

l1 = l1->next;

if (l2) {

sum += l2->data;

l2 = l2->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


carry = sum / 10;

temp->next = new Node(sum % 10);

temp = temp->next;

return dummy->next; // Return result, skipping the dummy node

// Function to print listvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

// Creating first number: 342 (stored as 2 -> 4 -> 3)

Node* l1 = new Node(2);

l1->next = new Node(4);

l1->next->next = new Node(3);

// Creating second number: 465 (stored as 5 -> 6 -> 4)

Node* l2 = new Node(5);

l2->next = new Node(6);

l2->next->next = new Node(4);

cout << "Number 1: ";

printList(l1);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Number 2: ";

printList(l2);

Node* result = addTwoNumbers(l1, l2);

cout << "Sum: ";

printList(result);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Traverse both lists digit by digit, adding values and handling carry.
2️⃣ Store each sum mod 10 in a new linked list.
3️⃣ Move forward in both lists, propagating carry if needed.
4️⃣ If carry remains after processing, add an extra node.

� Output
Number 1: 2 -> 4 -> 3 -> NULL

Number 2: 5 -> 6 -> 4 -> NULL

Sum: 7 -> 0 -> 8 -> NULL

PROBLEM:136

Question : Delete All Occurrences of a Key in a Doubly Linked List (DLL)

Approach:

1️⃣ Traverse the DLL to find nodes matching the key.


2️⃣ Update pointers of the previous and next nodes to remove the target node.
3️⃣ Handle edge cases: deleting the head or the last node.
4️⃣ Continue deletion until all occurrences are removed.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


✅ C++ Code Implementation
cpp

#include <iostream>

using namespace std;

// Node structure for DLLstruct Node {

int data;

Node* prev;

Node* next;

Node(int val) {

data = val;

prev = next = nullptr;

};

// Function to delete all occurrences of a keyNode* deleteAllOccurrences(Node* head, int key)


{

Node* temp = head;

while (temp) {

if (temp->data == key) {

Node* toDelete = temp;

// If deleting the head node

if (temp == head) {

head = temp->next;

if (head) head->prev = nullptr;

else {

temp->prev->next = temp->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (temp->next) temp->next->prev = temp->prev;

temp = temp->next;

delete toDelete;

else {

temp = temp->next;

return head;

// Function to print the DLLvoid printList(Node* head) {

while (head) {

cout << head->data << " <-> ";

head = head->next;

cout << "NULL" << endl;

// Function to insert a node at the endvoid insert(Node*& head, int data) {

Node* newNode = new Node(data);

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) temp = temp->next;

temp->next = newNode;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


newNode->prev = temp;

int main() {

Node* head = nullptr;

// Creating DLL: 1 <-> 2 <-> 3 <-> 2 <-> 4 <-> 2 <-> 5

insert(head, 1);

insert(head, 2);

insert(head, 3);

insert(head, 2);

insert(head, 4);

insert(head, 2);

insert(head, 5);

cout << "Original DLL: ";

printList(head);

int key = 2;

head = deleteAllOccurrences(head, key);

cout << "DLL after deleting " << key << ": ";

printList(head);

return 0;

� Code Explanation

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1️⃣ Traverse the DLL and find nodes matching the key.
2️⃣ Adjust links of the previous and next nodes to remove target nodes.
3️⃣ Handle special cases, like deleting the head node.
4️⃣ Continue until all occurrences of the key are removed.

� Output
Original DLL: 1 <-> 2 <-> 3 <-> 2 <-> 4 <-> 2 <-> 5 <-> NULL

DLL after deleting 2: 1 <-> 3 <-> 4 <-> 5 <-> NULL

PROBLEM:137

Question : Find Pairs with Given Sum in a Doubly Linked List (DLL)

✅ Approach (Two-Pointer Technique):

1️⃣ Set left to head and right to the last node.


2️⃣ Check sum of left->data + right->data.
3️⃣ If sum equals target, store the pair and move both pointers.
4️⃣ If sum is less, move left forward; if greater, move right backward.

� C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

Node* prev;

Node* next;

Node(int val) {

data = val;

prev = next = nullptr;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

// Function to insert at the end of DLLvoid insert(Node*& head, int val) {

Node* newNode = new Node(val);

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) temp = temp->next;

temp->next = newNode;

newNode->prev = temp;

// Function to find pairs with given sumvoid findPairsWithSum(Node* head, int target) {

if (!head) return;

Node* left = head;

Node* right = head;

// Move right to the end

while (right->next) right = right->next;

bool found = false;

while (left != right && left->prev != right) {

int sum = left->data + right->data;

if (sum == target) {

cout << "(" << left->data << ", " << right->data << ")" << endl;

found = true;

left = left->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


right = right->prev;

} else if (sum < target) {

left = left->next;

} else {

right = right->prev;

if (!found)

cout << "No pairs found." << endl;

int main() {

Node* head = nullptr;

// Sorted DLL: 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9

insert(head, 1);

insert(head, 2);

insert(head, 4);

insert(head, 5);

insert(head, 6);

insert(head, 8);

insert(head, 9);

int target = 7;

cout << "Pairs with sum " << target << ":" << endl;

findPairsWithSum(head, target);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation in 4 Lines:
1️⃣ Use two pointers, left at the head and right at the end.
2️⃣ Check if the sum of left and right is equal to the target.
3️⃣ Move pointers inward based on whether the sum is < or > target.
4️⃣ Print all valid (left, right) pairs until pointers cross.

� Output
Pairs with sum 7:

(1, 6)

(2, 5)

PROBLEM:138

Question : Remove Duplicates from a Sorted Doubly


Linked List (DLL)
✅ Approach:

1️⃣ Start traversing from the head node.


2️⃣ Compare the current node’s data with the next node’s data.
3️⃣ If they are equal, remove the next node by adjusting pointers.
4️⃣ Repeat until you reach the end of the list.

� C++ Code Implementation


cpp

#include <iostream>using namespace std;

// DLL Node structurestruct Node {

int data;

Node* prev;

Node* next;

Node(int val) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


data = val;

prev = next = nullptr;

};

// Function to insert at the end of DLLvoid insert(Node*& head, int val) {

Node* newNode = new Node(val);

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) temp = temp->next;

temp->next = newNode;

newNode->prev = temp;

// Function to remove duplicates from sorted DLLvoid removeDuplicates(Node* head) {

Node* curr = head;

while (curr && curr->next) {

if (curr->data == curr->next->data) {

Node* dup = curr->next;

curr->next = dup->next;

if (dup->next) dup->next->prev = curr;

delete dup;

} else {

curr = curr->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to print DLLvoid printList(Node* head) {

while (head) {

cout << head->data << " <-> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = nullptr;

// Sorted DLL: 1 <-> 2 <-> 2 <-> 3 <-> 3 <-> 3 <-> 4

insert(head, 1);

insert(head, 2);

insert(head, 2);

insert(head, 3);

insert(head, 3);

insert(head, 3);

insert(head, 4);

cout << "Original DLL: ";

printList(head);

removeDuplicates(head);

cout << "After removing duplicates: ";

printList(head);

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation in 4 Lines:
1️⃣ Traverse the sorted DLL using a pointer curr.
2️⃣ If curr and curr->next have the same value, delete curr->next.
3️⃣ Adjust the next and prev pointers properly during deletion.
4️⃣ Move to the next node only when no duplicate is found.

� Output
Original DLL: 1 <-> 2 <-> 2 <-> 3 <-> 3 <-> 3 <-> 4 <-> NULL

After removing duplicates: 1 <-> 2 <-> 3 <-> 4 <-> NULL

PROBLEM:139

Question : Reverse Linked List in Groups of Size K

✅ Approach:

1️⃣ Traverse k nodes, reverse them, and keep track of previous group's tail.
2️⃣ Use a recursive call or loop to reverse the next group of size k.
3️⃣ After reversal, connect previous group's tail to the new head.
4️⃣ Stop if less than k nodes are left.

� C++ Code Implementation


cpp

#include <iostream>using namespace std;

// Linked list nodestruct Node {

int data;

Node* next;

Node(int val) {

data = val;

next = nullptr;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

// Function to insert at endvoid insert(Node*& head, int val) {

Node* newNode = new Node(val);

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) temp = temp->next;

temp->next = newNode;

// Function to reverse k nodesNode* reverseKGroup(Node* head, int k) {

Node* curr = head;

Node* prev = nullptr;

Node* next = nullptr;

int count = 0;

// Check if there are at least k nodes

Node* temp = head;

for (int i = 0; i < k; i++) {

if (!temp) return head;

temp = temp->next;

// Reverse first k nodes

while (curr && count < k) {

next = curr->next;

curr->next = prev;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


prev = curr;

curr = next;

count++;

// Recurse for remaining list and link

if (next) head->next = reverseKGroup(next, k);

return prev;

// Function to print LLvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = nullptr;

for (int i = 1; i <= 10; i++) insert(head, i); // List: 1->2->...->10

cout << "Original List: ";

printList(head);

int k = 3;

head = reverseKGroup(head, k);

cout << "Reversed in groups of " << k << ": ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Reverse the first k nodes using a standard reverse logic.
2️⃣ Check if at least k nodes exist before reversing (base case).
3️⃣ Recursively reverse the rest of the list.
4️⃣ Connect the current group’s tail to the head of the next reversed group.

� Output
Original List: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> NULL

Reversed in groups of 3: 3 -> 2 -> 1 -> 6 -> 5 -> 4 -> 9 -> 8 -> 7 -> 10 -> NULL

PROBLEM:140

Question : Rotate a Linked List

✅ Approach:

1️⃣ Find the length of the list.


2️⃣ Convert the list into a circular list.
3️⃣ Break the circle at the new head after len - (k % len) steps.
4️⃣ Set the new head and nullify the new tail's next.

� C++ Code Implementation


cpp

#include <iostream>

using namespace std;

// Node structurestruct Node {

int data;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Node* next;

Node(int val) {

data = val;

next = nullptr;

};

// Function to insert at endvoid insert(Node*& head, int val) {

Node* newNode = new Node(val);

if (!head) {

head = newNode;

return;

Node* temp = head;

while (temp->next) temp = temp->next;

temp->next = newNode;

// Function to rotate LL by k positionsNode* rotateRight(Node* head, int k) {

if (!head || !head->next || k == 0) return head;

// Find length and tail

Node* tail = head;

int len = 1;

while (tail->next) {

tail = tail->next;

len++;

k %= len;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (k == 0) return head;

// Make it circular

tail->next = head;

// Move to the new tail: (len - k - 1) steps

Node* newTail = head;

for (int i = 0; i < len - k - 1; i++)

newTail = newTail->next;

// Set new head and break the loop

Node* newHead = newTail->next;

newTail->next = nullptr;

return newHead;

// Function to print LLvoid printList(Node* head) {

while (head) {

cout << head->data << " -> ";

head = head->next;

cout << "NULL" << endl;

int main() {

Node* head = nullptr;

for (int i = 1; i <= 5; i++) insert(head, i); // 1->2->3->4->5

int k = 2;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Original List: ";

printList(head);

head = rotateRight(head, k);

cout << "After rotating by " << k << ": ";

printList(head);

return 0;

� Code Explanation in 4 Lines:


1️⃣ Find the length of the list and connect the tail to the head (make it circular).
2️⃣ Compute effective rotations with k % length.
3️⃣ Move to the new tail (length - k - 1) and break the circular link.
4️⃣ Return the new head for the rotated list

output

Original List: 1 -> 2 -> 3 -> 4 -> 5 -> NULL

After rotating by 2: 4 -> 5 -> 1 -> 2 -> 3 -> NULL

PROBLEM:141

Question : Flattening a Linked List


✅ Approach:

1️⃣ Use recursion to flatten the next list.


2️⃣ Merge the current list with the flattened next list using the bottom pointer.
3️⃣ Repeat until only one list remains.
4️⃣ Ignore the next pointer in the final flattened list.

� C++ Code Implementation

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

Node* bottom;

Node(int x) : data(x), next(nullptr), bottom(nullptr) {}

};

// Merge two sorted bottom listsNode* merge(Node* a, Node* b) {

if (!a) return b;

if (!b) return a;

Node* result;

if (a->data < b->data) {

result = a;

result->bottom = merge(a->bottom, b);

} else {

result = b;

result->bottom = merge(a, b->bottom);

result->next = nullptr; // We only use bottom in the final list

return result;

// Flatten the multilevel listNode* flatten(Node* root) {

if (!root || !root->next) return root;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Flatten the next list first

root->next = flatten(root->next);

// Merge current and next

root = merge(root, root->next);

return root;

// Print bottom-only listvoid printList(Node* node) {

while (node) {

cout << node->data << " -> ";

node = node->bottom;

cout << "NULL" << endl;

� Code Explanation in 4 Lines:


1️⃣ Recursively flatten the list starting from the rightmost node.
2️⃣ Merge each list with its flattened next using the bottom pointer.
3️⃣ Use a sorted merge logic to ensure the result remains ordered.
4️⃣ Ignore the next pointer in the final flattened list.

PROBLEM:142

Question : Clone a Linked List with random and next pointer


✅ Approach:

1️⃣ Insert cloned nodes next to original nodes (interleaving).


2️⃣ Set the random pointers for the clones.
3️⃣ Separate the interleaved list into original and cloned.
4️⃣ Return the head of the cloned list.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� C++ Code Implementation
cpp

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

Node* random;

Node(int val) {

data = val;

next = nullptr;

random = nullptr;

};

Node* cloneList(Node* head) {

if (!head) return nullptr;

// Step 1: Insert cloned nodes

Node* curr = head;

while (curr) {

Node* copy = new Node(curr->data);

copy->next = curr->next;

curr->next = copy;

curr = copy->next;

// Step 2: Set random pointers

curr = head;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (curr) {

if (curr->random)

curr->next->random = curr->random->next;

curr = curr->next->next;

// Step 3: Separate the cloned list

Node* dummy = new Node(0);

Node* copyCurr = dummy;

curr = head;

while (curr) {

copyCurr->next = curr->next;

curr->next = curr->next->next;

copyCurr = copyCurr->next;

curr = curr->next;

return dummy->next;

// Utility to print list (shows data and random)void printList(Node* head) {

while (head) {

cout << "Node: " << head->data;

cout << ", Random: " << (head->random ? head->random->data : -1) << endl;

head = head->next;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Code Explanation in 4 Lines:
1️⃣ Clone each node and interleave it next to its original.
2️⃣ Use the interleaved structure to correctly assign random pointers.
3️⃣ Separate original and cloned lists while restoring the original.
4️⃣ Return the head of the cloned list.

PROBLEM:143

Question: recursive implementation of atoi()


C++

cpp

#include <iostream>

using namespace std;

int atoiRecursive(const char* str, int i = 0, int result = 0, int sign = 1) {

// Skip leading whitespaces

if (i == 0) {

while (str[i] == ' ') i++;

if (str[i] == '-' || str[i] == '+') {

sign = (str[i] == '-') ? -1 : 1;

return atoiRecursive(str, i + 1, result, sign);

// Base case: stop if current char is not a digit

if (str[i] < '0' || str[i] > '9')

return result * sign;

// Convert current char to digit and accumulate

result = result * 10 + (str[i] - '0');

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return atoiRecursive(str, i + 1, result, sign);

� Example Usage:

cpp

int main() {

const char* s1 = "12345";

const char* s2 = "-789";

const char* s3 = " +42abc";

cout << atoiRecursive(s1) << endl; // Output: 12345

cout << atoiRecursive(s2) << endl; // Output: -789

cout << atoiRecursive(s3) << endl; // Output: 42

return 0;

� Code Explanation:

1. Skips leading spaces and checks for sign (+ or -).


2. Base case: stops recursion when a non-digit is found.
3. Accumulates digits by multiplying previous result by 10 and adding current digit.
4. Applies sign and returns final result.

PROBLEM:144

Question: pow(x, n)

Recursive Power Function in C++

cpp

double myPow(double x, int n) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Base case

if (n == 0) return 1;

// Handle negative exponent

if (n < 0) {

x = 1 / x;

// Handle INT_MIN safely

if (n == INT_MIN)

return x * myPow(x, -(n + 1));

n = -n;

// Recursive step: exponentiation by squaring

double half = myPow(x, n / 2);

if (n % 2 == 0)

return half * half;

else

return half * half * x;

� Explanation in 4 Lines:

1. Handle base case: x0=1x^0 = 1x0=1.


2. If n < 0, invert x and make n positive (special care for INT_MIN).
3. Use divide and conquer (exponentiation by squaring) to reduce calls.
4. Multiply x back if n is odd.

Example Usage:

cpp

#include <iostream>using namespace std;

int main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << myPow(2.0, 10) << endl; // Output: 1024

cout << myPow(2.0, -2) << endl; // Output: 0.25

cout << myPow(3.0, 0) << endl; // Output: 1

return 0;

PROBLEM:145

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

Question: Count Good Numbers


A number is "good" if:

Even positions (0-based) have even digits: 0, 2, 4, 6, 8 → 5 choices

Odd positions have prime digits: 2, 3, 5, 7 → 4 choices

Given a number n (length of the number), count how many such good numbers exist,
modulo 109+710^9 + 7109+7.

✅ C++ Code (Modular Exponentiation)

cpp

CopyEdit

class Solution {public:

const int MOD = 1e9 + 7;

long long modPow(long long base, long long exp) {

long long result = 1;

while (exp > 0) {

if (exp % 2 == 1) result = (result * base) % MOD;

base = (base * base) % MOD;

exp /= 2;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return result;

int countGoodNumbers(long long n) {

long long evenCount = (n + 1) / 2; // positions 0, 2, 4,...

long long oddCount = n / 2; // positions 1, 3, 5,...

return (modPow(5, evenCount) * modPow(4, oddCount)) % MOD;

};

� Logic in 4 Lines:

1. Even indices have 5 possible digits; odd ones have 4.


2. Count even and odd digit positions using (n+1)/2 and n/2.
3. Use fast modular exponentiation for performance.
4. Multiply both parts and return result mod 109+710^9 + 7109+7.

PROBLEM:146

Question: Sort Stack Using Recursion

C++ Code:

cpp

#include <iostream>

#include <stack>

using namespace std;

// Insert element into the sorted stack in the right position

void insertSorted(stack<int>& s, int element) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (s.empty() || s.top() <= element) {

s.push(element);

return;

int top = s.top();

s.pop();

insertSorted(s, element);

s.push(top);

// Main recursive function to sort the stack

void sortStack(stack<int>& s) {

if (s.empty()) return;

int top = s.top();

s.pop();

sortStack(s); // Recursively sort the remaining stack

insertSorted(s, top); // Insert the popped item in sorted order

int main() {

stack<int> s;

s.push(3);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


s.push(1);

s.push(4);

s.push(2);

sortStack(s);

// Print sorted stack (smallest on top)

while (!s.empty()) {

cout << s.top() << " ";

s.pop();

return 0;

Logic Explained in 4 Beginner-Friendly Steps:


1. Remove the top element from the stack.
2. Sort the rest of the stack recursively.
3. Insert the removed element back into the sorted stack at the right place using another
recursive function.
4. Repeat this until the stack is fully sorted!

PROBLEM:147

Question: C++ Code: Reverse Stack Using Recursion

C++ Code:
cpp
#include <iostream>
#include <stack>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


using namespace std;

// Helper: Insert an element at the bottom of the stack


void insertAtBottom(stack<int>& s, int element) {
if (s.empty()) {
s.push(element);
return;
}

int top = s.top();


s.pop();
insertAtBottom(s, element);
s.push(top);
}

// Main recursive function to reverse the stack


void reverseStack(stack<int>& s) {
if (s.empty()) return;

int top = s.top();


s.pop();
reverseStack(s); // Reverse the rest of the stack
insertAtBottom(s, top); // Put the top at the bottom
}
int main() {
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);

reverseStack(s);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Print reversed stack
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
return 0;
}

� Logic in 4 Simple Steps (Beginner-Friendly):


1. Pop the top of the stack.
2. Recursively reverse the rest of the stack.
3. Use a helper function to insert the popped item at the bottom.
4. Repeat until the stack is reversed!

PROBLEM:148
Question: Generate All Binary Strings Using Recursion

C++ Code:

cpp
#include <iostream>
using namespace std;

// Recursive function to generate binary strings


void generateBinaryStrings(int n, string str = "") {
if (n == 0) {
cout << str << endl;
return;
}

generateBinaryStrings(n - 1, str + "0"); // Add 0 and recurse


generateBinaryStrings(n - 1, str + "1"); // Add 1 and recurse
}
int main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int n = 3;
generateBinaryStrings(n);
return 0;
}

� Logic in 4 Easy Lines:


1.Start with an empty string and length n.

2.At each step, add '0' or '1' to the string.

3.When n == 0, you’ve built a full-length binary string → print it.

4.Use recursion to explore both '0' and '1' options at each level.

PROBLEM:149

Question: Generate Valid Parenthesis

C++ Code: Generate Parentheses Using Recursion


cpp

#include <iostream>

#include <vector>

using namespace std;

void generateParenthesisHelper(int open, int close, string current, vector<string>& result) {

if (open == 0 && close == 0) {

result.push_back(current);

return;

if (open > 0) {

generateParenthesisHelper(open - 1, close, current + "(", result);

if (close > open) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


generateParenthesisHelper(open, close - 1, current + ")", result);

vector<string> generateParenthesis(int n) {

vector<string> result;

generateParenthesisHelper(n, n, "", result);

return result;

� Example Usage:

cpp

int main() {

int n = 3;

vector<string> parens = generateParenthesis(n);

for (string s : parens) {

cout << s << endl;

return 0;

� Logic Explained in 4 Beginner-Friendly Lines:


1. Use recursion to add ( and ) step by step.
2. You can only add ( if open > 0, and ) if close > open (to stay valid).
3. When both open and close are 0, a valid string is completed → save it.
4. This ensures all combinations are well-formed and balanced.

PROBLEM:150
Question: Print all subsequences/Power Set

C++ Code:
The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)
cpp

#include <iostream>

using namespace std;

void printSubsequences(string input, string output = "", int index = 0) {

if (index == input.length()) {

cout << "\"" << output << "\"" << endl; // Print subsequence

return;

// Include the current character

printSubsequences(input, output + input[index], index + 1);

// Exclude the current character

printSubsequences(input, output, index + 1);

� Example Usage:

cpp

int main() {

string str = "abc";

printSubsequences(str);

return 0;

Output:

arduino

"abc""ab""ac""a""bc""b""c"""

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Logic in 4 Simple Lines:
1.At each step, you have two choices: include or exclude the current character.

2.Use recursion to explore both choices for each character.

3.When the end of the string is reached, print the current combination.

4.This gives all 2^n subsequences of the string (power set).

PROBLEM:151
Question:Learn All Patterns of Subsequences

✅ 1. Print All Subsequences of a String


cpp

void printAllSubsequences(string &s, int i, string temp) {

if (i == s.length()) {

cout << temp << endl;

return;

printAllSubsequences(s, i + 1, temp + s[i]); // pick

printAllSubsequences(s, i + 1, temp); // not pick

Explanation:

1. At each index, you either include or exclude the current character.


2. This gives you 2 choices per character → total 2ⁿ subsequences.
3. When index reaches end, print the current string.
4. Works for any string without needing extra data structures.

✅ 2. Count All Subsequences of Array with Sum = K


cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


CopyEdit

int countSubsequences(vector<int> &arr, int i, int sum, int k) {

if (i == arr.size()) return sum == k ? 1 : 0;

return countSubsequences(arr, i + 1, sum + arr[i], k) +

countSubsequences(arr, i + 1, sum, k);

Explanation:

1. Use recursion to either include or exclude current element in sum.


2. If total sum equals target k, count that subsequence.
3. Add results of both choices to get total count.
4. This is a classic subset sum variant using recursion.

✅ 3. Print One Subsequence With Sum = K


cpp

CopyEdit

bool printOneSubsequence(vector<int> &arr, int i, int sum, int k, vector<int> &temp) {

if (i == arr.size()) {

if (sum == k) {

for (int x : temp) cout << x << " ";

cout << endl;

return true;

return false;

temp.push_back(arr[i]);

if (printOneSubsequence(arr, i + 1, sum + arr[i], k, temp)) return true;

temp.pop_back();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (printOneSubsequence(arr, i + 1, sum, k, temp)) return true;

return false;

Explanation:

1. Recursively build one valid subset where sum equals k.


2. Stop further recursion once the first valid subsequence is found.
3. Use backtracking to manage the current list (temp).
4. Efficient when you need only one solution, not all.

✅ 4. Print All Subsequences With Sum = K


cpp

CopyEdit

void printAllSumK(vector<int> &arr, int i, int sum, int k, vector<int> &temp) {

if (i == arr.size()) {

if (sum == k) {

for (int x : temp) cout << x << " ";

cout << endl;

return;

temp.push_back(arr[i]);

printAllSumK(arr, i + 1, sum + arr[i], k, temp);

temp.pop_back();

printAllSumK(arr, i + 1, sum, k, temp);

Explanation:

1. Use backtracking to find all subsets that sum to k.


2. No early return → all valid paths are explored.
3. Temp vector stores current subset under construction.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


4. Prints each valid combination when base condition is met.

✅ 5. Power Set of String (Same as All Subsequences)


cpp

CopyEdit

void powerSet(string &s, int i, string curr) {

if (i == s.size()) {

cout << "\"" << curr << "\"\n";

return;

powerSet(s, i + 1, curr + s[i]); // include

powerSet(s, i + 1, curr); // exclude

Explanation:

1. This is the exact same logic as printing all subsequences.


2. Generates the full power set including the empty string.
3. Useful when working with combinations, masks, or string problems.
4. Time complexity is O(2ⁿ) for string of length n.

PROBLEM:152

Question: Count Subsequences with Sum = K


C++ Code: Count Subsequences with Sum K

cpp

#include <iostream>

#include <vector>

using namespace std;

int countSubsequences(vector<int>& arr, int index, int sum, int K) {

if (index == arr.size()) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return sum == K ? 1 : 0;

// Include current element

int pick = countSubsequences(arr, index + 1, sum + arr[index], K);

// Exclude current element

int notPick = countSubsequences(arr, index + 1, sum, K);

return pick + notPick;

� Example Usage

cpp

int main() {

vector<int> arr = {1, 2, 1};

int K = 2;

int count = countSubsequences(arr, 0, 0, K);

cout << "Count of subsequences with sum " << K << " = " << count << endl;

return 0;

Output:

CCount of subsequences with sum 2 = 2

(The valid subsequences are [1,1] and [2])

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� 4-Line Explanation:

1. At each step, you can either include or exclude the current element.
2. If you reach the end (index == arr.size()), check if the sum equals K.
3. If yes, count this path (return 1); else return 0.
4. Add both counts (include + exclude) to get total valid subsequences.

PROBLEM:153

Question: Check if Subsequence Sum K Exists

C++ Code:
cpp

#include <iostream>

#include <vector>

using namespace std;

bool isSubsequenceSumK(vector<int>& arr, int index, int sum, int K) {

if (index == arr.size()) {

return sum == K;

// Include current element

if (isSubsequenceSumK(arr, index + 1, sum + arr[index], K))

return true;

// Exclude current element

if (isSubsequenceSumK(arr, index + 1, sum, K))

return true;

return false;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Example Usage

cpp

int main() {

vector<int> arr = {1, 2, 3};

int K = 5;

if (isSubsequenceSumK(arr, 0, 0, K))

cout << "Yes, a subsequence exists with sum " << K << endl;

else

cout << "No subsequence found with sum " << K << endl;

return 0;

}
Output:

Yes, a subsequence exists with sum 5


(Example: [2, 3] is a valid subsequence)

� 4-Line Explanation:

1. At each index, choose to include or exclude the element in the sum.


2. When end of array is reached, check if sum == K.
3. If any path returns true, the answer is true (early return).
4. Uses basic recursion (no need to store subsequences).

PROBLEM:154

Question: Combination Sum

C++ Code:
cpp

#include <iostream>

#include <vector>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


using namespace std;

void findCombinations(int index, vector<int>& candidates, int target, vector<int>& current,


vector<vector<int>>& result) {

if (target == 0) {

result.push_back(current); // valid combination found

return;

if (index == candidates.size() || target < 0) return;

// Pick the current element (can be picked again)

current.push_back(candidates[index]);

findCombinations(index, candidates, target - candidates[index], current, result);

current.pop_back();

// Don't pick current, move to next element

findCombinations(index + 1, candidates, target, current, result);

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {

vector<vector<int>> result;

vector<int> current;

findCombinations(0, candidates, target, current, result);

return result;

� Example Usage

cpp

int main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<int> candidates = {2, 3, 6, 7};

int target = 7;

vector<vector<int>> combinations = combinationSum(candidates, target);

for (auto& combo : combinations) {

for (int num : combo) cout << num << " ";

cout << endl;

return 0;

� 4-Line Explanation:

1. Use recursion to try including the current element (again) or skipping to the next.
2. If the sum becomes 0, you found a valid combination.
3. If sum goes negative or index exceeds array, backtrack.
4. Use a temporary vector to build combinations and backtrack after each path.

PROBLEM:155

Question: Combination Sum II

C++ Code:
cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


void findComb(int index, vector<int>& candidates, int target, vector<int>& current,
vector<vector<int>>& result) {

if (target == 0) {

result.push_back(current);

return;

for (int i = index; i < candidates.size(); i++) {

if (i > index && candidates[i] == candidates[i - 1]) continue; // Skip duplicates

if (candidates[i] > target) break;

current.push_back(candidates[i]);

findComb(i + 1, candidates, target - candidates[i], current, result); // Move to next index

current.pop_back();

vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {

sort(candidates.begin(), candidates.end()); // Sort to handle duplicates easily

vector<vector<int>> result;

vector<int> current;

findComb(0, candidates, target, current, result);

return result;

� Example Usage:

cpp

int main() {

vector<int> candidates = {10, 1, 2, 7, 6, 1, 5};

int target = 8;

vector<vector<int>> combos = combinationSum2(candidates, target);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (auto& comb : combos) {

for (int num : comb) cout << num << " ";

cout << endl;

return 0;

� 4-Line Explanation:

1. Sort the array to easily skip duplicates.


2. At each index, either include the number and move to next (i+1), or skip.
3. If you pick a number that’s the same as the previous at the same depth, skip it.
4. Use backtracking to explore all valid combinations without repetition.

PROBLEM:156

Question: Subset Sum I

C++ Code:
cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

void findSubsetSums(int index, int sum, vector<int>& arr, vector<int>& result) {

if (index == arr.size()) {

result.push_back(sum);

return;

// Include current element

findSubsetSums(index + 1, sum + arr[index], arr, result);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Exclude current element

findSubsetSums(index + 1, sum, arr, result);

� Example Usage:

cpp

int main() {

vector<int> arr = {1, 2, 3};

vector<int> result;

findSubsetSums(0, 0, arr, result);

sort(result.begin(), result.end()); // Optional: Sorted output

for (int sum : result)

cout << sum << " ";

return 0;

� 4-Line Explanation:

1. Recursively include or exclude each element.


2. When you reach the end, store the current sum as a result.
3. This covers all 2^n subsets of the array.
4. Optionally sort results for ordered output.

PROBLEM:157

Question: Subset Sum II

C++ Code:
cpp

#include <iostream>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <vector>

#include <algorithm>

using namespace std;

void findSubsets(int index, vector<int>& arr, vector<int>& current, vector<vector<int>>&


result) {

result.push_back(current);

for (int i = index; i < arr.size(); i++) {

if (i > index && arr[i] == arr[i - 1]) continue; // Skip duplicates

current.push_back(arr[i]);

findSubsets(i + 1, arr, current, result);

current.pop_back();

vector<vector<int>> subsetSumII(vector<int>& arr) {

sort(arr.begin(), arr.end()); // Sort to bring duplicates together

vector<vector<int>> result;

vector<int> current;

findSubsets(0, arr, current, result);

return result;

� Example Usage:

cpp

int main() {

vector<int> arr = {1, 2, 2};

vector<vector<int>> subsets = subsetSumII(arr);

for (auto& subset : subsets) {

cout << "[";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int num : subset)

cout << num << " ";

cout << "]\n";

return 0;

� 4-Line Explanation:

1. Sort the array to group duplicates together.


2. Use backtracking to generate all subset combinations.
3. Skip duplicates by checking if current element is same as previous (at same depth).
4. Collect all unique subsets without repetition.

PROBLEM:158

Question: Combination Sum III

C++ Code:
cpp

#include <iostream>

#include <vector>

using namespace std;

void backtrack(int start, int k, int n, vector<int>& current, vector<vector<int>>& result) {

if (k == 0 && n == 0) {

result.push_back(current);

return;

if (k == 0 || n < 0) return;

for (int i = start; i <= 9; i++) {

current.push_back(i);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


backtrack(i + 1, k - 1, n - i, current, result);

current.pop_back(); // backtrack

vector<vector<int>> combinationSum3(int k, int n) {

vector<vector<int>> result;

vector<int> current;

backtrack(1, k, n, current, result);

return result;

� Example Usage:

cpp

int main() {

int k = 3, n = 9;

vector<vector<int>> res = combinationSum3(k, n);

for (auto& comb : res) {

for (int num : comb) cout << num << " ";

cout << endl;

return 0;

� 4-Line Explanation:

1. Use numbers from 1 to 9, and build combinations of exactly k numbers.


2. At each step, try adding a number i and reduce both k and n.
3. If k == 0 && n == 0, you've found a valid combination.
4. Use backtracking and start from i + 1 to avoid reusing numbers.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:159

Question:Letter Combinations of a Phone Number

C++ Code:
cpp

#include <iostream>

#include <vector>

using namespace std;

void backtrack(int index, string& digits, string& current, vector<string>& result,


vector<string>& mapping) {

if (index == digits.length()) {

result.push_back(current);

return;

string letters = mapping[digits[index] - '0'];

for (char c : letters) {

current.push_back(c);

backtrack(index + 1, digits, current, result, mapping);

current.pop_back();

vector<string> letterCombinations(string digits) {

if (digits.empty()) return {};

vector<string> mapping = {

"", "", "abc", "def", "ghi", "jkl",

"mno", "pqrs", "tuv", "wxyz"

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<string> result;

string current;

backtrack(0, digits, current, result, mapping);

return result;

� Example Usage:

cpp

CopyEdit

int main() {

string digits = "23";

vector<string> combos = letterCombinations(digits);

for (string& s : combos)

cout << s << " ";

return 0;

� 4-Line Explanation:

1. Use a mapping from digits to letters (like a phone keypad).


2. Recursively build strings by trying all letters for each digit.
3. When the current string reaches full length, add it to results.
4. Use backtracking to explore and undo steps efficiently.

PROBLEM:160

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)Question:


Palindrome Partitioning

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code:
cpp

#include <iostream>

#include <vector>

using namespace std;

// Helper function to check if a substring is a palindromebool isPalindrome(string s, int start, int


end) {

while (start < end) {

if (s[start++] != s[end--])

return false;

return true;

void backtrack(int start, string& s, vector<string>& current, vector<vector<string>>& result) {

if (start == s.length()) {

result.push_back(current);

return;

for (int end = start; end < s.length(); end++) {

if (isPalindrome(s, start, end)) {

current.push_back(s.substr(start, end - start + 1)); // Choose

backtrack(end + 1, s, current, result); // Explore

current.pop_back(); // Undo

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<vector<string>> partition(string s) {

vector<vector<string>> result;

vector<string> current;

backtrack(0, s, current, result);

return result;

� Example Usage:

cpp

int main() {

string s = "aab";

vector<vector<string>> res = partition(s);

for (auto& part : res) {

for (string& str : part)

cout << str << " ";

cout << endl;

return 0;

� 4-Line Explanation:

1. Try every possible substring starting from index 0.


2. If the substring is a palindrome, include it in the current path.
3. Recursively continue partitioning the rest of the string.
4. Backtrack after exploring to try other splits.

PROBLEM:161

Question:Word Search

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code:
cpp

#include <iostream>

#include <vector>

using namespace std;

bool dfs(vector<vector<char>>& board, string& word, int i, int j, int index) {

if (index == word.size()) return true;

if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size()

|| board[i][j] != word[index]) return false;

char temp = board[i][j]; // Save the current letter

board[i][j] = '#'; // Mark as visited

bool found = dfs(board, word, i+1, j, index+1) ||

dfs(board, word, i-1, j, index+1) ||

dfs(board, word, i, j+1, index+1) ||

dfs(board, word, i, j-1, index+1);

board[i][j] = temp; // Backtrack

return found;

bool exist(vector<vector<char>>& board, string word) {

int rows = board.size(), cols = board[0].size();

for (int i = 0; i < rows; ++i)

for (int j = 0; j < cols; ++j)

if (dfs(board, word, i, j, 0))

return true;

return false;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� Example Usage:

cpp

int main() {

vector<vector<char>> board = {

{'A','B','C','E'},

{'S','F','C','S'},

{'A','D','E','E'}

};

string word = "ABCCED";

cout << (exist(board, word) ? "Found" : "Not Found") << endl;

return 0;

� 4-Line Explanation:

1. Start DFS from any cell that matches the first letter.
2. Move in 4 directions (up/down/left/right), marking visited cells temporarily.
3. If full word is matched, return true; otherwise, backtrack.
4. Restore cells after exploring to avoid blocking other paths.

PROBLEM:162

Question: N-Queen

C++ Code:
cpp

#include <iostream>

#include <vector>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


bool isSafe(int row, int col, vector<string>& board, int n) {

// Check upper column

for (int i = 0; i < row; i++)

if (board[i][col] == 'Q') return false;

// Check upper-left diagonal

for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)

if (board[i][j] == 'Q') return false;

// Check upper-right diagonal

for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)

if (board[i][j] == 'Q') return false;

return true;

void solve(int row, vector<string>& board, vector<vector<string>>& solutions, int n) {

if (row == n) {

solutions.push_back(board);

return;

for (int col = 0; col < n; col++) {

if (isSafe(row, col, board, n)) {

board[row][col] = 'Q';

solve(row + 1, board, solutions, n);

board[row][col] = '.'; // backtrack

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

vector<vector<string>> solveNQueens(int n) {

vector<vector<string>> solutions;

vector<string> board(n, string(n, '.'));

solve(0, board, solutions, n);

return solutions;

� Example Usage:

cpp

int main() {

int n = 4;

vector<vector<string>> result = solveNQueens(n);

for (auto& board : result) {

for (string row : board)

cout << row << endl;

cout << endl;

return 0;

� 4-Line Explanation:

1. Place queens row-by-row, checking if the current spot is safe.


2. Use backtracking to try all possibilities.
3. If a valid configuration is reached, store it.
4. Undo the placement and continue searching for other arrangements.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:163

Question: Rat in a Maze

C++ Code:
cpp

#include <iostream>

#include <vector>

using namespace std;

bool isSafe(int x, int y, int n, vector<vector<int>>& maze, vector<vector<int>>& visited) {

return x >= 0 && y >= 0 && x < n && y < n && maze[x][y] == 1 && visited[x][y] == 0;

void solve(int x, int y, vector<vector<int>>& maze, int n, vector<string>& result, string path,
vector<vector<int>>& visited) {

if (x == n - 1 && y == n - 1) {

result.push_back(path);

return;

visited[x][y] = 1;

// Down

if (isSafe(x + 1, y, n, maze, visited)) solve(x + 1, y, maze, n, result, path + 'D', visited);

// Left

if (isSafe(x, y - 1, n, maze, visited)) solve(x, y - 1, maze, n, result, path + 'L', visited);

// Right

if (isSafe(x, y + 1, n, maze, visited)) solve(x, y + 1, maze, n, result, path + 'R', visited);

// Up

if (isSafe(x - 1, y, n, maze, visited)) solve(x - 1, y, maze, n, result, path + 'U', visited);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


visited[x][y] = 0; // Backtrack

vector<string> findPaths(vector<vector<int>>& maze, int n) {

vector<string> result;

vector<vector<int>> visited(n, vector<int>(n, 0));

if (maze[0][0] == 1)

solve(0, 0, maze, n, result, "", visited);

return result;

� Example Usage:

cpp

int main() {

vector<vector<int>> maze = {

{1, 0, 0, 0},

{1, 1, 0, 1},

{0, 1, 0, 0},

{1, 1, 1, 1}

};

vector<string> paths = findPaths(maze, 4);

for (string p : paths) cout << p << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� 4-Line Explanation:

1. Start from (0, 0) and explore all valid moves (D, L, R, U).
2. Use a visited matrix to avoid revisiting cells in the same path.
3. If you reach the destination, save the current path.
4. Backtrack to explore other possible directions.

PROBLEM:164

Question: Word Break

C++ Code:
cpp

#include <iostream>

#include <vector>

#include <unordered_set>

using namespace std;

bool wordBreak(string s, vector<string>& wordDict) {

unordered_set<string> dict(wordDict.begin(), wordDict.end());

int n = s.length();

vector<bool> dp(n + 1, false);

dp[0] = true; // Empty string is always "breakable"

for (int i = 1; i <= n; i++) {

for (int j = 0; j < i; j++) {

if (dp[j] && dict.count(s.substr(j, i - j))) {

dp[i] = true;

break;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return dp[n];

� Example Usage:

cpp

int main() {

string s = "leetcode";

vector<string> dict = {"leet", "code"};

cout << (wordBreak(s, dict) ? "Yes" : "No") << endl;

return 0;

� 4-Line Explanation:

1. Use a dp[i] array to check if s[0..i) can be broken into dictionary words.
2. Start from each j < i and check if dp[j] == true and s[j..i) is a valid word.
3. If yes, mark dp[i] = true.
4. Finally, return dp[n] to know if full string is breakable.

PROBLEM:165

Question: M Coloring Problem

C++ Code:
cpp

#include <iostream>

#include <vector>

using namespace std;

// Check if it's safe to assign color to vertexbool isSafe(int node, vector<vector<int>>& graph,
vector<int>& color, int c, int n) {

for (int i = 0; i < n; i++) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (graph[node][i] == 1 && color[i] == c)

return false;

return true;

// Try to assign colors recursivelybool solve(int node, vector<vector<int>>& graph,


vector<int>& color, int m, int n) {

if (node == n) return true;

for (int c = 1; c <= m; c++) {

if (isSafe(node, graph, color, c, n)) {

color[node] = c;

if (solve(node + 1, graph, color, m, n)) return true;

color[node] = 0; // Backtrack

return false;

// Main functionbool graphColoring(vector<vector<int>>& graph, int m, int n) {

vector<int> color(n, 0);

return solve(0, graph, color, m, n);

� Example Usage:

cpp

CopyEdit

int main() {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int n = 4; // number of vertices

int m = 3; // max colors

vector<vector<int>> graph = {

{0, 1, 1, 1},

{1, 0, 1, 0},

{1, 1, 0, 1},

{1, 0, 1, 0}

};

if (graphColoring(graph, m, n))

cout << "Possible to color with " << m << " colors\n";

else

cout << "Not possible\n";

return 0;

� 4-Line Explanation:

1. Try assigning each color (from 1 to M) to a node.


2. Use isSafe() to ensure adjacent nodes don't share the same color.
3. Recursively assign colors to all nodes.
4. Backtrack if a conflict occurs, and try another color.

PROBLEM:166

Question: Sudoku Solver

C++ Code:
cpp

#include <iostream>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <vector>

using namespace std;

bool isValid(vector<vector<char>>& board, int row, int col, char ch) {

for (int i = 0; i < 9; i++) {

// Check row, column, and 3x3 box

if (board[row][i] == ch || board[i][col] == ch ||

board[3*(row/3)+i/3][3*(col/3)+i%3] == ch)

return false;

return true;

bool solve(vector<vector<char>>& board) {

for (int row = 0; row < 9; row++) {

for (int col = 0; col < 9; col++) {

if (board[row][col] == '.') {

for (char ch = '1'; ch <= '9'; ch++) {

if (isValid(board, row, col, ch)) {

board[row][col] = ch;

if (solve(board)) return true;

board[row][col] = '.'; // Backtrack

return false; // If no valid digit found

return true; // Solved

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Example Usage:

cpp

int main() {

vector<vector<char>> board = {

{'5','3','.','.','7','.','.','.','.'},

{'6','.','.','1','9','5','.','.','.'},

{'.','9','8','.','.','.','.','6','.'},

{'8','.','.','.','6','.','.','.','3'},

{'4','.','.','8','.','3','.','.','1'},

{'7','.','.','.','2','.','.','.','6'},

{'.','6','.','.','.','.','2','8','.'},

{'.','.','.','4','1','9','.','.','5'},

{'.','.','.','.','8','.','.','7','9'}

};

solve(board);

for (auto& row : board) {

for (char c : row)

cout << c << " ";

cout << endl;

return 0;

� 4-Line Explanation:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. Traverse the board; for each empty cell, try placing digits 1 to 9.
2. Use isValid() to ensure each digit fits Sudoku rules.
3. If valid, place the digit and continue recursively.
4. Backtrack if needed, and retry with other digits.

PROBLEM:167

Question:Expression Add Operators

C++ Code:
cpp

#include <iostream>

#include <vector>

#include <string>

using namespace std;

void helper(string& num, int target, int idx, long currVal, long prevOperand, string expr,
vector<string>& result) {

if (idx == num.length()) {

if (currVal == target) {

result.push_back(expr);

return;

for (int i = idx; i < num.length(); i++) {

// Avoid numbers with leading zeros

if (i != idx && num[idx] == '0') break;

string currStr = num.substr(idx, i - idx + 1);

long currNum = stol(currStr);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (idx == 0) {

// First number, no operator needed

helper(num, target, i + 1, currNum, currNum, currStr, result);

} else {

// Add '+'

helper(num, target, i + 1, currVal + currNum, currNum, expr + "+" + currStr, result);

// Add '-'

helper(num, target, i + 1, currVal - currNum, -currNum, expr + "-" + currStr, result);

// Add '*'

helper(num, target, i + 1, currVal - prevOperand + (prevOperand * currNum),

prevOperand * currNum, expr + "*" + currStr, result);

vector<string> addOperators(string num, int target) {

vector<string> result;

helper(num, target, 0, 0, 0, "", result);

return result;

� Example Usage:

cpp

int main() {

string num = "123";

int target = 6;

vector<string> result = addOperators(num, target);

for (string s : result) cout << s << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� 4-Line Explanation:

1. We recursively insert +, -, and * between digits and evaluate expressions.


2. Track the current value (currVal) and the previous operand (prevOperand) for *
handling.
3. Avoid numbers with leading zeros (e.g., "05").
4. If at the end of the string and the expression equals the target, add to result.

PROBLEM:168

Question:Introduction to Bit Manipulation


Bit Manipulation is a method to directly work with individual bits (0 or 1) of
integers using bitwise operators.
It is super fast and can solve many problems more efficiently than brute-force
methods.

� Bitwise Operators in C++


Operator Symbol Description Example (a=5, b=3)

AND & 1 if both bits are 1 5&3=1

OR ` ` 1 if at least one bit is 1

XOR ^ 1 if bits are different 5^3=6

NOT ~ Flips all bits (1's → 0's) ~5 = -6

Left Shift << Shifts bits left (×2) 5 << 1 = 10

Right Shift >> Shifts bits right (÷2) 5 >> 1 = 2

� Common Bit Tricks:


✅ Check if number is even or odd:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

if (n & 1) cout << "Odd"; else cout << "Even";

✅ Count number of set bits (1s):

cpp

int count = __builtin_popcount(n); // GCC/Clang

✅ Check if k-th bit is set:

cpp

if (n & (1 << k)) cout << "Yes";

✅ Set k-th bit:

cpp

n = n | (1 << k);

✅ Unset (clear) k-th bit:

cpp

n = n & ~(1 << k);

✅ Toggle k-th bit:

cpp

n = n ^ (1 << k);

� Loop through all subsets of a set:


cpp

int n = 3; // Set of 3 elements → 2^3 = 8 subsetsfor (int mask = 0; mask < (1 << n); mask++) {

for (int i = 0; i < n; i++) {

if (mask & (1 << i))

cout << i << " ";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << endl;

� 4-Line Summary:
1. Bit manipulation works directly at the binary level for fast computation.
2. Operators like <<, >>, &, |, ^, ~ let us modify individual bits.
3. It's used in subset generation, parity checking, optimization problems, etc.
4. Mastering it helps in competitive coding and system design!

PROBLEM:169

Question:Check if the i-th bit is set or not

C++ Code:

cpp

#include <iostream>

using namespace std;

bool isBitSet(int n, int i) {

return (n & (1 << i)) != 0;

int main() {

int n = 10; // binary: 1010

int i = 3;

if (isBitSet(n, i))

cout << "Bit " << i << " is set.\n";

else

cout << "Bit " << i << " is not set.\n";

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� 4-Line Explanation:

1. (1 << i) shifts 1 to the i-th position (makes a mask).


2. n & (1 << i) checks if that bit in n is 1.
3. If the result is non-zero, the bit is set.
4. Otherwise, it's not set.

PROBLEM:170

Question: Check if a Number is Odd or Not

C++ Code:

cpp

#include <iostream>

using namespace std;

bool isOdd(int n) {

return (n & 1);

int main() {

int n = 7;

if (isOdd(n))

cout << n << " is odd\n";

else

cout << n << " is even\n";

return 0;

� 4-Line Explanation:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. In binary, even numbers end in 0, odd numbers end in 1.
2. n & 1 checks the last bit of n.
3. If it’s 1, the number is odd.
4. If it’s 0, the number is even.

� Example:

cpp

n = 7 → binary: 0111 → last bit = 1 → odd ✅

n = 8 → binary: 1000 → last bit = 0 → even ❌

PROBLEM:171

Question: Check if a Number is Power of 2

C++ Code:

cpp

#include <iostream>

using namespace std;

bool isPowerOfTwo(int n) {

if (n <= 0) return false;

return (n & (n - 1)) == 0;

int main() {

int n = 16;

if (isPowerOfTwo(n))

cout << n << " is a power of 2\n";

else

cout << n << " is not a power of 2\n";

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� 4-Line Explanation:

1. A power of 2 has only one set bit (e.g. 2^4 = 16 → 10000).


2. Subtracting 1 flips all bits after that set bit (e.g. 16-1 = 15 → 01111).
3. n & (n-1) becomes 0 only for powers of 2.
4. Also check n > 0 to handle non-positive numbers.

� Example:

n Binary n & (n-1) Power of 2?

16 10000 00000 ✅ Yes

18 10010 10000 ❌ No

1 00001 00000 ✅ Yes

0 00000 - ❌ No

PROBLEM:172

Question: Count the Number of Set Bits in a Number

C++ Code (Kernighan’s Algorithm - Efficient)

cpp

#include <iostream>

using namespace std;

int countSetBits(int n) {

int count = 0;

while (n) {

n = n & (n - 1); // removes the lowest set bit

count++;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return count;

int main() {

int n = 29; // binary: 11101

cout << "Number of set bits in " << n << " is " << countSetBits(n) << endl;

return 0;

� 4-Line Explanation:

1. Subtracting 1 from n flips the rightmost set bit and all bits after it.
2. n & (n - 1) clears the lowest set bit.
3. Repeat until n becomes 0, counting how many times it happens.
4. This runs in O(number of set bits) — very efficient!

PROBLEM:173

Question: Set/Unset the Rightmost Unset Bit

Formula:

cpp

n | (n + 1)

� Example:

cpp

n = 18 → binary: 10010

n | (n + 1) = 18 | 19 = 10011 → 19 ✅

✅ C++ Code:

cpp

int setRightmostUnsetBit(int n) {

return n | (n + 1);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

✅ 2. Unset the rightmost unset bit

Technically we can’t directly unset a 0, but we often mean “set the rightmost
set bit to 0”.

� Formula (for clearing rightmost set bit):

cpp

n & (n - 1)

But if you really want to turn the first 0 into 0 again, you'd need to:

� Trick to force-unset the rightmost 0:

cpp

int unsetRightmostUnsetBit(int n) {

int mask = ~n & (n + 1); // isolates the rightmost 0

return n & ~mask;

� 4-Line Explanation:
1. n | (n + 1) sets the rightmost 0 to 1.
2. n & (n - 1) clears the rightmost 1 (if that's your goal).
3. To actually unset the rightmost 0, use a mask: ~n & (n + 1).
4. Apply that mask to n using n & ~mask.

PROBLEM:174

Question: Swap Two Numbers in C++


1. Using a Temporary Variable (Traditional Way)

cpp

int a = 5, b = 10;int temp = a;

a = b;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


b = temp;

✅ 2. Without Temporary Variable (Using Arithmetic)

cpp

int a = 5, b = 10;

a = a + b;

b = a - b;

a = a - b;

⚠! Be cautious: this can overflow if a + b becomes too large.

✅ 3. Using XOR (Bitwise Swap Trick)

cpp

int a = 5, b = 10;

a = a ^ b;

b = a ^ b;

a = a ^ b;

✅ No temp variable, no overflow — neat bit manipulation trick!

� 4-Line Explanation:
1. Swapping means exchanging values between two variables.
2. You can use a third variable (temp) or just math/XOR.
3. a = a ^ b stores combined info; XOR-ing again gives back original values.
4. XOR swap is safe, fast, and memory-efficient — great for interviews!

PROBLEM:175

Question:Divide Two Integers Without Using *, /, or %

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code (Using Bit Manipulation):

cpp

#include <iostream>

#include <climits>

using namespace std;

int divide(int dividend, int divisor) {

// Handle edge case overflow

if (dividend == INT_MIN && divisor == -1)

return INT_MAX;

// Convert to long to avoid overflow and use absolute values

long long a = abs((long long)dividend);

long long b = abs((long long)divisor);

int result = 0;

// Subtract divisor shifted left by powers of 2

for (int i = 31; i >= 0; i--) {

if ((a >> i) >= b) {

a -= (b << i);

result += (1 << i);

// Determine the sign of the result

return (dividend > 0) ^ (divisor > 0) ? -result : result;

int main() {

int dividend = 43, divisor = -8;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Quotient = " << divide(dividend, divisor) << endl;

return 0;

� 4-Line Explanation:
1. Shift divisor left (<< i) to multiply by powers of 2 and subtract it from dividend.
2. Add the corresponding 1 << i to the result each time.
3. This simulates division by repeated subtraction using bit manipulation.
4. Use XOR to determine the sign of the final result.

� Edge Case:

cpp

divide(INT_MIN, -1) → causes overflow → return INT_MAX

PROBLEM:176
Question: Count number of bits to be flipped to convert A to B

C++ Code

cpp

#include <iostream>using namespace std;

int countBitsToFlip(int A, int B) {

int xorVal = A ^ B; // XOR gives bits that are different

int count = 0;

while (xorVal) {

count += xorVal & 1; // check if last bit is 1

xorVal >>= 1; // right shift to check next bit

return count;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Example usage:// int main() {// int A = 29, B = 15;// cout << "Bits to flip: " <<
countBitsToFlip(A, B) << endl;// return 0;// }

� Explanation in Four Lines

1. XOR of A and B gives a number where set bits represent differing positions.
2. Count how many set bits are in the XOR result.
3. Each set bit corresponds to one flip needed.
4. Use bitwise AND and right shift to count the set bits.

PROBLEM:177

Question:find the number that appears an odd number of times


C++ Code

cpp

#include <iostream>#include <vector>using namespace std;

int findOddOccurringNumber(const vector<int>& arr) {

int result = 0;

for (int num : arr) {

result ^= num; // XOR cancels out even occurrences

return result;

// Example usage:// int main() {// vector<int> arr = {1, 2, 3, 2, 3, 1, 3};// cout << "Odd
occurring number: " << findOddOccurringNumber(arr) << endl;// return 0;// }

� Explanation in Four Lines

1. XOR of a number with itself is 0, and XOR with 0 gives the number.
2. All even-occurring numbers cancel out through XOR.
3. The number that appears odd times remains at the end.
4. Loop through the array, XOR all elements to get the result.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:178

Question:Power Set
Definition: The power set is the set of all subsets, including the empty set and the set itself.

Example:
Input: "abc"
Output: ["", "a", "b", "c", "ab", "ac", "bc", "abc"]

✅ C++ Code (Using Bitmasking)

cpp

#include <iostream>#include <vector>#include <string>using namespace std;

vector<string> powerSet(string str) {

int n = str.length();

int powSize = 1 << n; // 2^n subsets

vector<string> result;

for (int i = 0; i < powSize; ++i) {

string subset = "";

for (int j = 0; j < n; ++j) {

if (i & (1 << j)) {

subset += str[j];

result.push_back(subset);

return result;

// Example usage:// int main() {// string input = "abc";// vector<string> subsets =
powerSet(input);// for (string s : subsets) cout << s << endl;// return 0;// }

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Explanation in Four Lines

1. Use a loop from 0 to 2^n - 1, where each number represents a subset.


2. Each bit in the number represents whether to include a character.
3. Use bitwise AND to check if a bit is set, and include corresponding char.
4. Collect all subsets in a vector and return.

PROBLEM:179

Question:find the XOR of all numbers from L to R


C++ Code

cpp

#include <iostream>using namespace std;

// XOR from 0 to nint xorTill(int n) {

if (n % 4 == 0) return n;

else if (n % 4 == 1) return 1;

else if (n % 4 == 2) return n + 1;

else return 0;

// XOR from L to Rint xorFromLtoR(int L, int R) {

return xorTill(R) ^ xorTill(L - 1);

// Example usage:

int main() {

int L = 3, R = 9;

cout << "XOR from " << L << " to " << R << " is " << xorFromLtoR(L, R) << endl;

return 0;

� Explanation in Four Lines

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. XOR from 0 to n has a repeating pattern every 4 numbers.
2. Precompute XOR from 0 to R and from 0 to L-1.
3. XOR of those two gives XOR from L to R.
4. This runs in O(1) time – super efficient!

PROBLEM:180

Question:find the two numbers that appear an odd number of times


C++ Code

cpp

#include <iostream>#include <vector>using namespace std;

void findTwoOddNumbers(const vector<int>& arr) {

int xorAll = 0;

// Step 1: XOR all elements. Result = A ^ B (A and B are odd-occuring numbers)

for (int num : arr)

xorAll ^= num;

// Step 2: Find a set bit in xorAll (rightmost set bit)

int rightmostSetBit = xorAll & -xorAll;

int x = 0, y = 0;

// Step 3: Divide elements in two groups based on set bit

for (int num : arr) {

if (num & rightmostSetBit)

x ^= num; // one odd number

else

y ^= num; // other odd number

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Output the result

cout << "Two odd occurring numbers are: " << x << " and " << y << endl;

// Example usage:

int main() {

vector<int> arr = {4, 2, 4, 5, 2, 3, 3, 1};

findTwoOddNumbers(arr);

return 0;

� Explanation in Four Lines

1. XOR all elements to get xorAll = A ^ B, where A and B are the two odd numbers.
2. Find any set bit in xorAll to distinguish between A and B.
3. Partition array into two groups based on that bit and XOR separately.
4. You'll get both odd-occurring numbers individually.

PROBLEM:181

Question:Print Prime Factors of a Number


C++ Program to Print Prime Factors of a Number

cpp

#include <iostream>using namespace std;

void primeFactors(int n) {

cout << "Prime factors of " << n << " are: ";

while (n % 2 == 0) {

cout << 2 << " ";

n /= 2;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int i = 3; i * i <= n; i += 2) {

while (n % i == 0) {

cout << i << " ";

n /= i;

if (n > 2)

cout << n;

cout << endl;

int main() {

int num;

cout << "Enter a number: ";

cin >> num;

primeFactors(num);

return 0;

� Explanation (in 4 lines):

1. The program starts by dividing the number by 2 until it's no longer divisible.
2. Then it checks for odd divisors from 3 up to √n.
3. Each time a factor divides the number, it prints it and reduces the number.
4. If any prime >2 remains, it prints that as the final factor.

PROBLEM:182
Question:All Divisors of a Number

C++ Program to Print All Divisors of a Number

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>#include <cmath>using namespace std;

void printDivisors(int n) {

cout << "Divisors of " << n << " are: ";

for (int i = 1; i <= sqrt(n); i++) {

if (n % i == 0) {

cout << i << " ";

if (i != n / i) // To avoid printing square roots twice

cout << n / i << " ";

cout << endl;

int main() {

int num;

cout << "Enter a number: ";

cin >> num;

printDivisors(num);

return 0;

� Explanation (in 4 lines):

1. Loop from 1 to √n to find all numbers that divide n.


2. For each divisor i, both i and n/i are divisors.
3. Avoid duplicate printing if i == n/i (perfect square).
4. Efficiently prints all divisors in unordered form.

PROBLEM:183

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question:Sieve of Eratosthenes
C++ Program: Sieve of Eratosthenes (for Prime Numbers)

cpp

#include <iostream>#include <vector>using namespace std;

void sieveOfEratosthenes(int n) {

vector<bool> isPrime(n + 1, true);

isPrime[0] = isPrime[1] = false;

for (int i = 2; i * i <= n; i++) {

if (isPrime[i]) {

for (int j = i * i; j <= n; j += i)

isPrime[j] = false;

cout << "Prime numbers up to " << n << " are: ";

for (int i = 2; i <= n; i++) {

if (isPrime[i])

cout << i << " ";

cout << endl;

int main() {

int limit;

cout << "Enter the limit: ";

cin >> limit;

sieveOfEratosthenes(limit);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Explanation (in 4 lines):

1. We mark all numbers as prime initially in a boolean array.


2. Starting from 2, we eliminate all multiples of each prime.
3. We continue the process up to √n for efficiency.
4. Remaining true values in the array are prime numbers.

PROBLEM:184
Question:Find Prime Factorisation of a Number using Sieve

C++ Program: Prime Factorization Using Sieve (Efficient Method)

This approach uses a precomputed Smallest Prime Factor (SPF) array via sieve, allowing
fast factorization of any number up to n.

cpp

#include <iostream>#include <vector>using namespace std;

const int MAX = 1000000;vector<int> spf(MAX); // Smallest prime factor for every number

// Precompute SPF using modified sievevoid sieve() {

for (int i = 1; i < MAX; i++)

spf[i] = i;

for (int i = 2; i * i < MAX; i++) {

if (spf[i] == i) {

for (int j = i * i; j < MAX; j += i) {

if (spf[j] == j)

spf[j] = i;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

// Prime factorization using precomputed SPFvoid primeFactorization(int n) {

cout << "Prime factors of " << n << " are: ";

while (n != 1) {

cout << spf[n] << " ";

n /= spf[n];

cout << endl;

int main() {

sieve(); // Run once for all queries

int num;

cout << "Enter a number: ";

cin >> num;

primeFactorization(num);

return 0;

� Explanation (in 4 lines):

1. First, use a modified Sieve to compute the smallest prime factor (SPF) for all numbers.
2. To factorize any number n, keep dividing it by its SPF.
3. This gives prime factors in O(log n) time per query.
4. The sieve is run once, enabling fast multiple queries.

PROBLEM:185

Question: Power(n, x)

C++ Program: Compute n to the Power x (i.e., n^x)

cpp

#include <iostream>using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Function to calculate n^xlong long power(int n, int x) {

long long result = 1;

while (x > 0) {

if (x % 2 == 1)

result *= n;

n *= n;

x /= 2;

return result;

int main() {

int n, x;

cout << "Enter base (n): ";

cin >> n;

cout << "Enter exponent (x): ";

cin >> x;

cout << n << "^" << x << " = " << power(n, x) << endl;

return 0;

� Explanation (in 4 lines):

1. This uses binary exponentiation for efficient calculation.


2. If exponent x is odd, multiply result with base.
3. Square the base and halve the exponent at each step.
4. Time complexity is O(log x) — fast even for large exponents.

PROBLEM:186

Question:Stack Implementation Using Arrays

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Program: Stack Implementation Using Arrays

cpp

#include <iostream>using namespace std;

#define MAX 1000

class Stack {

int top;

int arr[MAX];

public:

Stack() { top = -1; }

bool push(int x) {

if (top >= MAX - 1) {

cout << "Stack Overflow\n";

return false;

arr[++top] = x;

cout << x << " pushed into stack\n";

return true;

int pop() {

if (top < 0) {

cout << "Stack Underflow\n";

return -1;

return arr[top--];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int peek() {

if (top < 0) {

cout << "Stack is Empty\n";

return -1;

return arr[top];

bool isEmpty() {

return top < 0;

};

int main() {

Stack s;

s.push(10);

s.push(20);

s.push(30);

cout << "Top element is " << s.peek() << endl;

cout << "Popped element is " << s.pop() << endl;

cout << "Stack empty? " << (s.isEmpty() ? "Yes" : "No") << endl;

return 0;

� Explanation (in 4 lines):

1. A stack class with an array and a top pointer is used.


2. push() adds elements on top and checks for overflow.
3. pop() removes and returns the top element or underflow warning.
4. Includes peek() and isEmpty() for stack operations.

PROBLEM:187

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question:Implement Queue using Arrays
C++ Program: Queue Implementation Using Arrays

cpp

#include <iostream>using namespace std;

#define MAX 1000

class Queue {

int front, rear;

int arr[MAX];

public:

Queue() {

front = rear = -1;

bool enqueue(int x) {

if (rear == MAX - 1) {

cout << "Queue Overflow\n";

return false;

if (front == -1) front = 0; // First insertion

arr[++rear] = x;

cout << x << " enqueued to queue\n";

return true;

int dequeue() {

if (front == -1 || front > rear) {

cout << "Queue Underflow\n";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return -1;

return arr[front++];

int peek() {

if (front == -1 || front > rear) {

cout << "Queue is Empty\n";

return -1;

return arr[front];

bool isEmpty() {

return front == -1 || front > rear;

};

int main() {

Queue q;

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

cout << "Front element is " << q.peek() << endl;

cout << "Dequeued element is " << q.dequeue() << endl;

cout << "Queue empty? " << (q.isEmpty() ? "Yes" : "No") << endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Explanation (in 4 lines):

1. A queue is managed using front and rear indices in an array.


2. enqueue() adds elements at the rear end with overflow check.
3. dequeue() removes elements from the front with underflow check.
4. Includes peek() and isEmpty() for common queue operations.

PROBLEM:188

Question:Implement Stack using Queue


C++ Program: Stack Implementation Using Queues

We'll implement a stack (LIFO) using two queues (FIFO).

✅ Method: Using Two Queues (Costly pop())

cpp

#include <iostream>#include <queue>using namespace std;

class Stack {

queue<int> q1, q2;

public:

// Push is O(1)

void push(int x) {

q1.push(x);

cout << x << " pushed into stack\n";

// Pop is O(n)

void pop() {

if (q1.empty()) {

cout << "Stack Underflow\n";

return;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Move elements except last to q2

while (q1.size() > 1) {

q2.push(q1.front());

q1.pop();

cout << q1.front() << " popped from stack\n";

q1.pop();

// Swap q1 and q2

swap(q1, q2);

int top() {

if (q1.empty()) {

cout << "Stack is Empty\n";

return -1;

// Move elements to q2 except last

while (q1.size() > 1) {

q2.push(q1.front());

q1.pop();

int val = q1.front(); // Top element

q2.push(val); // Put it back

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


q1.pop();

swap(q1, q2);

return val;

bool isEmpty() {

return q1.empty();

};

int main() {

Stack s;

s.push(10);

s.push(20);

s.push(30);

cout << "Top element: " << s.top() << endl;

s.pop();

cout << "Stack empty? " << (s.isEmpty() ? "Yes" : "No") << endl;

return 0;

� Explanation (in 4 lines):

1. We use two queues q1 and q2 to simulate stack behavior.


2. push() just enqueues in q1 (O(1)).
3. pop() moves all but last element to q2, then removes last (O(n)).
4. top() retrieves last element similarly and swaps queues.

PROBLEM:189

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question:Implement Queue using Stack
C++ Program: Queue Implementation Using Stacks

We'll implement a queue (FIFO) using two stacks (LIFO).

✅ Method: Using Two Stacks (Costly dequeue())

cpp

#include <iostream>#include <stack>using namespace std;

class Queue {

stack<int> s1, s2;

public:

// Enqueue is O(1)

void enqueue(int x) {

s1.push(x);

cout << x << " enqueued to queue\n";

// Dequeue is O(n)

int dequeue() {

if (s1.empty() && s2.empty()) {

cout << "Queue Underflow\n";

return -1;

if (s2.empty()) {

// Move all elements from s1 to s2 (reverse order)

while (!s1.empty()) {

s2.push(s1.top());

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


s1.pop();

int front = s2.top();

s2.pop();

return front;

int peek() {

if (s1.empty() && s2.empty()) {

cout << "Queue is Empty\n";

return -1;

if (s2.empty()) {

while (!s1.empty()) {

s2.push(s1.top());

s1.pop();

return s2.top();

bool isEmpty() {

return s1.empty() && s2.empty();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


};

int main() {

Queue q;

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

cout << "Front element: " << q.peek() << endl;

cout << "Dequeued element: " << q.dequeue() << endl;

cout << "Queue empty? " << (q.isEmpty() ? "Yes" : "No") << endl;

return 0;

� Explanation (in 4 lines):

1. We use two stacks: s1 for enqueue, s2 for dequeue.


2. enqueue() simply pushes to s1 (O(1)).
3. dequeue() transfers elements from s1 to s2 only if s2 is empty (O(n)).
4. This preserves FIFO order using LIFO structures.

PROBLEM:190
Question:Implement stack using Linkedlist

C++ Program: Stack Implementation Using Linked List

cpp

#include <iostream>using namespace std;

// Node structurestruct Node {

int data;

Node* next;

};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Stack class using Linked Listclass Stack {

Node* top;

public:

Stack() { top = nullptr; }

void push(int x) {

Node* newNode = new Node();

newNode->data = x;

newNode->next = top;

top = newNode;

cout << x << " pushed into stack\n";

void pop() {

if (top == nullptr) {

cout << "Stack Underflow\n";

return;

cout << top->data << " popped from stack\n";

Node* temp = top;

top = top->next;

delete temp;

int peek() {

if (top == nullptr) {

cout << "Stack is Empty\n";

return -1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return top->data;

bool isEmpty() {

return top == nullptr;

};

int main() {

Stack s;

s.push(10);

s.push(20);

s.push(30);

cout << "Top element is " << s.peek() << endl;

s.pop();

cout << "Stack empty? " << (s.isEmpty() ? "Yes" : "No") << endl;

return 0;

� Explanation (in 4 lines):

1. Each stack element is a node in a singly linked list.


2. push() creates a new node and makes it the new top.
3. pop() deletes the current top and updates the pointer.
4. peek() returns the top value, and isEmpty() checks for underflow.

PROBLEM:191
Question:Implement queue using Linkedlist

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Program: Queue Implementation Using Linked List

cpp

#include <iostream>using namespace std;

// Node structurestruct Node {

int data;

Node* next;

};

// Queue class using Linked Listclass Queue {

Node* front;

Node* rear;

public:

Queue() {

front = rear = nullptr;

void enqueue(int x) {

Node* newNode = new Node();

newNode->data = x;

newNode->next = nullptr;

if (rear == nullptr) {

front = rear = newNode;

} else {

rear->next = newNode;

rear = newNode;

cout << x << " enqueued to queue\n";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

void dequeue() {

if (front == nullptr) {

cout << "Queue Underflow\n";

return;

cout << front->data << " dequeued from queue\n";

Node* temp = front;

front = front->next;

if (front == nullptr)

rear = nullptr;

delete temp;

int peek() {

if (front == nullptr) {

cout << "Queue is Empty\n";

return -1;

return front->data;

bool isEmpty() {

return front == nullptr;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

};

int main() {

Queue q;

q.enqueue(10);

q.enqueue(20);

q.enqueue(30);

cout << "Front element is " << q.peek() << endl;

q.dequeue();

cout << "Queue empty? " << (q.isEmpty() ? "Yes" : "No") << endl;

return 0;

� Explanation (in 4 lines):

1. Each queue node holds data and a pointer to the next node.
2. enqueue() adds elements at the rear of the list.
3. dequeue() removes elements from the front of the list.
4. peek() returns the front value, and isEmpty() checks if the queue is empty.

PROBLEM:192
Question:Check for balanced paranthesis
C++ Program: Check for Balanced Parentheses

This program checks if an expression has balanced brackets: (), {}, [].

cpp

#include <iostream>#include <stack>using namespace std;

bool isMatching(char open, char close) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return (open == '(' && close == ')') ||

(open == '{' && close == '}') ||

(open == '[' && close == ']');

bool isBalanced(string expr) {

stack<char> s;

for (char ch : expr) {

if (ch == '(' || ch == '{' || ch == '[') {

s.push(ch);

} else if (ch == ')' || ch == '}' || ch == ']') {

if (s.empty() || !isMatching(s.top(), ch))

return false;

s.pop();

return s.empty();

int main() {

string expr;

cout << "Enter an expression: ";

cin >> expr;

if (isBalanced(expr))

cout << "Balanced\n";

else

cout << "Not Balanced\n";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Explanation (in 4 lines):

1. We use a stack to track opening brackets.


2. For each closing bracket, we check for matching with top of the stack.
3. If a mismatch occurs or stack is empty too early → not balanced.
4. If stack is empty at end, the expression is balanced.

PROBLEM:193
Question:Implement Min Stack

C++ Program: Min Stack (with O(1) getMin)

A Min Stack supports standard stack operations and retrieves the minimum element in O(1)
time.

� Approach: Use Two Stacks

One for normal elements (s)

One to keep track of the current minimums (minStack)

cpp

#include <iostream>#include <stack>using namespace std;

class MinStack {

stack<int> s;

stack<int> minStack;

public:

void push(int x) {

s.push(x);

if (minStack.empty() || x <= minStack.top())

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


minStack.push(x);

cout << x << " pushed into stack\n";

void pop() {

if (s.empty()) {

cout << "Stack Underflow\n";

return;

if (s.top() == minStack.top())

minStack.pop();

cout << s.top() << " popped from stack\n";

s.pop();

int top() {

if (s.empty()) {

cout << "Stack is Empty\n";

return -1;

return s.top();

int getMin() {

if (minStack.empty()) {

cout << "Stack is Empty\n";

return -1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return minStack.top();

bool isEmpty() {

return s.empty();

};

int main() {

MinStack ms;

ms.push(5);

ms.push(3);

ms.push(7);

cout << "Minimum: " << ms.getMin() << endl;

ms.pop();

cout << "Minimum: " << ms.getMin() << endl;

ms.pop();

cout << "Top: " << ms.top() << endl;

return 0;

� Explanation (in 4 lines):

1. A second stack stores the current minimum at each level.


2. On push(), update minStack only if the new element is ≤ current min.
3. On pop(), if popped element is min, pop from minStack too.
4. getMin() gives the minimum in O(1) time from minStack.

PROBLEM:194
Question:Infix to Postfix Conversion Using Stack

C++ Program: Infix to Postfix Conversion Using Stack

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Infix: A + B * C
Postfix: A B C * +

� Approach:

Use a stack to store operators and follow operator precedence and associativity rules.

cpp

#include <iostream>#include <stack>#include <string>using namespace std;

// Function to return precedence of operatorsint precedence(char op) {

if (op == '^') return 3;

if (op == '*' || op == '/') return 2;

if (op == '+' || op == '-') return 1;

return 0;

// Function to check if character is operandbool isOperand(char ch) {

return isalnum(ch); // letters or digits

// Infix to Postfix conversionstring infixToPostfix(string infix) {

stack<char> st;

string postfix = "";

for (char ch : infix) {

if (isOperand(ch)) {

postfix += ch;

else if (ch == '(') {

st.push(ch);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


else if (ch == ')') {

while (!st.empty() && st.top() != '(') {

postfix += st.top();

st.pop();

if (!st.empty()) st.pop(); // Remove '('

else { // operator

while (!st.empty() && precedence(ch) <= precedence(st.top())) {

if (ch == '^' && st.top() == '^') break; // right-associative

postfix += st.top();

st.pop();

st.push(ch);

while (!st.empty()) {

postfix += st.top();

st.pop();

return postfix;

int main() {

string infix;

cout << "Enter infix expression: ";

cin >> infix;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


string postfix = infixToPostfix(infix);

cout << "Postfix expression: " << postfix << endl;

return 0;

� Explanation (in 4 lines):

1. Operands go straight to the output; operators go into a stack.


2. Handle () with care — push (, pop till ( on ).
3. Use precedence and associativity to decide when to pop from stack.
4. After scanning, pop all remaining operators to postfix.

The PDF created by Abhishek Rathor (Instagram:SYNTAX


ERROR)

PROBLEM:195
Question:Prefix to Infix Conversion

C++ Program: Prefix to Infix Conversion Using Stack

� Example:
Prefix: *+AB-CD → Infix: ((A+B)*(C-D))

� Approach:

We scan the prefix expression from right to left, and use a stack to build expressions.

cpp

#include <iostream>#include <stack>#include <string>using namespace std;

// Function to check if character is operatorbool isOperator(char ch) {

return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^');

// Function to convert prefix to infixstring prefixToInfix(string prefix) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


stack<string> st;

// Scan from right to left

for (int i = prefix.length() - 1; i >= 0; i--) {

char ch = prefix[i];

if (isOperator(ch)) {

// Pop two operands

string op1 = st.top(); st.pop();

string op2 = st.top(); st.pop();

// Combine them

string expr = "(" + op1 + ch + op2 + ")";

st.push(expr);

} else {

// Operand: push as string

st.push(string(1, ch));

return st.top();

int main() {

string prefix;

cout << "Enter prefix expression: ";

cin >> prefix;

string infix = prefixToInfix(prefix);

cout << "Infix expression: " << infix << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Explanation (in 4 lines):

1. We scan prefix from right to left.


2. If the character is an operand, push it to the stack.
3. If it's an operator, pop two operands and form an infix string.
4. Final result on the stack is the full infix expression.

PROBLEM:196

Question:Prefix to Postfix Conversion

C++ Program: Prefix to Postfix Conversion Using Stack

� Example:
Prefix: *+AB-CD → Postfix: AB+CD-*

� Approach:

Scan the prefix expression right to left, use a stack to build postfix expressions.

cpp

#include <iostream>#include <stack>#include <string>using namespace std;

// Function to check if character is operatorbool isOperator(char ch) {

return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^');

// Function to convert prefix to postfixstring prefixToPostfix(string prefix) {

stack<string> st;

for (int i = prefix.length() - 1; i >= 0; i--) {

char ch = prefix[i];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (isOperator(ch)) {

// Pop two operands

string op1 = st.top(); st.pop();

string op2 = st.top(); st.pop();

// Build postfix expression

string expr = op1 + op2 + ch;

st.push(expr);

} else {

// Operand: push as string

st.push(string(1, ch));

return st.top();

int main() {

string prefix;

cout << "Enter prefix expression: ";

cin >> prefix;

string postfix = prefixToPostfix(prefix);

cout << "Postfix expression: " << postfix << endl;

return 0;

� Explanation (in 4 lines):

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. Traverse the prefix string from right to left.
2. Push operands directly to the stack.
3. When an operator appears, pop two operands, combine to postfix (op1 op2
operator).
4. The stack's top will be the full postfix expression.

PROBLEM:197

Question:Postfix to Prefix Conversion

C++ Program: Postfix to Prefix Conversion Using Stack

� Example:
Postfix: AB+CD-* → Prefix: *+AB-CD

� Approach:

We scan the postfix expression from left to right and use a stack to build the prefix
expression.

cpp

#include <iostream>#include <stack>#include <string>using namespace std;

// Function to check if character is operatorbool isOperator(char ch) {

return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^');

// Function to convert postfix to prefixstring postfixToPrefix(string postfix) {

stack<string> st;

// Scan the postfix expression from left to right

for (int i = 0; i < postfix.length(); i++) {

char ch = postfix[i];

if (isOperator(ch)) {

// Pop two operands

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


string op2 = st.top(); st.pop();

string op1 = st.top(); st.pop();

// Combine them in prefix order

string expr = ch + op1 + op2;

st.push(expr);

} else {

// Operand: push as string

st.push(string(1, ch));

return st.top();

int main() {

string postfix;

cout << "Enter postfix expression: ";

cin >> postfix;

string prefix = postfixToPrefix(postfix);

cout << "Prefix expression: " << prefix << endl;

return 0;

� Explanation (in 4 lines):

1. We traverse the postfix string from left to right.


2. Push operands directly to the stack.
3. When an operator appears, pop two operands and form the prefix expression (operator
op1 op2).

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


4. The final result on the stack will be the complete prefix expression.

PROBLEM:198

Question:Postfix to Infix

C++ Program: Postfix to Infix Conversion Using Stack

� Example:
Postfix: AB+C* → Infix: (A + B) * C

� Approach:

We scan the postfix expression from left to right, and use a stack to build the infix
expression.

cpp

#include <iostream>#include <stack>#include <string>using namespace std;

// Function to check if character is operatorbool isOperator(char ch) {

return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^');

// Function to convert postfix to infixstring postfixToInfix(string postfix) {

stack<string> st;

for (char ch : postfix) {

if (isOperator(ch)) {

// Pop two operands

string op2 = st.top(); st.pop();

string op1 = st.top(); st.pop();

// Combine them in infix order

string expr = "(" + op1 + ch + op2 + ")";

st.push(expr);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


} else {

// Operand: push as string

st.push(string(1, ch));

return st.top();

int main() {

string postfix;

cout << "Enter postfix expression: ";

cin >> postfix;

string infix = postfixToInfix(postfix);

cout << "Infix expression: " << infix << endl;

return 0;

� Explanation (in 4 lines):

1. Traverse the postfix expression from left to right.


2. Push operands directly to the stack.
3. When an operator appears, pop two operands and form the infix expression ((op1
operator op2)).
4. The final result on the stack will be the complete infix expression.

PROBLEM:199

Question:Convert Infix To Prefix Notation

C++ Program: Infix to Prefix Conversion Using Stack

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Example:
Infix: (A + B) * (C - D) → Prefix: *+AB-CD

� Approach:

Reverse the infix expression.

Convert it to postfix using the same logic, but treat parentheses in reverse.

Reverse the result to get the prefix expression.

cpp

#include <iostream>#include <stack>#include <algorithm>#include <string>using namespace


std;

// Function to return precedence of operatorsint precedence(char op) {

if (op == '^') return 3;

if (op == '*' || op == '/') return 2;

if (op == '+' || op == '-') return 1;

return 0;

// Function to check if character is operandbool isOperand(char ch) {

return isalnum(ch); // letters or digits

// Function to reverse a stringstring reverseStr(string str) {

reverse(str.begin(), str.end());

return str;

// Function to convert infix to postfixstring infixToPostfix(string infix) {

stack<char> st;

string postfix = "";

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (char ch : infix) {

if (isOperand(ch)) {

postfix += ch;

else if (ch == '(') {

st.push(ch);

else if (ch == ')') {

while (!st.empty() && st.top() != '(') {

postfix += st.top();

st.pop();

if (!st.empty()) st.pop(); // Remove '('

else { // operator

while (!st.empty() && precedence(ch) <= precedence(st.top())) {

if (ch == '^' && st.top() == '^') break; // right-associative

postfix += st.top();

st.pop();

st.push(ch);

while (!st.empty()) {

postfix += st.top();

st.pop();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return postfix;

// Function to convert infix to prefixstring infixToPrefix(string infix) {

// Reverse the infix expression

infix = reverseStr(infix);

// Replace '(' with ')' and vice versa

for (int i = 0; i < infix.length(); i++) {

if (infix[i] == '(') {

infix[i] = ')';

} else if (infix[i] == ')') {

infix[i] = '(';

// Convert the reversed infix to postfix

string postfix = infixToPostfix(infix);

// Reverse the postfix to get prefix

return reverseStr(postfix);

int main() {

string infix;

cout << "Enter infix expression: ";

cin >> infix;

string prefix = infixToPrefix(infix);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << "Prefix expression: " << prefix << endl;

return 0;

� Explanation (in 4 lines):

1. Reverse the infix expression for easier handling of parentheses.


2. Swap ( with ) and vice versa for correct precedence rules in the reversed string.
3. Convert the reversed infix expression to postfix using standard precedence and
associativity rules.
4. Reverse the resulting postfix expression to get the final prefix expression.

PROBLEM:200

Question:Next Greater Element

C++ Program: Find Next Greater Element

The Next Greater Element (NGE) for an element x in an array is the first element to the
right of x which is greater than x. If no such element exists, the NGE for x is -1.

� Approach:

Use a stack to efficiently find the next greater element for each element of the array.

cpp

#include <iostream>#include <stack>#include <vector>using namespace std;

void nextGreaterElement(const vector<int>& arr) {

stack<int> st;

int n = arr.size();

vector<int> nge(n, -1); // Initialize result array with -1

// Traverse the array from right to left

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int i = n - 1; i >= 0; i--) {

// Pop elements from the stack that are less than or equal to the current element

while (!st.empty() && st.top() <= arr[i]) {

st.pop();

// If stack is not empty, the top of the stack is the NGE

if (!st.empty()) {

nge[i] = st.top();

// Push the current element onto the stack

st.push(arr[i]);

// Print the Next Greater Element for each element in the array

for (int i = 0; i < n; i++) {

cout << "Next Greater Element for " << arr[i] << " is " << nge[i] << endl;

int main() {

vector<int> arr = {4, 5, 2, 10, 8};

nextGreaterElement(arr);

return 0;

� Explanation (in 4 lines):

1. We traverse the array from right to left, using a stack to store elements.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


2. For each element, we pop stack elements that are smaller than or equal to the current
element.
3. If the stack is non-empty, the top of the stack is the next greater element for the current
element.
4. Push the current element onto the stack to be considered for the next elements.

PROBLEM:201

Question:Next Greater Element 2

C++ Program: Next Greater Element II (Circular Array)

In the Next Greater Element II problem, we are given an array, and we need to find the
next greater element for each element in the array. Unlike the typical problem where the
array is linear, here the array is circular, meaning that after reaching the last element, we
loop back to the first element.

� Approach:

Use a stack to help track the next greater element for each element in the array, and simulate
a circular array by iterating through the array twice.

cpp

#include <iostream>#include <stack>#include <vector>using namespace std;

void nextGreaterElementCircular(const vector<int>& arr) {

int n = arr.size();

stack<int> st;

vector<int> nge(n, -1); // Initialize result array with -1

// Iterate the array twice to simulate the circular nature

for (int i = 2 * n - 1; i >= 0; i--) {

int currentIndex = i % n; // Simulate the circular index

// Pop elements from the stack that are less than or equal to the current element

while (!st.empty() && arr[st.top()] <= arr[currentIndex]) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


st.pop();

// If stack is not empty, the top of the stack is the NGE

if (!st.empty()) {

nge[currentIndex] = arr[st.top()];

// Push the current element index onto the stack

st.push(currentIndex);

// Print the Next Greater Element for each element in the array

for (int i = 0; i < n; i++) {

cout << "Next Greater Element for " << arr[i] << " is " << nge[i] << endl;

int main() {

vector<int> arr = {1, 2, 1};

nextGreaterElementCircular(arr);

return 0;

� Explanation (in 4 lines):

1. We iterate through the array twice to simulate the circular nature of the problem.
2. For each element, we use a stack to track the next greater element.
3. The stack helps us efficiently find the next greater element by removing smaller elements
and keeping track of potential candidates.
4. Finally, the result array contains the next greater elements for all elements, considering the
circular nature of the array.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:202

Question: Next Smaller Element

C++ Program: Next Smaller Element

The Next Smaller Element (NSE) for an element x in an array is the first element to the
right of x which is smaller than x. If no such element exists, the NSE for x is -1.

� Approach:

Use a stack to efficiently find the next smaller element for each element of the array.

cpp

#include <iostream>#include <stack>#include <vector>using namespace std;

void nextSmallerElement(const vector<int>& arr) {

stack<int> st;

int n = arr.size();

vector<int> nse(n, -1); // Initialize result array with -1

// Traverse the array from right to left

for (int i = n - 1; i >= 0; i--) {

// Pop elements from the stack that are greater than or equal to the current element

while (!st.empty() && st.top() >= arr[i]) {

st.pop();

// If stack is not empty, the top of the stack is the NSE

if (!st.empty()) {

nse[i] = st.top();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Push the current element onto the stack

st.push(arr[i]);

// Print the Next Smaller Element for each element in the array

for (int i = 0; i < n; i++) {

cout << "Next Smaller Element for " << arr[i] << " is " << nse[i] << endl;

int main() {

vector<int> arr = {4, 5, 2, 10, 8};

nextSmallerElement(arr);

return 0;

� Explanation (in 4 lines):

1. We traverse the array from right to left using a stack.


2. For each element, we pop elements from the stack that are greater than or equal to the
current element.
3. If the stack is not empty, the top of the stack is the next smaller element.
4. The result array stores the next smaller element for each element in the array.

PROBLEM:203

Question: Number of NGEs to the right

C++ Program: Count Number of Next Greater Elements (NGEs) to the Right

This problem asks for the count of Next Greater Elements (NGEs) for each element in the
array. The count for an element x is the number of elements to its right that are greater than x.

� Approach:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


We can use a stack to track the elements in a way that allows us to count how many elements
to the right are greater than the current element.

cpp

CopyEdit

#include <iostream>#include <stack>#include <vector>using namespace std;

void countNGEsToRight(const vector<int>& arr) {

int n = arr.size();

vector<int> ngeCount(n, 0); // Initialize count array with 0

stack<int> st;

// Traverse the array from right to left

for (int i = n - 1; i >= 0; i--) {

// Pop elements from the stack that are smaller than or equal to the current element

while (!st.empty() && st.top() <= arr[i]) {

st.pop();

// Count the number of elements on the stack that are greater than the current element

ngeCount[i] = st.size();

// Push the current element onto the stack

st.push(arr[i]);

// Print the count of NGEs for each element

for (int i = 0; i < n; i++) {

cout << "Number of NGEs to the right of " << arr[i] << " is " << ngeCount[i] << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

vector<int> arr = {4, 5, 2, 10, 8};

countNGEsToRight(arr);

return 0;

� Explanation (in 4 lines):

1. Traverse the array from right to left using a stack to maintain elements.
2. For each element, we count how many elements in the stack are greater than the current
element.
3. We keep track of this count in a ngeCount array.
4. The stack holds only elements that could potentially be the next greater element for the
future elements.

PROBLEM:204

Question: Trapping Rainwater

C++ Program: Trapping Rainwater Problem

The Trapping Rainwater problem asks for the total amount of water that can be trapped
between bars of different heights after it rains.

� Example:
Input: {0,1,0,2,1,0,1,3,2,1,2,1}
Output: 6 units of water

Approach (Two Arrays Method):

Create two arrays:

leftMax[i] stores the max height to the left of index i.

rightMax[i] stores the max height to the right of index i.

For each index, water trapped is:


min(leftMax[i], rightMax[i]) - height[i]

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>#include <vector>using namespace std;

int trapRainWater(const vector<int>& height) {

int n = height.size();

if (n == 0) return 0;

vector<int> leftMax(n), rightMax(n);

int water = 0;

// Fill leftMax array

leftMax[0] = height[0];

for (int i = 1; i < n; i++) {

leftMax[i] = max(leftMax[i - 1], height[i]);

// Fill rightMax array

rightMax[n - 1] = height[n - 1];

for (int i = n - 2; i >= 0; i--) {

rightMax[i] = max(rightMax[i + 1], height[i]);

// Calculate trapped water

for (int i = 0; i < n; i++) {

water += min(leftMax[i], rightMax[i]) - height[i];

return water;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

int main() {

vector<int> height = {0,1,0,2,1,0,1,3,2,1,2,1};

cout << "Trapped water: " << trapRainWater(height) << " units" << endl;

return 0;

� Explanation (in 4 lines):

1. For each bar, we compute the maximum height to its left and right.
2. Water above a bar depends on the minimum of those two heights minus the bar’s height.
3. We sum this trapped water for all bars.
4. The final result is the total water that can be trapped after raining.

PROBLEM:205

Question: Sum of subarray minimum

C++ Program: Sum of Subarray Minimums

� Problem:
Given an array of integers, find the sum of the minimum element of all subarrays.
Return the answer modulo 109+710^9 + 7109+7 (as the result can be large).

� Efficient Approach (Monotonic Stack + Contribution Technique)

For each element, calculate:

How many subarrays it is the minimum for.

Use Previous Less Element (PLE) and Next Less Element (NLE) to count.

Each element contributes:


arr[i] * countLeft * countRight

cpp

#include <iostream>#include <vector>#include <stack>using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


const int MOD = 1e9 + 7;

int sumSubarrayMins(vector<int>& arr) {

int n = arr.size();

vector<int> ple(n), nle(n);

stack<int> st;

// Previous Less Element (PLE)

for (int i = 0; i < n; i++) {

while (!st.empty() && arr[st.top()] > arr[i])

st.pop();

ple[i] = st.empty() ? -1 : st.top();

st.push(i);

// Clear stack for NLE

while (!st.empty()) st.pop();

// Next Less Element (NLE)

for (int i = n - 1; i >= 0; i--) {

while (!st.empty() && arr[st.top()] >= arr[i])

st.pop();

nle[i] = st.empty() ? n : st.top();

st.push(i);

// Calculate result

long long result = 0;

for (int i = 0; i < n; i++) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


long long left = i - ple[i];

long long right = nle[i] - i;

result = (result + arr[i] * left * right) % MOD;

return result;

int main() {

vector<int> arr = {3, 1, 2, 4};

cout << "Sum of subarray minimums: " << sumSubarrayMins(arr) << endl;

return 0;

}The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

� Explanation (in 4 lines):

1. Use monotonic stacks to find for each element:


2. How far left and right it can extend while still being the minimum.
3. Count of such subarrays: (i - PLE) * (NLE - i)
4. Each element contributes: value * leftCount * rightCount
5. Sum all contributions and take modulo 109+710^9 + 7109+7.

PROBLEM:206

Question: Asteroid Collision

C++ Program: Asteroid Collision

� Problem Statement:

You're given an array of integers representing asteroids moving in space.

Each integer represents the size and direction:

Positive → moving right

Negative → moving left

When two asteroids collide:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


The smaller one explodes.

If equal, both explode.

If they move in the same direction, they never collide.

Return the state of the asteroids after all collisions.

� Approach: Use a Stack

Loop through each asteroid.

Use a stack to track surviving asteroids.

Handle collisions when a left-moving asteroid (< 0) meets a right-moving asteroid (>
0 on top of stack).

cpp

#include <iostream>#include <vector>#include <stack>using namespace std;

vector<int> asteroidCollision(vector<int>& asteroids) {

stack<int> st;

for (int asteroid : asteroids) {

bool destroyed = false;

while (!st.empty() && asteroid < 0 && st.top() > 0) {

if (st.top() < -asteroid) {

st.pop(); // Right asteroid explodes, keep checking

} else if (st.top() == -asteroid) {

st.pop(); // Both explode

destroyed = true;

break;

} else {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


destroyed = true; // Left asteroid explodes

break;

if (!destroyed) {

st.push(asteroid);

vector<int> result(st.size());

for (int i = st.size() - 1; i >= 0; i--) {

result[i] = st.top();

st.pop();

return result;

int main() {

vector<int> asteroids = {5, 10, -5};

vector<int> result = asteroidCollision(asteroids);

cout << "Asteroids after collision: ";

for (int a : result) {

cout << a << " ";

cout << endl;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return 0;

� Explanation (in 4 lines):

1. Use a stack to simulate asteroid collisions in sequence.


2. When a left-moving asteroid meets a right-moving one, check for collision
conditions.
3. Depending on the size, either one or both explode.
4. Remaining asteroids in the stack represent the final state.

PROBLEM:207

Question: Sum of subarray ranges

C++ Program: Sum of Subarray Ranges

� Problem:
Given an integer array nums, return the sum of ranges of all subarrays.

The range of a subarray is max - min of its elements.

� Efficient Approach (Monotonic Stack)

We calculate:

Sum of all subarray maximums.

Sum of all subarray minimums.


Then:
Answer = Sum of subarray maximums − Sum of subarray minimums

cpp

#include <iostream>#include <vector>#include <stack>using namespace std;

typedef long long ll;

ll sumSubarrayRanges(vector<int>& nums) {

int n = nums.size();

vector<int> pleMin(n), nleMin(n);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<int> pleMax(n), nleMax(n);

stack<int> st;

// Previous Less Element for Minimum

for (int i = 0; i < n; i++) {

while (!st.empty() && nums[st.top()] > nums[i]) st.pop();

pleMin[i] = st.empty() ? -1 : st.top();

st.push(i);

while (!st.empty()) st.pop();

// Next Less Element for Minimum

for (int i = n - 1; i >= 0; i--) {

while (!st.empty() && nums[st.top()] >= nums[i]) st.pop();

nleMin[i] = st.empty() ? n : st.top();

st.push(i);

while (!st.empty()) st.pop();

// Previous Greater Element for Maximum

for (int i = 0; i < n; i++) {

while (!st.empty() && nums[st.top()] < nums[i]) st.pop();

pleMax[i] = st.empty() ? -1 : st.top();

st.push(i);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (!st.empty()) st.pop();

// Next Greater Element for Maximum

for (int i = n - 1; i >= 0; i--) {

while (!st.empty() && nums[st.top()] <= nums[i]) st.pop();

nleMax[i] = st.empty() ? n : st.top();

st.push(i);

ll minSum = 0, maxSum = 0;

for (int i = 0; i < n; i++) {

ll leftMin = i - pleMin[i];

ll rightMin = nleMin[i] - i;

ll leftMax = i - pleMax[i];

ll rightMax = nleMax[i] - i;

minSum += (ll)nums[i] * leftMin * rightMin;

maxSum += (ll)nums[i] * leftMax * rightMax;

return maxSum - minSum;

int main() {

vector<int> nums = {1, 2, 3};

cout << "Sum of subarray ranges: " << sumSubarrayRanges(nums) << endl;

return 0;

� Explanation (in 4 lines):

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. For each element, we count how many subarrays it is the minimum or maximum in.
2. We use monotonic stacks to find Previous/Next Less and Greater Elements
3. Multiply contributions and sum for both max and min.
4. Subtract the total min sum from max sum to get the result.

PROBLEM:208
Question: Remove k Digits

C++ Program: Remove K Digits to Get the Smallest Number

� Problem:
Given a string num representing a non-negative integer and an integer k,
remove k digits from the number so that the new number is the smallest possible.

� Approach: Use Monotonic Stack

We maintain a monotonic increasing stack of digits.

If the current digit is smaller than the top of the stack, pop from the stack (to make
number smaller).

After processing, remove extra digits if needed (when k > 0).

Remove leading zeroes and return result.

cpp

#include <iostream>

#include <stack>

using namespace std;

string removeKdigits(string num, int k) {

string result;

for (char digit : num) {

// Remove digits from result if they are greater than current digit

while (!result.empty() && k > 0 && result.back() > digit) {

result.pop_back();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


k--;

result.push_back(digit);

// If k > 0, remove from the end

while (k > 0 && !result.empty()) {

result.pop_back();

k--;

// Remove leading zeros

int index = 0;

while (index < result.size() && result[index] == '0') {

index++;

string finalResult = result.substr(index);

return finalResult.empty() ? "0" : finalResult;

int main() {

string num = "1432219";

int k = 3;

cout << "Smallest number after removing " << k << " digits: " << removeKdigits(num, k) <<
endl;

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Explanation (in 4 lines):

1. Use a string (stack behavior) to greedily build the smallest number.


2. Remove previous digits if the current digit is smaller and k > 0.
3. If any digits left to remove (k > 0), pop from the end.
4. Remove leading zeroes, return "0" if empty.

PROBLEM:209

Question: Largest rectangle in a histogram

C++ Program: Largest Rectangle in a Histogram

� Problem Statement:
Given an array heights[] representing the height of bars in a histogram,
find the area of the largest rectangle that can be formed.

� Approach: Monotonic Stack

For each bar, calculate:

Next Smaller Element (NSE)

Previous Smaller Element (PSE)

Width of the largest rectangle using bar i is:


width = NSE[i] - PSE[i] - 1

Area = heights[i] * width

cpp

#include <iostream>

#include <vector>

#include <stack>

using namespace std;

int largestRectangleArea(vector<int>& heights) {

int n = heights.size();

vector<int> left(n), right(n);

stack<int> st;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Previous Smaller Element

for (int i = 0; i < n; i++) {

while (!st.empty() && heights[st.top()] >= heights[i])

st.pop();

left[i] = st.empty() ? -1 : st.top();

st.push(i);

while (!st.empty()) st.pop();

// Next Smaller Element

for (int i = n - 1; i >= 0; i--) {

while (!st.empty() && heights[st.top()] >= heights[i])

st.pop();

right[i] = st.empty() ? n : st.top();

st.push(i);

int maxArea = 0;

for (int i = 0; i < n; i++) {

int width = right[i] - left[i] - 1;

int area = heights[i] * width;

maxArea = max(maxArea, area);

return maxArea;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int main() {

vector<int> heights = {2, 1, 5, 6, 2, 3};

cout << "Largest rectangle area: " << largestRectangleArea(heights) << endl;

return 0;

� Explanation (in 4 lines):

1. Use a monotonic stack to find the left and right bounds for each bar.
2. Calculate the width of the rectangle for each bar using these bounds.
3. Compute area = height × width, and track the maximum area.
4. Return the largest area among all bars.

PROBLEM:210

Question:Maximal Rectangles

C++ Program: Maximal Rectangle in a Binary Matrix

� Problem Statement:
Given a 2D binary matrix filled with '0' and '1',
find the largest rectangle containing only '1's and return its area.

� Approach: Histogram + Largest Rectangle in Histogram

Treat each row as the base of a histogram.

Convert the 2D matrix into histograms of heights.

For each row, use the Largest Rectangle in Histogram method.

cpp

#include <iostream>

#include <vector>

#include <stack>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Helper: Largest Rectangle in Histogramint largestRectangleArea(vector<int>& heights) {

int n = heights.size();

stack<int> st;

int maxArea = 0;

for (int i = 0; i <= n; i++) {

int h = (i == n ? 0 : heights[i]);

while (!st.empty() && h < heights[st.top()]) {

int height = heights[st.top()];

st.pop();

int width = st.empty() ? i : i - st.top() - 1;

maxArea = max(maxArea, height * width);

st.push(i);

return maxArea;

// Main: Maximal Rectangle in Matrixint maximalRectangle(vector<vector<char>>& matrix) {

if (matrix.empty()) return 0;

int maxArea = 0;

int cols = matrix[0].size();

vector<int> heights(cols, 0);

for (auto& row : matrix) {

for (int i = 0; i < cols; i++) {

// Build histogram from matrix row

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


heights[i] = row[i] == '1' ? heights[i] + 1 : 0;

// Find largest rectangle in current histogram

maxArea = max(maxArea, largestRectangleArea(heights));

return maxArea;

int main() {

vector<vector<char>> matrix = {

{'1','0','1','0','0'},

{'1','0','1','1','1'},

{'1','1','1','1','1'},

{'1','0','0','1','0'}

};

cout << "Maximal rectangle area: " << maximalRectangle(matrix) << endl;

return 0;

� Explanation (in 4 lines):

1. Each row builds a histogram where heights[i] is the number of consecutive 1s above
(including current row).
2. For each histogram (row), find the largest rectangle using the stack method.
3. Keep updating the maximum area found so far.
4. Return the largest area across all rows.

PROBLEM:211

Question:Sliding Window maximum

Sliding Window Maximum - C++ Code

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>

#include <deque>

#include <vector>

using namespace std;

vector<int> maxSlidingWindow(vector<int>& nums, int k) {

deque<int> dq;

vector<int> res;

for (int i = 0; i < nums.size(); ++i) {

if (!dq.empty() && dq.front() < i - k + 1)

dq.pop_front();

while (!dq.empty() && nums[dq.back()] < nums[i])

dq.pop_back();

dq.push_back(i);

if (i >= k - 1)

res.push_back(nums[dq.front()]);

return res;

� Quick Explanation:

1. deque stores indices of potential max elements within the window.


2. Elements outside the current window or smaller than the current number are removed.
3. After processing k elements, the front of the deque is the current max.
4. The result vector stores the maximums for each window.

PROBLEM:212

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question: Stock Span Problem
C++ Code (Using Stack):

cpp

#include <iostream>

#include <stack>

#include <vector>

using namespace std;

vector<int> calculateSpan(vector<int>& prices) {

stack<int> s;

vector<int> span(prices.size());

for (int i = 0; i < prices.size(); ++i) {

while (!s.empty() && prices[s.top()] <= prices[i])

s.pop();

span[i] = s.empty() ? (i + 1) : (i - s.top());

s.push(i);

return span;

� Quick Explanation:

1. Use a stack to keep track of indices where prices are higher than the current.
2. Pop all smaller or equal prices to find how far back the span goes.
3. If stack is empty, span = entire length so far → i + 1.
4. Otherwise, span = distance from last greater price → i - s.top().

PROBLEM:213

Question: The Celebrity Problem

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� The Celebrity Problem

� Problem Statement:

In a party of n people, a celebrity is defined as someone who:

Is known by everyone, and

Knows no one (not even themselves).

You are given a knows(a, b) function that returns true if person a knows person b.
Your task: Find the celebrity if one exists, else return -1.

� Efficient C++ Code (O(n) time):

cpp

#include <iostream>

#include <vector>

using namespace std;

// Sample matrix (global)

vector<vector<int>> M;

bool knows(int a, int b) {

return M[a][b] == 1;

int findCelebrity(int n) {

int candidate = 0;

// Step 1: Find the candidate

for (int i = 1; i < n; ++i) {

if (knows(candidate, i))

candidate = i;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Step 2: Verify the candidate

for (int i = 0; i < n; ++i) {

if (i != candidate && (knows(candidate, i) || !knows(i, candidate)))

return -1;

return candidate;

}
The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

� Quick Explanation:

1. Step 1: Assume person 0 is celebrity and update the candidate if they know anyone.
2. Step 2: Verify that the candidate doesn't know anyone and everyone knows them
3. Uses only O(n) time by checking linearly instead of O(n²).
4. knows(a, b) acts like a black-box API you query to make decisions.

PROBLEM:214

Question: LRU cache (IMPORTANT)


LRU Cache (Least Recently Used) - IMPORTANT Interview Question

� Problem Statement:

Design a data structure that behaves like an LRU Cache with:

get(key) → returns the value if the key exists, else -1.

put(key, value) → insert/update the value, and if the cache exceeds capacity, evict
the least recently used item.

Must support both operations in O(1) time.

� Efficient C++ Code (Using unordered_map + list):

cpp

#include <iostream>

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <unordered_map>

#include <list>

using namespace std;

class LRUCache {

int capacity;

list<pair<int, int>> dll; // Doubly linked list: {key, value}

unordered_map<int, list<pair<int, int>>::iterator> cache;

public:

LRUCache(int cap) {

capacity = cap;

int get(int key) {

if (cache.find(key) == cache.end())

return -1;

// Move the accessed node to the front

dll.splice(dll.begin(), dll, cache[key]);

return cache[key]->second;

void put(int key, int value) {

if (cache.find(key) != cache.end()) {

// Update and move to front

cache[key]->second = value;

dll.splice(dll.begin(), dll, cache[key]);

} else {

if (dll.size() == capacity) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Remove least recently used

int lruKey = dll.back().first;

dll.pop_back();

cache.erase(lruKey);

dll.emplace_front(key, value);

cache[key] = dll.begin();

};

� Quick Explanation:

1. list keeps items in recent → least recent order.


2. unordered_map gives O(1) access to list iterators.
3. On get or put, move key to front of the list (most recent).
4. If capacity is full, evict the key at the back of the list (least recent).

PROBLEM:215

Question: LFU cache

LFU Cache (Least Frequently Used) — Advanced & IMPORTANT

✅ Problem Statement:

Design a Least Frequently Used (LFU) Cache that supports:

get(key) → returns value if present, else -1.


put(key, value) → inserts or updates value. If full, evict the least frequently used
key (if tie, evict least recently used among them).

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


All operations must be O(1) time complexity.

� C++ Code using HashMaps + Frequency Lists

cpp

#include <iostream>

#include <unordered_map>

#include <list>

using namespace std;

class LFUCache {

int capacity, minFreq;

unordered_map<int, pair<int, int>> keyToValFreq; // key -> {value, freq}

unordered_map<int, list<int>> freqToKeys; // freq -> list of keys

unordered_map<int, list<int>::iterator> keyToIter; // key -> iterator in freq list

public:

LFUCache(int capacity) {

this->capacity = capacity;

minFreq = 0;

int get(int key) {

if (keyToValFreq.find(key) == keyToValFreq.end())

return -1;

int val = keyToValFreq[key].first;

int freq = keyToValFreq[key].second;

// Remove from current frequency list

freqToKeys[freq].erase(keyToIter[key]);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Clean up if needed

if (freqToKeys[freq].empty()) {

freqToKeys.erase(freq);

if (minFreq == freq) minFreq++;

// Add to higher frequency list

freqToKeys[freq + 1].push_front(key);

keyToIter[key] = freqToKeys[freq + 1].begin();

keyToValFreq[key].second++;

return val;

void put(int key, int value) {

if (capacity == 0) return;

if (get(key) != -1) {

// Already exists; just update value

keyToValFreq[key].first = value;

return;

// Evict if needed

if (keyToValFreq.size() >= capacity) {

int keyToEvict = freqToKeys[minFreq].back();

freqToKeys[minFreq].pop_back();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (freqToKeys[minFreq].empty())

freqToKeys.erase(minFreq);

keyToValFreq.erase(keyToEvict);

keyToIter.erase(keyToEvict);

// Insert new key

keyToValFreq[key] = {value, 1};

freqToKeys[1].push_front(key);

keyToIter[key] = freqToKeys[1].begin();

minFreq = 1;

};

⚙️ Quick Explanation:

1. keyToValFreq → stores key's value and frequency.


2. freqToKeys → stores keys at each frequency in LRU order (list).
3. keyToIter → maps key to its position in the list for O(1) removal.
4. On get or put, update frequency and move key to new list.
5. If evicting, remove the least recently used key from the lowest frequency list.

PROBLEM:216

Question: Longest Substring Without Repeating Characters

C++ Code (Using Sliding Window + HashMap)

cpp

#include <iostream>#include <unordered_map>using namespace std;

int lengthOfLongestSubstring(string s) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


unordered_map<char, int> lastSeen;

int maxLen = 0, start = 0;

for (int i = 0; i < s.length(); ++i) {

if (lastSeen.find(s[i]) != lastSeen.end() && lastSeen[s[i]] >= start) {

start = lastSeen[s[i]] + 1;

lastSeen[s[i]] = i;

maxLen = max(maxLen, i - start + 1);

return maxLen;

� Quick Explanation:

1. Use a hash map to track the last index of each character.


2. Move start of the window to avoid repeating characters.
3. Calculate maxLen as the window size i - start + 1.
4. Runs in O(n) time where n = length of string.

PROBLEM:217

Question:Max Consecutive Ones III

C++ Code (Sliding Window Approach — O(n))

cpp

#include <iostream>#include <vector>using namespace std;

int longestOnes(vector<int>& nums, int k) {

int left = 0, zeros = 0, maxLen = 0;

for (int right = 0; right < nums.size(); ++right) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (nums[right] == 0)

zeros++;

while (zeros > k) {

if (nums[left] == 0)

zeros--;

left++;

maxLen = max(maxLen, right - left + 1);

return maxLen;

� Quick Explanation:

1. Use a sliding window with two pointers left and right.


2. Expand right; count how many 0s in the current window.
3. If zeros > k, shrink the window from the left.
4. Track the maximum length of valid windows throughout.

PROBLEM:218

Question:Fruit Into Baskets


C++ Code (Sliding Window + HashMap)

cpp

#include <iostream>

#include <unordered_map>

#include <vector>

using namespace std;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int totalFruit(vector<int>& fruits) {

unordered_map<int, int> count;

int left = 0, maxLen = 0;

for (int right = 0; right < fruits.size(); ++right) {

count[fruits[right]]++;

while (count.size() > 2) {

count[fruits[left]]--;

if (count[fruits[left]] == 0)

count.erase(fruits[left]);

left++;

maxLen = max(maxLen, right - left + 1);

return maxLen;

� Quick Explanation:

1. Use a hash map to count fruit types in the window.


2. Slide the right pointer to expand the window.
3. If more than 2 fruit types, shrink from the left.
4. Keep track of the maximum window size.

PROBLEM:219

Question:longest repeating character replacement

C++ Code (Sliding Window + Frequency Map)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>#include <vector>using namespace std;

int characterReplacement(string s, int k) {

vector<int> count(26, 0);

int maxCount = 0, maxLen = 0, left = 0;

for (int right = 0; right < s.length(); ++right) {

count[s[right] - 'A']++;

maxCount = max(maxCount, count[s[right] - 'A']);

// If more than k replacements needed, shrink window

while ((right - left + 1) - maxCount > k) {

count[s[left] - 'A']--;

left++;

maxLen = max(maxLen, right - left + 1);

return maxLen;

� Quick Explanation:

1. Track frequency of characters in current window using a count array.


2. maxCount = frequency of most common character in the window.
3. If window needs more than k replacements, move left forward.
4. Keep track of the maximum valid window size.

PROBLEM:220

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question:Binary subarray with sum
C++ Code — Using Prefix Sum + Hash Map (O(n) time)

cpp

#include <iostream>#include <vector>#include <unordered_map>using namespace std;

int numSubarraysWithSum(vector<int>& nums, int goal) {

unordered_map<int, int> prefixCount;

prefixCount[0] = 1;

int sum = 0, count = 0;

for (int num : nums) {

sum += num;

if (prefixCount.find(sum - goal) != prefixCount.end()) {

count += prefixCount[sum - goal];

prefixCount[sum]++;

return count;

� Quick Explanation:

1. Use a prefix sum to track total sum up to each index.


2. Store count of each prefix sum in a hash map.
3. For each index, check if there's a previous prefix sum = sum - goal.
4. If so, it means the subarray between them sums to goal.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:221

Question:Count number of nice subarrays


C++ Code — Prefix Sum + Hash Map (O(n) time)

cpp

#include <iostream>

#include <unordered_map>

#include <vector>

using namespace std;

int numberOfSubarrays(vector<int>& nums, int k) {

unordered_map<int, int> count;

count[0] = 1;

int odd = 0, result = 0;

for (int num : nums) {

if (num % 2 != 0) odd++;

if (count.find(odd - k) != count.end()) {

result += count[odd - k];

count[odd]++;

return result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Quick Explanation:

1. Count how many odd numbers seen so far (odd).


2. Use a hash map to track how often each odd count has occurred.
3. If odd - k has occurred before, then there's a subarray ending here with exactly k odds.
4. Add its frequency to the result.

PROBLEM:222

Question: Number of substring containing all three characters


C++ Code — Sliding Window (O(n) Time)

cpp

#include <iostream>#include <vector>#include <string>using namespace std;

int numberOfSubstrings(string s) {

vector<int> count(3, 0);

int left = 0, res = 0;

for (int right = 0; right < s.size(); ++right) {

count[s[right] - 'a']++;

while (count[0] > 0 && count[1] > 0 && count[2] > 0) {

res += s.size() - right;

count[s[left] - 'a']--;

left++;

return res;

}
The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

� Quick Explanation:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. Use a sliding window to maintain counts of 'a', 'b', and 'c'.
2. Once all three are in the window, every substring starting at left and ending from right
to end is valid.
3. Count these (s.size() - right) and move left forward.
4. Repeat until end of string.

PROBLEM:223

Question:Maximum point you can obtain from cards


C++ Code — Sliding Window (O(n))

cpp

#include <iostream>#include <vector>#include <numeric>using namespace std;

int maxScore(vector<int>& cardPoints, int k) {

int n = cardPoints.size();

int total = accumulate(cardPoints.begin(), cardPoints.begin() + k, 0);

int maxPoints = total;

for (int i = 0; i < k; ++i) {

total -= cardPoints[k - 1 - i];

total += cardPoints[n - 1 - i];

maxPoints = max(maxPoints, total);

return maxPoints;

� Quick Explanation:

1. Start by taking the first k cards — this is your initial score.


2. Then try removing cards from the start and adding from the end, one by one.
3. Keep updating the maximum total you can get at each step.
4. Only k steps needed, so time complexity is O(k).

PROBLEM:224

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question:Longest Substring with At Most K Distinct Characters
C++ Code — Sliding Window + Hash Map (O(n))

cpp

#include <iostream>#include <unordered_map>using namespace std;

int lengthOfLongestSubstringKDistinct(string s, int k) {

if (k == 0) return 0;

unordered_map<char, int> count;

int left = 0, maxLen = 0;

for (int right = 0; right < s.size(); ++right) {

count[s[right]]++;

while (count.size() > k) {

count[s[left]]--;

if (count[s[left]] == 0)

count.erase(s[left]);

left++;

maxLen = max(maxLen, right - left + 1);

return maxLen;

� Quick Explanat

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


1. Use a sliding window from left to right to explore the string.
2. Keep track of character frequencies in the window using a hash map.
3. Shrink the window from the left if there are more than k distinct characters.
4. Update maxLen with the size of the valid window.

PROBLEM:225

Question: Subarray with k different integers


C++ Code — Using Sliding Window Trick

We calculate: ExactlyK(k) = AtMostK(k) - AtMostK(k - 1)

cpp

#include <iostream>#include <unordered_map>#include <vector>using namespace std;

int atMostK(vector<int>& nums, int k) {

unordered_map<int, int> freq;

int left = 0, res = 0;

for (int right = 0; right < nums.size(); ++right) {

if (freq[nums[right]] == 0)

k--;

freq[nums[right]]++;

while (k < 0) {

freq[nums[left]]--;

if (freq[nums[left]] == 0)

k++;

left++;

res += right - left + 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return res;

int subarraysWithKDistinct(vector<int>& nums, int k) {

return atMostK(nums, k) - atMostK(nums, k - 1);

� Quick Explanatio

1. atMostK(k) returns the number of subarrays with at most k distinct integers.


2. To get exactly k, subtract atMostK(k - 1) from atMostK(k).
3. Uses sliding window + hash map for O(n) performance.

PROBLEM:226

Question: Minimum Window Substring


C++ Code — Sliding Window + Hash Map (O(n))

cpp

#include <iostream>#include <unordered_map>#include <climits>using namespace std;

string minWindow(string s, string t) {

if (s.empty() || t.empty()) return "";

unordered_map<char, int> need, window;

for (char c : t) need[c]++;

int left = 0, right = 0;

int valid = 0;

int start = 0, len = INT_MAX;

while (right < s.size()) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


char c = s[right++];

window[c]++;

if (need.count(c) && window[c] == need[c])

valid++;

while (valid == need.size()) {

if (right - left < len) {

start = left;

len = right - left;

char d = s[left++];

if (need.count(d) && window[d] == need[d])

valid--;

window[d]--;

return len == INT_MAX ? "" : s.substr(start, len);

� Quick Explanation:

1. Count required characters in t using need map.


2. Expand window using right and track counts in window map.
3. When all required chars are in window, try shrinking it from left.
4. Keep track of the smallest valid window.

PROBLEM:227

Question: Minimum Window Subsequence

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


C++ Code — Two-Pointer Scan (O(n * m))

cpp

#include <iostream>#include <string>using namespace std;

string minWindow(string S, string T) {

int sLen = S.length(), tLen = T.length();

int minLen = INT_MAX, start = -1;

for (int i = 0; i < sLen; ++i) {

if (S[i] != T[0]) continue;

int s = i, t = 0;

// Move forward to match T as subsequence

while (s < sLen && t < tLen) {

if (S[s] == T[t]) t++;

s++;

if (t == tLen) {

// Match found, move backward to minimize window

int end = s - 1;

t = tLen - 1;

while (s >= i && t >= 0) {

if (S[s] == T[t]) t--;

s--;

s++;

if (end - s + 1 < minLen) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


minLen = end - s + 1;

start = s;

return start == -1 ? "" : S.substr(start, minLen);

� Quick Explanation:

1. Loop through S, and whenever you see a char matching T[0], try to match all of T forward.
2. Once matched, scan backward to find the minimum window containing that
subsequence.
3. Update the smallest window found.

PROBLEM:228

Question: Introduction to Priority Queues using Binary Heaps

Introduction to Priority Queues using Binary Heaps

� What is a Priority Queue?

A priority queue is an abstract data type where each element has a priority, and elements
with higher priority are served before those with lower priority.

� Insertion: O(log n)
� Removal of highest priority (max/min): O(log n)

� Binary Heap: The Backbone of Priority Queues

A Binary Heap is a complete binary tree that satisfies the heap property:

Max Heap: Parent ≥ Children (used for max-priority queue)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Min Heap: Parent ≤ Children (used for min-priority queue)

It’s usually implemented as an array, where:

Left child = 2*i + 1

Right child = 2*i + 2

Parent = (i - 1) / 2

✅ C++ STL Implementation

cpp

#include <iostream>#include <queue>using namespace std;

int main() {

// Max Heap (default)

priority_queue<int> maxPQ;

maxPQ.push(3);

maxPQ.push(5);

maxPQ.push(1);

cout << "Max Heap Top: " << maxPQ.top() << endl; // 5

// Min Heap

priority_queue<int, vector<int>, greater<int>> minPQ;

minPQ.push(3);

minPQ.push(5);

minPQ.push(1);

cout << "Min Heap Top: " << minPQ.top() << endl; // 1

return 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� Quick Highlights:

1. Efficient for real-time scheduling, Dijkstra’s, A* algorithm, etc.


2. Binary Heaps ensure fast insertion and removal using log time.
3. C++ priority_queue is a wrapper over a binary heap built on vector.

PROBLEM:229

Question: Min Heap and Max Heap Implementation

Min Heap & Max Heap Implementation in C++ (Without STL)

Let’s implement both Min Heap and Max Heap using a vector and basic heap operations.

�️ 1. Min Heap Implementation


cpp

#include <iostream>#include <vector>using namespace std;

class MinHeap {

vector<int> heap;

void heapifyUp(int index) {

while (index > 0 && heap[index] < heap[(index - 1)/2]) {

swap(heap[index], heap[(index - 1)/2]);

index = (index - 1)/2;

void heapifyDown(int index) {

int size = heap.size();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int smallest = index;

int left = 2 * index + 1;

int right = 2 * index + 2;

if (left < size && heap[left] < heap[smallest])

smallest = left;

if (right < size && heap[right] < heap[smallest])

smallest = right;

if (smallest != index) {

swap(heap[index], heap[smallest]);

heapifyDown(smallest);

public:

void push(int val) {

heap.push_back(val);

heapifyUp(heap.size() - 1);

void pop() {

if (heap.empty()) return;

heap[0] = heap.back();

heap.pop_back();

heapifyDown(0);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int top() {

return heap.empty() ? -1 : heap[0];

bool empty() {

return heap.empty();

};

�️ 2. Max Heap Implementation


Same logic as Min Heap, but conditions flipped.

cpp

class MaxHeap {

vector<int> heap;

void heapifyUp(int index) {

while (index > 0 && heap[index] > heap[(index - 1)/2]) {

swap(heap[index], heap[(index - 1)/2]);

index = (index - 1)/2;

void heapifyDown(int index) {

int size = heap.size();

int largest = index;

int left = 2 * index + 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int right = 2 * index + 2;

if (left < size && heap[left] > heap[largest])

largest = left;

if (right < size && heap[right] > heap[largest])

largest = right;

if (largest != index) {

swap(heap[index], heap[largest]);

heapifyDown(largest);

public:

void push(int val) {

heap.push_back(val);

heapifyUp(heap.size() - 1);

void pop() {

if (heap.empty()) return;

heap[0] = heap.back();

heap.pop_back();

heapifyDown(0);

int top() {

return heap.empty() ? -1 : heap[0];

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


bool empty() {

return heap.empty();

};

� Key Points:

heapifyUp maintains order while inserting.

heapifyDown maintains order while deleting.

Both heaps operate in O(log n) for insert and delete.

PROBLEM:230

Question: Check if an array represents a min-heap or not

C++ Code — Check Min-Heap Property

cpp

#include <iostream>#include <vector>using namespace std;

bool isMinHeap(const vector<int>& arr) {

int n = arr.size();

for (int i = 0; i <= (n - 2) / 2; ++i) {

int left = 2 * i + 1;

int right = 2 * i + 2;

// Check if left child is smaller

if (left < n && arr[i] > arr[left])

return false;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


// Check if right child is smaller

if (right < n && arr[i] > arr[right])

return false;

return true;

� Quick Explanation:

1. For each internal node i from 0 to (n-2)/2, check:


2. Is arr[i] ≤ arr[2*i + 1] (left child)?
3. Is arr[i] ≤ arr[2*i + 2] (right child)?
4. If both conditions are true for all parents, it’s a Min-Heap.

PROBLEM:231

Question: Convert min Heap to max Heap

C++ Code — Heapify Bottom-Up (O(n))

cpp

#include <iostream>#include <vector>using namespace std;

void heapify(vector<int>& arr, int n, int i) {

int largest = i;

int left = 2*i + 1;

int right = 2*i + 2;

if (left < n && arr[left] > arr[largest])

largest = left;

if (right < n && arr[right] > arr[largest])

largest = right;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (largest != i) {

swap(arr[i], arr[largest]);

heapify(arr, n, largest);

void convertMinToMaxHeap(vector<int>& arr) {

int n = arr.size();

// Start from last non-leaf node and heapify down

for (int i = (n - 2) / 2; i >= 0; --i)

heapify(arr, n, i);

� Quick Explanation:

1.The input is a valid Min-Heap in array form.

2.To turn it into a Max-Heap, we call heapify() bottom-up starting from the last non-leaf
node.

3.heapify() ensures the Max-Heap property: parent ≥ children.

� Usage:

cpp

int main() {

vector<int> arr = {1, 3, 5, 7, 9, 6};

convertMinToMaxHeap(arr);

for (int x : arr)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cout << x << " ";

return 0;

}// Output: 9 7 6 3 1 5

PROBLEM:232

Question: Kth largest element in an array [use priority queue]

C++ Code — Min Heap of Size K (Using Priority Queue)

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

int findKthLargest(vector<int>& nums, int k) {

priority_queue<int, vector<int>, greater<int>> minHeap;

for (int num : nums) {

minHeap.push(num);

if (minHeap.size() > k)

minHeap.pop(); // Remove smallest to keep k largest

return minHeap.top(); // Top of minHeap is kth largest

� Quick Explanation:

1. We use a min-heap to keep track of the k largest elements.


2. If the heap size exceeds k, we remove the smallest (min-heap behavior).
3. After processing all elements, the top of the heap is the k-th largest.

� Time Complexity:

O(n log k) — for n elements, each heap operation takes log k

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Space: O(k) — storing k elements in the heap

PROBLEM:233

Question: Kth smallest element in an array [use priority queue]

C++ Code — Max Heap of Size K (Using Priority Queue)

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

int findKthSmallest(vector<int>& nums, int k) {

priority_queue<int> maxHeap;

for (int num : nums) {

maxHeap.push(num);

if (maxHeap.size() > k)

maxHeap.pop(); // Remove largest to keep k smallest

return maxHeap.top(); // Top is kth smallest

� Quick Explanation:

1. Use a max-heap to store the k smallest elements so far.


2. If size exceeds k, remove the largest to keep only the smallest k.
3. After all elements, the top is the k-th smallest.

� Time Complexity:

O(n log k) — each of the n insertions/removals takes log k

Space: O(k) — heap holds k elements

PROBLEM:234

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

Question: Sort K sorted array

C++ Code — Min Heap Approach (O(n log k))

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

vector<int> sortKSortedArray(vector<int>& arr, int k) {

priority_queue<int, vector<int>, greater<int>> minHeap;

vector<int> result;

// Add first k+1 elements to the heap

for (int i = 0; i <= k; ++i)

minHeap.push(arr[i]);

// Process remaining elements

for (int i = k + 1; i < arr.size(); ++i) {

result.push_back(minHeap.top());

minHeap.pop();

minHeap.push(arr[i]);

// Extract remaining from heap

while (!minHeap.empty()) {

result.push_back(minHeap.top());

minHeap.pop();

return result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� Quick Explanation:

1. The smallest element will always be among the first k+1 items.
2. Use a min-heap to always extract the smallest from the current window.
3. Push new elements into the heap while popping the smallest one to maintain sorted order.

� Time & Space Complexity:

Time: O(n log k)

Space: O(k)

PROBLEM:235

Question: Merge M sorted Lists

Merge M Sorted Lists

Problem Statement:

Given M sorted linked lists (or arrays), merge them into one sorted list.

� Example:

Input: lists = [[1,4,5],[1,3,4],[2,6]]

Output: [1,1,2,3,4,4,5,6]

✅ C++ Code — Using Min Heap (Priority Queue)

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

struct Node {

int val;

int listIdx; // which list

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int eleIdx; // index in list

bool operator>(const Node& other) const {

return val > other.val;

};

vector<int> mergeKSortedLists(vector<vector<int>>& lists) {

priority_queue<Node, vector<Node>, greater<Node>> minHeap;

vector<int> result;

// Initialize with first element of each list

for (int i = 0; i < lists.size(); ++i) {

if (!lists[i].empty()) {

minHeap.push({lists[i][0], i, 0});

// Extract min and insert next element from that list

while (!minHeap.empty()) {

Node curr = minHeap.top();

minHeap.pop();

result.push_back(curr.val);

if (curr.eleIdx + 1 < lists[curr.listIdx].size()) {

minHeap.push({lists[curr.listIdx][curr.eleIdx + 1], curr.listIdx, curr.eleIdx + 1});

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return result;

� Quick Explanation:

1. Use a min heap to keep track of the smallest current elements from all M lists.
2. Pop the smallest, push its next element from the same list.
3. Continue until all lists are exhausted.

� Time & Space Complexity:

Time: O(N log M) where N = total elements, M = number of lists

Space: O(M) for the heap

PROBLEM:236
Question: Replace each array element by its corresponding rank

Replace Each Array Element by Its Rank

Problem Statement:

Given an array, replace each element with its rank when the array is sorted.
Equal elements receive the same rank.

� Example:

Input: arr = [40, 10, 20, 20, 30]

Output: [4, 1, 2, 2, 3]

✅ C++ Code — Using Sorting & Hash Map

cpp

#include <iostream>#include <vector>#include <unordered_map>#include <algorithm>using


namespace std;

vector<int> arrayRankTransform(vector<int>& arr) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<int> sortedArr = arr;

sort(sortedArr.begin(), sortedArr.end());

unordered_map<int, int> rank;

int r = 1;

for (int num : sortedArr) {

if (rank.find(num) == rank.end()) {

rank[num] = r++;

for (int i = 0; i < arr.size(); ++i) {

arr[i] = rank[arr[i]];

return arr;

� Quick Explanation:

1. Copy and sort the array.


2. Use a map to assign increasing ranks (skip duplicates).
3. Replace original values using the map.

� Time & Space Complexity

Time: O(n log n) — for sorting

Space: O(n) — for the hash map and temporary vector

PROBLEM:237

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question: Task Scheduler
Task Scheduler

Problem Statement:

Given a list of tasks represented by capital letters and a non-negative integer n (cooldown),
return the least number of units of time required to finish all tasks such that
the same task can only be run again after n units of time.

� Example:

Input: tasks = ['A','A','A','B','B','B'], n = 2

Output: 8

Explanation: A → B → idle → A → B → idle → A → B

✅ C++ Code — Greedy + Priority Queue

cpp

#include <iostream>#include <vector>#include <queue>#include <unordered_map>using


namespace std;

int leastInterval(vector<char>& tasks, int n) {

unordered_map<char, int> freq;

for (char task : tasks)

freq[task]++;

priority_queue<int> maxHeap;

for (auto& f : freq)

maxHeap.push(f.second);

int time = 0;

while (!maxHeap.empty()) {

int cycle = n + 1;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<int> temp;

while (cycle-- && !maxHeap.empty()) {

int cnt = maxHeap.top(); maxHeap.pop();

if (cnt > 1)

temp.push_back(cnt - 1);

time++;

for (int count : temp)

maxHeap.push(count);

if (!maxHeap.empty())

time += cycle + 1; // Add idle time

return time;

� Quick Explanation:

1. Count frequencies of tasks and use a max-heap to always schedule the most frequent first.
2. In each (n + 1) time unit "cycle", schedule up to n+1 different tasks.
3. If fewer than n+1 tasks are run, insert idle time.

� Time & Space Complexity:

Time: O(N log 26) ≈ O(N), where N = number of tasks

Space: O(26) = O(1) for English uppercase letters

PROBLEM:238

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Question: Hands of Straights
Hands of Straights

Problem Statement:

Given an array of integers hand and an integer groupSize, return true if we can divide the
hand into groups of groupSize consecutive cards, otherwise return false.

� Example:

Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3

Output: true

Explanation: Groups → [1,2,3], [2,3,4], [6,7,8]

✅ C++ Code — Using map (Ordered Frequency Map)

cpp

#include <iostream>#include <vector>#include <map>using namespace std;

bool isNStraightHand(vector<int>& hand, int groupSize) {

if (hand.size() % groupSize != 0) return false;

map<int, int> freq;

for (int card : hand)

freq[card]++;

for (auto& [card, count] : freq) {

if (count > 0) {

for (int i = 0; i < groupSize; ++i) {

if (freq[card + i] < count)

return false;

freq[card + i] -= count;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return true;

� Quick Explanation:

1. Count frequencies of each card using a map (sorted by key).


2. For each card, try to form a group of size groupSize starting from it.
3. Reduce frequency as you form valid groups. If not possible, return false.

� Time & Space Complexity:

Time: O(N log N), due to sorting in map

Space: O(N) for the frequency map

PROBLEM:239

Question: Design twitter

Design Twitter

System Design + OOP (LeetCode-style)

� Problem Statement:

Design a simplified version of Twitter:

Post a tweet

Follow/unfollow users

Get the 10 most recent tweets from followed users (including self)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


✅ C++ Code — Using unordered_map, set, and priority_queue

cpp

#include <iostream>#include <unordered_map>#include <unordered_set>#include


<vector>#include <queue>using namespace std;

class Twitter {

int time;

unordered_map<int, unordered_set<int>> followMap;

unordered_map<int, vector<pair<int, int>>> tweets; // user -> [<time, tweetId>]

public:

Twitter() : time(0) {}

void postTweet(int userId, int tweetId) {

tweets[userId].push_back({time++, tweetId});

vector<int> getNewsFeed(int userId) {

priority_queue<pair<int, int>> maxHeap;

followMap[userId].insert(userId); // follow self

for (int followee : followMap[userId]) {

for (auto& tweet : tweets[followee]) {

maxHeap.push(tweet);

if (maxHeap.size() > 10)

maxHeap.pop();

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


vector<int> feed;

while (!maxHeap.empty()) {

feed.push_back(maxHeap.top().second);

maxHeap.pop();

reverse(feed.begin(), feed.end());

return feed;

void follow(int followerId, int followeeId) {

followMap[followerId].insert(followeeId);

void unfollow(int followerId, int followeeId) {

if (followerId != followeeId)

followMap[followerId].erase(followeeId);

};

� Quick Explanation:

1. postTweet(userId, tweetId): adds the tweet with a timestamp.


2. getNewsFeed(userId): gets top 10 most recent tweets from all followed users.
3. follow/unfollow: updates the followMap.
4. Uses a max-heap to always track the most recent 10 tweets efficiently.

� Time Complexity:

postTweet: O(1)

follow/unfollow: O(1)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


getNewsFeed: O(n log k), where n = total tweets, k = 10

PROBLEM:240

Question: Connect n ropes with minimal cost

Connect n Ropes with Minimal Cost

� Problem Statement:

Given n ropes of different lengths, connect them into one rope. The cost to connect two ropes
is equal to the sum of their lengths.
Return the minimum total cost to connect all ropes.

� Example:

Input: ropes = [4, 3, 2, 6]

Output: 29

Explanation: Connect 2+3=5, then 5+4=9, then 9+6=15 → Total = 5+9+15 = 29

✅ C++ Code — Min Heap Approach

cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

int connectRopes(vector<int>& ropes) {

priority_queue<int, vector<int>, greater<int>> minHeap(ropes.begin(), ropes.end());

int totalCost = 0;

while (minHeap.size() > 1) {

int first = minHeap.top(); minHeap.pop();

int second = minHeap.top(); minHeap.pop();

int cost = first + second;

totalCost += cost;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


minHeap.push(cost);

return totalCost;

� Quick Explanation:

1. Use a min-heap to always pick the two shortest ropes.


2. Combine them and add the cost, then push the new rope back.
3. Repeat until one rope remains.

� Time & Space Complexity:

Time: O(n log n)

Space: O(n)

PROBLEM:241

Question: Kth Largest Element in a Stream of Running Integers


Problem Statement:

Design a class to continuously track the k-th largest element in a stream.


Support:

Constructor with k and initial stream

add(val) to insert a new number and return the k-th largest element

� Example:

Input: KthLargest(3, [4,5,8,2])add(3) → 4 add(5) → 5 add(10) → 5 add(9) → 8 add(4) → 8

✅ C++ Code — Min Heap

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>#include <vector>#include <queue>using namespace std;

class KthLargest {

priority_queue<int, vector<int>, greater<int>> minHeap;

int k;

public:

KthLargest(int k, vector<int>& nums) {

this->k = k;

for (int num : nums) {

minHeap.push(num);

if (minHeap.size() > k)

minHeap.pop();

int add(int val) {

minHeap.push(val);

if (minHeap.size() > k)

minHeap.pop();

return minHeap.top(); // Kth largest

};

� Quick Explanation:

1. Maintain a min-heap of size k for the top k largest elements.


2. The top of the heap is the k-th largest.
3. Each add() call inserts the new element and ensures the heap stays size k.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Time & Space Complexity:

Time: O(log k) per insertion

Space: O(k)

PROBLEM:242

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

Question: Maximum Sum Combination

Maximum Sum Combination (Top K Sums from Two Arrays)

Problem Statement:

Given two sorted arrays A and B of size N and an integer K,


find the K maximum sum combinations from A[i] + B[j] (with no repetition of the same
pair).

� Example:

Input: A = [1, 4, 2, 3], B = [2, 5, 1, 6], K = 4

Output: [10, 9, 9, 8]

Explanation: 4 max sums → 4+6=10, 3+6=9, 4+5=9, 2+6=8

✅ C++ Code — Max Heap + Set (Efficient Approach)

cpp

#include <iostream>#include <vector>#include <queue>#include <set>#include


<algorithm>using namespace std;

vector<int> maxSumCombination(vector<int>& A, vector<int>& B, int K) {

int N = A.size();

sort(A.begin(), A.end());

sort(B.begin(), B.end());

priority_queue<tuple<int, int, int>> maxHeap;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


set<pair<int, int>> seen;

maxHeap.push({A[N-1] + B[N-1], N-1, N-1});

seen.insert({N-1, N-1});

vector<int> result;

while (K-- && !maxHeap.empty()) {

auto [sum, i, j] = maxHeap.top();

maxHeap.pop();

result.push_back(sum);

if (i > 0 && !seen.count({i-1, j})) {

maxHeap.push({A[i-1] + B[j], i-1, j});

seen.insert({i-1, j});

if (j > 0 && !seen.count({i, j-1})) {

maxHeap.push({A[i] + B[j-1], i, j-1});

seen.insert({i, j-1});

return result;

� Quick Explanation:

1. Sort both arrays in ascending order.


2. Use a max-heap to track the largest possible sums with indices.
3. Use a set to avoid pushing duplicate index pairs.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Time & Space Complexity:

Time: O(K log K)

Space: O(K)

PROBLEM:243

Question: Find Median from Data Stream

Find Median from Data Stream

� Problem Statement:

Design a data structure that supports:

Adding numbers from a stream

Getting the median at any point in O(log N) time per operation

� Example:

Input:addNum(1)addNum(2)findMedian() → 1.5addNum(3)findMedian() → 2

✅ C++ Code — Two Heaps Approach

cpp

#include <iostream>

#include <queue>

using namespace std;

class MedianFinder {

priority_queue<int> maxHeap; // left half (max-heap)

priority_queue<int, vector<int>, greater<int>> minHeap; // right half (min-heap)

public:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


void addNum(int num) {

if (maxHeap.empty() || num <= maxHeap.top())

maxHeap.push(num);

else

minHeap.push(num);

// Balance the heaps

if (maxHeap.size() > minHeap.size() + 1) {

minHeap.push(maxHeap.top()); maxHeap.pop();

} else if (minHeap.size() > maxHeap.size()) {

maxHeap.push(minHeap.top()); minHeap.pop();

double findMedian() {

if (maxHeap.size() == minHeap.size())

return (maxHeap.top() + minHeap.top()) / 2.0;

return maxHeap.top(); // if odd, maxHeap is larger

};

� Quick Explanation:

1. Use two heaps:


2. maxHeap stores the smaller half
3. minHeap stores the larger half
4. Balance the heaps so their sizes differ by at most 1
5. Median is:
6. Top of both heaps averaged (even size)
7. Top of maxHeap (odd size)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Time & Space Complexity:

addNum: O(log N)

findMedian: O(1)

Space: O(N)

PROBLEM:244

Question: K most frequent elements


Problem Statement:

Given an integer array nums and an integer k, return the k most frequent elements.

� Example:

Input: nums = [1,1,1,2,2,3], k = 2

Output: [1,2]

✅ C++ Code — Hash Map + Min Heap

cpp

#include <iostream>

#include <vector>

#include <unordered_map>

#include <queue>

using namespace std;

vector<int> topKFrequent(vector<int>& nums, int k) {

unordered_map<int, int> freq;

for (int num : nums)

freq[num]++;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> minHeap;

for (auto& [num, count] : freq) {

minHeap.push({count, num});

if (minHeap.size() > k)

minHeap.pop();

vector<int> result;

while (!minHeap.empty()) {

result.push_back(minHeap.top().second);

minHeap.pop();

return result;

� Quick Explanation:

1. Count frequencies using a hash map.


2. Use a min-heap to keep track of the top k frequent elements.
3. If heap exceeds size k, pop the least frequent one.

� Time & Space Complexity:

Time: O(N log K)

Space: O(N)

PROBLEM:245

Question: Assign Cookies

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Problem Statement:

You are given two integer arrays:

g[i]: greed factor of child i

s[j]: size of cookie j

Each child can get at most one cookie, and will be satisfied if s[j] >= g[i].
Return the maximum number of content children.

� Example:

Input: g = [1,2,3], s = [1,1]

Output: 1

Explanation: Only one child can be content with available cookies.

✅ C++ Code — Greedy Approach

cpp

#include <iostream>#include <vector>#include <algorithm>using namespace std;

int findContentChildren(vector<int>& g, vector<int>& s) {

sort(g.begin(), g.end());

sort(s.begin(), s.end());

int i = 0, j = 0;

while (i < g.size() && j < s.size()) {

if (s[j] >= g[i]) {

i++; // content child

j++; // move to next cookie

return i;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� Quick Explanation:

1. Sort both arrays.


2. Greedily assign the smallest possible cookie that satisfies a child.
3. If cookie is too small, skip to next cookie. If it's enough, assign and move both pointers.

� Time & Space Complexity:

Time: O(N log N + M log M)

Space: O(1) (in-place sort)

PROBLEM:246

Question: Fractional Knapsack Problem


Problem Statement:

Given N items with value[] and weight[], and a knapsack with capacity W,
choose fractions of items to maximize total value.

✅ Unlike 0/1 knapsack, you can take fractions of an item.

� Example:

Input:

value[] = {60, 100, 120}

weight[] = {10, 20, 30}

W = 50

Output: 240.0

Explanation: Take full item 2 (100), full item 1 (60), and 2/3 of item 3 (80)

✅ C++ Code — Greedy + Custom Sort

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>#include <vector>#include <algorithm>using namespace std;

struct Item {

int value, weight;

Item(int v, int w) : value(v), weight(w) {}

};

// Compare by value-to-weight ratiobool cmp(Item a, Item b) {

return (double)a.value / a.weight > (double)b.value / b.weight;

double fractionalKnapsack(int W, vector<Item>& items) {

sort(items.begin(), items.end(), cmp);

double totalValue = 0.0;

for (Item& item : items) {

if (W >= item.weight) {

W -= item.weight;

totalValue += item.value;

} else {

totalValue += (double)item.value * W / item.weight;

break;

return totalValue;

� Quick Explanation:

1. Calculate value-to-weight ratio for all items.


2. Sort items by highest ratio (most value per unit weight).
3. Greedily pick full items, and fractional last item if needed.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Time & Space Complexity:

Time: O(N log N) for sorting

Space: O(1) (excluding input)

PROBLEM:247

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

Question: Greedy algorithm to find minimum number of coins


Problem Statement:

Given a list of coin denominations and an amount V,


find the minimum number of coins needed to make the amount using a greedy approach
(assume infinite supply of coins).

� Example:

Input: coins = [1, 2, 5, 10, 20, 50, 100, 500, 2000], V = 93

Output: 50 20 20 2 1

Explanation: Minimum coins to make 93

✅ C++ Code — Greedy Approach

cpp

#include <iostream>#include <vector>#include <algorithm>using namespace std;

void findMinCoins(vector<int>& coins, int V) {

sort(coins.rbegin(), coins.rend()); // sort in descending order

vector<int> result;

for (int coin : coins) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


while (V >= coin) {

V -= coin;

result.push_back(coin);

cout << "Coins used: ";

for (int coin : result) cout << coin << " ";

cout << endl;

� Quick Explanation:

1. Sort coins descendingly.


2. Pick the largest possible coin as many times as it fits into the remaining amount.
3. Repeat until the amount becomes zero.

PROBLEM:248

Question: Lemonade Change


Problem Statement:

At a lemonade stand, each lemonade costs $5.


Customers pay with $5, $10, or $20 bills — in that order.
You must provide correct change at each step using bills you have received so far.
Return true if you can give change to every customer, otherwise false.

� Example:

Input: [5, 5, 5, 10, 20]

Output: true

Explanation:

- 5 → keep

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


- 5 → keep

- 5 → keep

- 10 → give back 5

- 20 → give back 10 + 5

✅ C++ Code — Greedy

cpp

#include <iostream>#include <vector>using namespace std;

bool lemonadeChange(vector<int>& bills) {

int five = 0, ten = 0;

for (int bill : bills) {

if (bill == 5) {

five++;

} else if (bill == 10) {

if (five == 0) return false;

five--; ten++;

} else { // bill == 20

if (ten > 0 && five > 0) {

ten--; five--;

} else if (five >= 3) {

five -= 3;

} else {

return false;

return true;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

� Quick Explanation:

1. Count how many $5 and $10 bills you have.


2. For $10 → give back one $5.
3. For $20 → give one $10 + $5 if possible, else give three $5s.
4. If neither possible → return false.

� Time & Space Complexity:

Time: O(n)

Space: O(1)

PROBLEM:249

Question: Valid Paranthesis Checker


Problem Statement:

Given a string containing '(', ')', '{', '}', '[', ']', determine if the brackets are valid.
A string is valid if:

Brackets are closed by the correct type

Brackets are closed in the correct order

� Example:

Input: s = "({[]})"

Output: true

Input: s = "({[)]}"

Output: false

✅ C++ Code — Using Stack

cpp

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


#include <iostream>#include <stack>#include <unordered_map>using namespace std;

bool isValid(string s) {

stack<char> st;

unordered_map<char, char> match = {{')','('}, {']','['}, {'}','{'}};

for (char c : s) {

if (match.count(c)) {

if (st.empty() || st.top() != match[c]) return false;

st.pop();

} else {

st.push(c);

return st.empty();

� Quick Explanation:

1. Push opening brackets onto a stack.


2. For closing brackets, check if the top matches the corresponding opening one.
3. If it doesn’t match or stack is empty → invalid.
4. At the end, stack should be empty if valid.

� Time & Space Complexity:

Time: O(n)

Space: O(n)

PROBLEM:250

Question: N meetings in one room


Problem Statement:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


You are given N meetings with start[] and **end[]` times.
Find the maximum number of meetings that can be scheduled in a single room without
overlaps.

� Example:

Input:

start[] = {1, 3, 0, 5, 8, 5}

end[] = {2, 4, 6, 7, 9, 9}

Output: 4

Explanation: Meetings at indices {0, 1, 3, 4} can be selected.

✅ C++ Code — Greedy + Sorting by End Time

cpp

#include <iostream>#include <vector>#include <algorithm>using namespace std;

struct Meeting {

int start, end;

};

bool compare(Meeting a, Meeting b) {

return a.end < b.end;

int maxMeetings(vector<int>& start, vector<int>& end) {

int n = start.size();

vector<Meeting> meetings(n);

for (int i = 0; i < n; ++i)

meetings[i] = {start[i], end[i]};

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


sort(meetings.begin(), meetings.end(), compare);

int count = 1;

int lastEnd = meetings[0].end;

for (int i = 1; i < n; ++i) {

if (meetings[i].start > lastEnd) {

count++;

lastEnd = meetings[i].end;

return count;

� Quick Explanation:

1. Store all meetings as {start, end} pairs.


2. Sort them by end time (earliest end finishes first).
3. Select meetings greedily: pick next one only if it starts after last selected one ends.

� Time & Space Complexity:

Time: O(N log N)

Space: O(N) (for meetings vector)

PROBLEM:251

Question: � Jump Game


Problem Statement:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Given an array nums, where each element represents your maximum jump length at that
position,
return true if you can reach the last index, otherwise false.

� Example:

Input: nums = [2, 3, 1, 1, 4]

Output: true

Explanation: Jump 2 → 3 → 4 (reaches end)

Input: nums = [3, 2, 1, 0, 4]

Output: false

Explanation: You get stuck at 0.

✅ C++ Code — Greedy Approach

cpp

#include <iostream>#include <vector>using namespace std;

bool canJump(vector<int>& nums) {

int reachable = 0;

for (int i = 0; i < nums.size(); ++i) {

if (i > reachable) return false;

reachable = max(reachable, i + nums[i]);

return true;

� Quick Explanation:

1. Maintain the maximum reachable index from the current position.


2. At each index, check if you can reach it. If not → return false.
3. Update the farthest reachable point. If you reach or pass the last index → return true.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


� Time & Space Complexity:

Time: O(n)

Space: O(1)

PROBLEM:252

Question: � Jump Game II – Minimum Jumps to Reach End


Problem Statement:

Given an array nums where each element represents your max jump length,
return the minimum number of jumps required to reach the last index.
Assume you can always reach the end.

� Example:

Input: nums = [2, 3, 1, 1, 4]

Output: 2

Explanation: Jump 1 → 4 (i.e. 2 → 3 → 4)

✅ C++ Code — Greedy Level Tracking

cpp

#include <iostream>#include <vector>using namespace std;

int jump(vector<int>& nums) {

int jumps = 0, end = 0, farthest = 0;

for (int i = 0; i < nums.size() - 1; ++i) {

farthest = max(farthest, i + nums[i]);

if (i == end) {

jumps++;

end = farthest;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return jumps;

� Quick Explanation:

1. Traverse array while tracking:


2. farthest: the farthest index you can reach so far
3. end: the boundary of the current jump
4. When you reach end, it means you need another jump → increment jumps, update end.

� Time & Space Complexity:

Time: O(n)

Space: O(1)

PROBLEM:253

Question: :Minimum number of platforms required for a railway


Problem Statement:

Given arrival and departure times of n trains,


find the minimum number of platforms required so that no train waits.

� Example:

Arrival: [900, 940, 950, 1100, 1500, 1800]

Departure: [910, 1200, 1120, 1130, 1900, 2000]

Output: 3

Explanation: Between 940 and 1200, 3 trains are at the station.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


✅ C++ Code — Sorting + Two Pointers

cpp

#include <iostream>#include <vector>#include <algorithm>using namespace std;

int findPlatform(vector<int>& arr, vector<int>& dep) {

sort(arr.begin(), arr.end());

sort(dep.begin(), dep.end());

int platforms = 0, maxPlat = 0;

int i = 0, j = 0, n = arr.size();

while (i < n && j < n) {

if (arr[i] <= dep[j]) {

platforms++;

i++;

} else {

platforms--;

j++;

maxPlat = max(maxPlat, platforms);

return maxPlat;

� Quick Explanation:

1. Sort both arrival and departure times.


2. Traverse both with two pointers:
3. If a train arrives before the next one departs → need a new platform.
4. Else, one train has left → free a platform.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


5. Keep track of max platforms needed at any time.

� Time & Space Complexity:

Time: O(n log n)

Space: O(1) (excluding input)

PROBLEM:254

Question: Job sequencing Problem


Problem Statement:

You are given N jobs where each job has:

an ID

a deadline

a profit

Each job takes 1 unit of time and only one job can be scheduled at a time.
Your goal is to maximize the total profit by selecting and scheduling jobs before their
deadlines.

� Example:

Input:

Jobs = {{id:1, deadline:4, profit:20},

{id:2, deadline:1, profit:10},

{id:3, deadline:1, profit:40},

{id:4, deadline:1, profit:30}}

Output: Max Profit = 60 (Jobs 3 and 1)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


✅ C++ Code — Greedy + Disjoint Slot Booking

cpp

#include <iostream>#include <vector>#include <algorithm>using namespace std;

struct Job {

int id, deadline, profit;

};

bool compare(Job a, Job b) {

return a.profit > b.profit; // sort by profit descending

pair<int, int> jobScheduling(vector<Job>& jobs) {

sort(jobs.begin(), jobs.end(), compare);

int maxDeadline = 0;

for (auto& job : jobs)

maxDeadline = max(maxDeadline, job.deadline);

vector<int> slot(maxDeadline + 1, -1); // index 1-based

int count = 0, maxProfit = 0;

for (auto& job : jobs) {

for (int j = job.deadline; j > 0; --j) {

if (slot[j] == -1) {

slot[j] = job.id;

count++;

maxProfit += job.profit;

break;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


}

return {count, maxProfit};

� Quick Explanation:

1. Sort jobs by profit descending (do most profitable first).


2. For each job, try to schedule it at the latest available slot ≤ deadline.
3. Use a slot array to keep track of which time slots are filled.
4. Count jobs and accumulate profit.

� Time & Space Complexity:

Time: O(N log N + N × D) → D is max deadline

Space: O(D)

PROBLEM:255
Question: Candy
Candy Problem (Greedy)

Problem Statement:

There are n children standing in a line. Each child is assigned a rating value.
You have to give at least one candy to each child, and children with higher rating than
their neighbors must get more candies.

Goal: Minimize the total candies.

� Example:

cpp

CopyEdit

Input: ratings = [1, 0, 2]

Output: 5

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Explanation: Candies = [2, 1, 2]

cpp

CopyEdit

Input: ratings = [1, 2, 2]

Output: 4

Explanation: Candies = [1, 2, 1]

✅ C++ Code — Two Pass Greedy

cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int candy(vector<int>& ratings) {

int n = ratings.size();

vector<int> candies(n, 1);

// Left to right: ensure right child gets more if rating is higher

for (int i = 1; i < n; ++i)

if (ratings[i] > ratings[i - 1])

candies[i] = candies[i - 1] + 1;

// Right to left: ensure left child gets more if rating is higher

for (int i = n - 2; i >= 0; --i)

if (ratings[i] > ratings[i + 1])

candies[i] = max(candies[i], candies[i + 1] + 1);

int total = 0;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


for (int c : candies) total += c;

return total;

� Quick Explanation:

1. First pass: Left to right — handle increasing sequences.


2. Second pass: Right to left — handle decreasing sequences.
3. Use max() to keep the larger requirement from both directions.
4. Sum the candy array for the answer

� Time & Space Complexity:

Time: O(n)

Space: O(n)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

PROBLEM:256
Question: Program for Shortest Job First (or SJF) CPU Scheduling

Shortest Job First (SJF) CPU Scheduling Algorithm (Non-Preemptive)

SJF selects the process with the shortest burst time first. It’s an optimal strategy in terms of
average waiting time, but not preemptive in basic form.

� Assumptions:

All processes arrive at time = 0 (or modify for arrival time variant).

Each process has:

Process ID

Burst Time

✅ C++ Code — Non-Preemptive SJF (All Arrival = 0)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

struct Process {

int pid;

int burst;

};

bool compare(Process a, Process b) {

return a.burst < b.burst;

void findWaitingTime(vector<Process>& proc, vector<int>& wt) {

wt[0] = 0;

for (int i = 1; i < proc.size(); i++)

wt[i] = wt[i - 1] + proc[i - 1].burst;

void findTurnAroundTime(vector<Process>& proc, vector<int>& wt, vector<int>& tat) {

for (int i = 0; i < proc.size(); i++)

tat[i] = proc[i].burst + wt[i];

void findAvgTime(vector<Process>& proc) {

int n = proc.size();

vector<int> wt(n), tat(n);

sort(proc.begin(), proc.end(), compare); // Sort by burst time

findWaitingTime(proc, wt);

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


findTurnAroundTime(proc, wt, tat);

cout << "PID\tBurst\tWait\tTurnaround\n";

float total_wt = 0, total_tat = 0;

for (int i = 0; i < n; i++) {

cout << proc[i].pid << "\t" << proc[i].burst << "\t" << wt[i] << "\t" << tat[i] << "\n";

total_wt += wt[i];

total_tat += tat[i];

cout << "\nAvg Waiting Time: " << total_wt / n;

cout << "\nAvg Turnaround Time: " << total_tat / n << "\n";

int main() {

vector<Process> proc = {{1, 6}, {2, 8}, {3, 7}, {4, 3}};

findAvgTime(proc);

return 0;

� Quick Explanation:

1. Sort processes by burst time.


2. Compute waiting time using cumulative previous burst times.
3. Turnaround time = waiting time + burst time.
4. Output all metrics and compute averages.

� Time & Space Complexity:

Time: O(n log n) (due to sorting)

Space: O(n)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


PROBLEM:257
Question: Program for Least Recently Used (LRU) Page Replacement Algorithm

Least Recently Used (LRU) Page Replacement Algorithm

Problem Statement:

Simulate the LRU page replacement algorithm, where the least recently used page is
replaced when the cache is full.

� Example:

Input: Pages = [1, 2, 3, 4, 2, 1, 5], Capacity = 3

Output: Page Faults = 6

Explanation: Only one hit (for page 2 on second occurrence)

✅ C++ Code — Using list + unordered_map

cpp

#include <iostream>#include <list>#include <unordered_map>#include <vector>using


namespace std;

int LRU_PageFaults(vector<int>& pages, int capacity) {

list<int> lru; // keeps order of usage

unordered_map<int, list<int>::iterator> pos; // maps page to its position in list

int faults = 0;

for (int page : pages) {

// If page is not in cache (miss)

if (pos.find(page) == pos.end()) {

faults++;

if (lru.size() == capacity) {

// Remove least recently used page

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int lruPage = lru.back();

lru.pop_back();

pos.erase(lruPage);

} else {

// If page is already in cache, remove it to move to front

lru.erase(pos[page]);

// Insert page at front as most recently used

lru.push_front(page);

pos[page] = lru.begin();

return faults;

int main() {

vector<int> pages = {1, 2, 3, 4, 2, 1, 5};

int capacity = 3;

cout << "Page Faults: " << LRU_PageFaults(pages, capacity) << endl;

return 0;

� Quick Explanation:

1. Use a list to keep the order of page usage (front = most recent).
2. Use a map to store iterators to list nodes for quick access.
3. On access:If page is in cache → move to front.

If not:

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


If full → remove from back (least recently used).

4. Insert new page at front.


5. Count page faults accordingly.

� Time & Space Complexity:

Time: O(1) per page using unordered_map + list

Space: O(capacity)

PROBLEM:258
Question: Insert Interval

Insert Interval (Leetcode #57)

Problem Statement:

You are given a list of non-overlapping intervals, sorted by start time.


Insert a new interval, and merge if necessary.

� Example:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]

Output: [[1,5],[6,9]]

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]

Output: [[1,2],[3,10],[12,16]]

✅ C++ Code — Merge on Insert

cpp

#include <iostream>#include <vector>using namespace std;

vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {

vector<vector<int>> result;

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


int i = 0, n = intervals.size();

// 1. Add all intervals before newInterval

while (i < n && intervals[i][1] < newInterval[0])

result.push_back(intervals[i++]);

// 2. Merge overlapping intervals

while (i < n && intervals[i][0] <= newInterval[1]) {

newInterval[0] = min(newInterval[0], intervals[i][0]);

newInterval[1] = max(newInterval[1], intervals[i][1]);

i++;

result.push_back(newInterval);

// 3. Add remaining intervals

while (i < n)

result.push_back(intervals[i++]);

return result;

� Quick Explanation:

1. Add all intervals before the new interval (no overlap).


2. Merge all intervals that overlap with newInterval.
3. Add all intervals after the merged one.

� Time & Space Complexity:

Time: O(n)

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Space: O(n)

The PDF created by Abhishek Rathor (Instagram:SYNTAX


ERROR)

PROBLEM:259

Question: Merge Intervals


Problem Statement:

Given an array of intervals where intervals[i] = [start, end],


merge all overlapping intervals and return the result.

� Example:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]

Output: [[1,6],[8,10],[15,18]]

Input: intervals = [[1,4],[4,5]]

Output: [[1,5]]

✅ C++ Code — Sorting + Merge

cpp

#include <iostream>#include <vector>#include <algorithm>using namespace std;

vector<vector<int>> merge(vector<vector<int>>& intervals) {

if (intervals.empty()) return {};

sort(intervals.begin(), intervals.end());

vector<vector<int>> merged;

merged.push_back(intervals[0]);

for (int i = 1; i < intervals.size(); ++i) {

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


if (merged.back()[1] >= intervals[i][0]) {

merged.back()[1] = max(merged.back()[1], intervals[i][1]);

} else {

merged.push_back(intervals[i]);

return merged;

� Quick Explanation:

1. Sort intervals by start time.


2. Iterate through each interval:
3. If it overlaps with the previous → merge them.
4. If not → add as a new interval.
5. Use merged.back() to update or append.

� Time & Space Complexity:

Time: O(n log n) (due to sorting)

Space: O(n) (result array)

PROBLEM:260

Question: Non-overlapping Intervals


Problem Statement:

You are given a list of intervals.


Return the minimum number of intervals you need to remove to make the rest of the
intervals non-overlapping.

� Example:

Input: [[1,2],[2,3],[3,4],[1,3]]

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


Output: 1

Explanation: Remove [1,3] to make the rest non-overlapping.

Input: [[1,2],[1,2],[1,2]]

Output: 2

✅ C++ Code — Greedy by End Time

cpp

#include <iostream>#include <vector>#include <algorithm>using namespace std;

int eraseOverlapIntervals(vector<vector<int>>& intervals) {

if (intervals.empty()) return 0;

// Sort by end time

sort(intervals.begin(), intervals.end(), [](auto& a, auto& b) {

return a[1] < b[1];

});

int count = 0;

int prevEnd = intervals[0][1];

for (int i = 1; i < intervals.size(); ++i) {

if (intervals[i][0] < prevEnd) {

count++; // overlap found, remove this one

} else {

prevEnd = intervals[i][1]; // update previous end

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)


return count;

� Quick Explanation:

1. Sort intervals by end time (greedy approach).


2. Track the end of last selected interval.
3. If current interval starts before that, it overlaps → remove it.
4. Else, update the prevEnd.

� Time & Space Complexity:

Time: O(n log n) (for sorting)

Space: O(1)

Congratulations on completing the PDF created by SYNTAX ERROR, also known as


Abhishek Rathor!
Your dedication and perseverance are truly commendable. For more insights and
updates, feel free
to connect on Instagram at SYNTAX ERROR.

The PDF created by Abhishek Rathor (Instagram:SYNTAX ERROR)

You might also like