Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions C-Plus-Plus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,17 @@
- [Side Views of The binary tree ](ds/Side_Views_of_Binary_tree.cpp)
- [Convert BST to Min Heap ](ds/BSTtoMinHeap.cpp)


### Sliding Window

| Problem | Description |
|----------|--------------|
| [Maximum Sum Subarray of Size K](./Sliding_Window/max_sum_subarray.cpp) | Find the maximum sum of subarray of size K |
| [First Negative Integer in Every Window of Size K](./Sliding_Window/first_negative_in_window.cpp) | Find the first negative number in each window |
| [Longest Substring with K Distinct Characters](./Sliding_Window/longest_substring_k_distinct.cpp) | Find length of longest substring with at most K distinct characters |
| [Minimum Window Substring](./Sliding_Window/min_window_substring.cpp) | Find the smallest window containing all characters of another string |


## Graphs

- [Adjacency List Representation](graphs/Adjacency_List.cpp)
Expand Down Expand Up @@ -374,6 +385,11 @@
- [Sqrt Monotonic Binary Search](search/Sqrt_Monotonic_Binary_Search.cpp)
- [Order Agnostic Binary Search](search/orderAgnosticBS.cpp)


## Greedy
- [Greedy Algorithms](./greedy/README.md)


## Sorting

- [Bead Sort](sort/Bead_Sort.cpp)
Expand Down
32 changes: 32 additions & 0 deletions C-Plus-Plus/greedy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Greedy Algorithms (C++)

This folder contains implementations of popular **Greedy Algorithms** in C++.

Greedy algorithms make the locally optimal choice at each step with the hope of finding a global optimum.
These are widely used in optimization problems.

---

## 📚 List of Implemented Problems

| No. | Problem | Description | Time Complexity |
|-----|----------|--------------|----------------|
| 1 | [Activity Selection](activity_selection.cpp) | Select maximum number of non-overlapping activities | O(n log n) |
| 2 | [Fractional Knapsack](fractional_knapsack.cpp) | Maximize total value in a knapsack allowing fractional items | O(n log n) |
| 3 | [Job Sequencing Problem](job_sequencing.cpp) | Schedule jobs to maximize profit within deadlines | O(n²) |
| 4 | [Huffman Encoding](huffman_encoding.cpp) | Generate Huffman codes for characters based on frequency | O(n log n) |

---

## 🧠 Concepts Used
- Sorting and Priority Queues
- Greedy Choice Property
- Optimal Substructure
- Min-Heap / Max-Heap usage

---

## 🛠 How to Run
```bash
g++ filename.cpp -o output
./output
33 changes: 33 additions & 0 deletions C-Plus-Plus/greedy/activity-selection.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <bits/stdc++.h>
using namespace std;

// Function to find maximum number of non-overlapping activities
int activitySelection(vector<int>& start, vector<int>& end) {
int n = start.size();
vector<pair<int, int>> activities;
for (int i = 0; i < n; i++) {
activities.push_back({end[i], start[i]});
}

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

int count = 1;
int last_end = activities[0].first;

for (int i = 1; i < n; i++) {
if (activities[i].second >= last_end) {
count++;
last_end = activities[i].first;
}
}
return count;
}

int main() {
vector<int> start = {1, 3, 0, 5, 8, 5};
vector<int> end = {2, 4, 6, 7, 9, 9};

cout << "Maximum number of activities: " << activitySelection(start, end) << endl;
return 0;
}
35 changes: 35 additions & 0 deletions C-Plus-Plus/greedy/fractional-knapsack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include <bits/stdc++.h>
using namespace std;

struct Item {
int value, weight;
};

bool cmp(Item a, Item b) {
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}

double fractionalKnapsack(int W, vector<Item>& arr) {
sort(arr.begin(), arr.end(), cmp);

double totalValue = 0.0;
for (auto& item : arr) {
if (W >= item.weight) {
totalValue += item.value;
W -= item.weight;
} else {
totalValue += item.value * ((double)W / item.weight);
break;
}
}
return totalValue;
}

int main() {
int W = 50;
vector<Item> arr = {{60, 10}, {100, 20}, {120, 30}};
cout << "Maximum value in Knapsack = " << fractionalKnapsack(W, arr) << endl;
return 0;
}
50 changes: 50 additions & 0 deletions C-Plus-Plus/greedy/huffman-encoding.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include <bits/stdc++.h>
using namespace std;

struct Node {
char data;
int freq;
Node *left, *right;

Node(char data, int freq) : data(data), freq(freq), left(nullptr), right(nullptr) {}
};

struct Compare {
bool operator()(Node* a, Node* b) {
return a->freq > b->freq;
}
};

void printCodes(Node* root, string str) {
if (!root) return;
if (root->data != '$')
cout << root->data << ": " << str << "\n";
printCodes(root->left, str + "0");
printCodes(root->right, str + "1");
}

void huffmanCodes(vector<char> data, vector<int> freq) {
priority_queue<Node*, vector<Node*>, Compare> pq;

for (int i = 0; i < data.size(); i++)
pq.push(new Node(data[i], freq[i]));

while (pq.size() > 1) {
Node* left = pq.top(); pq.pop();
Node* right = pq.top(); pq.pop();

Node* top = new Node('$', left->freq + right->freq);
top->left = left;
top->right = right;
pq.push(top);
}

printCodes(pq.top(), "");
}

int main() {
vector<char> data = {'a', 'b', 'c', 'd', 'e', 'f'};
vector<int> freq = {5, 9, 12, 13, 16, 45};
huffmanCodes(data, freq);
return 0;
}
43 changes: 43 additions & 0 deletions C-Plus-Plus/greedy/job-sequence.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <bits/stdc++.h>
using namespace std;

struct Job {
int id;
int deadline;
int profit;
};

bool cmp(Job a, Job b) {
return a.profit > b.profit;
}

pair<int, int> jobScheduling(vector<Job>& jobs) {
sort(jobs.begin(), jobs.end(), cmp);

int maxDeadline = 0;
for (auto& job : jobs) maxDeadline = max(maxDeadline, job.deadline);

vector<int> slot(maxDeadline + 1, -1);
int countJobs = 0, totalProfit = 0;

for (auto& job : jobs) {
for (int j = job.deadline; j > 0; j--) {
if (slot[j] == -1) {
slot[j] = job.id;
countJobs++;
totalProfit += job.profit;
break;
}
}
}

return {countJobs, totalProfit};
}

int main() {
vector<Job> jobs = {{1, 2, 100}, {2, 1, 19}, {3, 2, 27}, {4, 1, 25}, {5, 3, 15}};
auto result = jobScheduling(jobs);
cout << "Number of jobs done: " << result.first << endl;
cout << "Total profit: " << result.second << endl;
return 0;
}
21 changes: 21 additions & 0 deletions C-Plus-Plus/slidingwindow/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Sliding Window Algorithms in C++

This folder contains C++ implementations of common **Sliding Window problems**.

## 📘 Problems Implemented

1. [Maximum Sum Subarray of Size K](./max_sum_subarray.cpp)
2. [First Negative Integer in Every Window of Size K](./first_negative_in_window.cpp)
3. [Longest Substring with K Distinct Characters](./longest_substring_k_distinct.cpp)
4. [Minimum Window Substring](./min_window_substring.cpp)

## 🧩 Concept Overview

The Sliding Window technique is used to reduce time complexity in problems involving **contiguous subarrays or substrings**.

- Time Complexity: Often reduced from O(N²) → O(N)
- Common use-cases: Strings, arrays, subarrays with given constraints

## 🧠 Example
For array `[2, 1, 5, 1, 3, 2]` and `k = 3` →
The maximum sum subarray is `[5, 1, 3]` with sum = **9**.
52 changes: 52 additions & 0 deletions C-Plus-Plus/slidingwindow/first-negative-in-window.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
Problem: First Negative Integer in Every Window of Size K
Language: C++
Author: <Umang Chandra>
Description: Print the first negative number in each window of size K using a queue.
*/

#include <bits/stdc++.h>
using namespace std;

vector<int> firstNegativeInWindow(const vector<int>& arr, int k) {
deque<int> dq;
vector<int> result;

for (int i = 0; i < arr.size(); i++) {
// Remove elements outside the window
if (!dq.empty() && dq.front() == i - k)
dq.pop_front();

// Add negative numbers
if (arr[i] < 0)
dq.push_back(i);

// Start adding results after the first k elements
if (i >= k - 1) {
if (!dq.empty())
result.push_back(arr[dq.front()]);
else
result.push_back(0);
}
}

return result;
}

int main() {
vector<int> arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;

vector<int> res = firstNegativeInWindow(arr, k);
cout << "First negative integers in every window of size " << k << ":\n";
for (int x : res) cout << x << " ";
cout << endl;

return 0;
}

/*
Sample Output:
First negative integers in every window of size 3:
-1 -1 -7 -15 -15 0
*/
46 changes: 46 additions & 0 deletions C-Plus-Plus/slidingwindow/longest-substring-k-distinct.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Problem: Longest Substring with K Distinct Characters
Language: C++
Author: <Umang Chandra>
Description: Use Sliding Window with HashMap to track character frequency and expand/shrink window dynamically.
*/

#include <bits/stdc++.h>
using namespace std;

int longestKDistinct(string s, int k) {
int n = s.size();
if (k == 0 || n == 0) return 0;

unordered_map<char, int> freq;
int left = 0, maxLen = 0;

for (int right = 0; right < n; right++) {
freq[s[right]]++;

// Shrink window if distinct count > k
while (freq.size() > k) {
freq[s[left]]--;
if (freq[s[left]] == 0)
freq.erase(s[left]);
left++;
}

maxLen = max(maxLen, right - left + 1);
}

return maxLen;
}

int main() {
string s = "eceba";
int k = 2;
cout << "Length of longest substring with at most " << k << " distinct characters: "
<< longestKDistinct(s, k) << endl;
return 0;
}

/*
Sample Output:
Length of longest substring with at most 2 distinct characters: 3
*/
40 changes: 40 additions & 0 deletions C-Plus-Plus/slidingwindow/max-subarray-sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
Problem: Maximum Sum Subarray of Size K
Language: C++
Author: <Umang Chandra>
Description: Find the maximum sum of any contiguous subarray of size K using the Sliding Window technique.
*/

#include <bits/stdc++.h>
using namespace std;

int maxSumSubarray(vector<int>& arr, int k) {
int n = arr.size();
if (n < k) return -1;

int windowSum = 0, maxSum = INT_MIN;

// Compute sum of first window
for (int i = 0; i < k; i++) windowSum += arr[i];
maxSum = windowSum;

// Slide window
for (int i = k; i < n; i++) {
windowSum += arr[i] - arr[i - k];
maxSum = max(maxSum, windowSum);
}

return maxSum;
}

int main() {
vector<int> arr = {2, 1, 5, 1, 3, 2};
int k = 3;
cout << "Maximum sum of subarray of size " << k << " = " << maxSumSubarray(arr, k) << endl;
return 0;
}

/*
Sample Output:
Maximum sum of subarray of size 3 = 9
*/
Loading
Loading