Crack Maang Companies - DSA Questions (C++) - 1
Crack Maang Companies - DSA Questions (C++) - 1
COMPANIES
DAARIS AMEEN
Page | 1
DAARIS AMEEN
TRIE
Implement Trie – 1
Problem Statement: Implementing insertion, search, and startWith operations in a trie or
prefix-tree.
Implementation:
Type 1: To insert a string “word” in Trie.
Type 2: To check if the string “word” is present in Trie or not.
Type 3: To check if there is any string in the Trie that starts with the given prefix string
“word”.
Example: Input: type = {1, 1, 2, 3, 2}; value = {"hello", "help", "help", "hel", "hel"}; Output:
true true false Explanation: Trie object initialized “hello” inserted in the trie. “help”
insertedin the trie “help” searched in the trie //returns true Checked if any previously
inserted word has the prefix “hel” //return true “hel” searches in the trie //returns true
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define MAXN 100001
#define INF 1e18+1
struct Node {
Node *links[26];
bool flag = false;
//checks if the reference trie is present or not
bool containKey(char ch) {
return (links[ch - 'a'] != NULL);
}
//creating reference trie
void put(char ch, Node *node) {
links[ch - 'a'] = node;
}
//to get the next node for traversal
Node *get(char ch) {
return links[ch - 'a'];
}
//setting flag to true at the end of the word
void setEnd() {
flag = true;
}
//checking if the word is completed or not
bool isEnd() {
return flag;
}
};
class Trie {
Page | 2
DAARIS AMEEN
private:
Node* root;
public:
Trie() {
//creating new obejct
root = new Node();
}
int main()
{
int n = 5;
vector<int>type = {1, 1, 2, 3, 2};
vector<string>value = {"hello", "help", "help", "hel", "hel"};
Trie trie;
Page | 3
DAARIS AMEEN
Implement Trie – II
Problem Statement: Implement a data structure ”TRIE” from scratch. Complete some
functions.
1) Trie(): Initialize the object of this “TRIE” data structure.
2) insert(“WORD”): Insert the string “WORD” into this “TRIE” data structure.
3) countWordsEqualTo(“WORD”): Return how many times this “WORD” is present in this
“TRIE”.
4) countWordsStartingWith(“PREFIX”): Return how many words are there in this “TRIE”
that have the string “PREFIX” as a prefix.
5) erase(“WORD”): Delete this string “WORD” from the “TRIE”.
Note:
1. If erase(“WORD”) function is called then it is guaranteed that the “WORD” is presentin
the “TRIE”.
2. If you are going to use variables with dynamic memory allocation then you need to
release the memory associated with them at the end of your solution.
Example: Input: 1 6 insert samsung insert samsung insert vivo erase vivo
countWordsEqualTo samsung countWordsStartingWith vi Output: 2 0
Page | 4
DAARIS AMEEN
Explanation:
Insert “samsung”: we are going to insert the word “samsung” into the “TRIE”. Insert
“samsung”: we are going to insert the word “samsung” again into the “TRIE”. Insert “vivo”:
we are going to insert the word “vivo” into the “TRIE”. Erase “vivo”: we are going to delete
the word “vivo” from the “TRIE”. countWordsEqualTo “samsung”: There are two instancesof
“samsung” is present in “TRIE”. countWordsStartWith “vi”:There is not a single word in the
“TRIE” that starts from the prefix “vi”.
#include <bits/stdc++.h>
public:
Page | 5
DAARIS AMEEN
int main() {
Trie T;
T.insert("apple");
T.insert("apple");
T.insert("apps");
T.insert("apps");
string word1 = "apps";
cout<<"Count Words Equal to "<< word1<<"
"<<T.countWordsEqualTo(word1)<<endl;
string word2 = "abc";
cout<<"Count Words Equal to "<< word2<<"
"<<T.countWordsEqualTo(word2)<<endl;
string word3 = "ap";
cout<<"Count Words Starting With "<<word3<<"
"<<T.countWordsStartingWith(word3)
<<endl;
string word4 = "appl";
cout<<"Count Words Starting With "<< word4<<"
"<<T.countWordsStartingWith(word4)
<<endl;
T.erase(word1);
cout<<"Count Words equal to "<< word1<<"
"<<T.countWordsEqualTo(word1)<<endl;
return 0;
}
struct Node {
Node * links[26];
}
return count + 1;
}
int main() {
string s1 = "ababa";
cout << "Total number of distinct substrings : " <<
countDistinctSubstrings(s1);
cout << "\n";
Page | 8
DAARIS AMEEN
string s2 = "ccfdf";
cout << "Total number of distinct substrings : " <<
countDistinctSubstrings(s2);
return 0;
}
struct Node {
Node * links[2];
public:
void insert(int num) {
Node * node = root;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
if (!node -> containsKey(bit)) {
node -> put(bit, new Node());
}
node = node -> get(bit);
}
}
public:
int findMax(int num) {
Node * node = root;
int maxNum = 0;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
if (node -> containsKey(!bit)) {
maxNum = maxNum | (1 << i);
node = node -> get(!bit);
} else {
node = node -> get(bit);
}
}
return maxNum;
}
};
vector < int > maxXorQueries(vector < int > & arr, vector < vector <
int
>> & queries) {
vector < int > ans(queries.size(), 0);
vector < pair < int, pair < int, int >>> offlineQueries;
sort(arr.begin(), arr.end());
int index = 0;
for (auto & it: queries) {
offlineQueries.push_back({
it[1],
{
P a g e | 10
DAARIS AMEEN
it[0],
index++
}
});
}
sort(offlineQueries.begin(), offlineQueries.end());
int i = 0;
int n = arr.size();
Trie trie;
}
P a g e | 11
DAARIS AMEEN
TREE
Prorder - Iterative
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> preorder;
if(root == NULL) return preorder;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
root = st.top();
st.pop();
preorder.push_back(root->val);
if(root->right != NULL){
st.push(root->right);
}
if(root->left!= NULL){
st.push(root->left);
}
}
return preorder;
}
};
Inorder - Recursive
class Solution {
private:
void dfs(TreeNode *node, vector<int> &inorder) {
if(node == NULL) return;
dfs(node->left, inorder);
inorder.push_back(node->val);
dfs(node->right, inorder);
}
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> inorder;
dfs(root, inorder);
return inorder;
}
};
postorder 2 stacks
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> postorder;
P a g e | 12
DAARIS AMEEN
postorder 1 stack
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> postorder;
if(root == NULL) return postorder;
stack<TreeNode*> st1;
TreeNode* current = root;
while(current != NULL || !st1.empty()) {
if(current != NULL){
st1.push(current);
current = current->left;
}else{
TreeNode* temp = st1.top()->right;
if (temp == NULL) {
temp = st1.top();
st1.pop();
postorder.push_back(temp->val);
while (!st1.empty() && temp == st1.top()->right) {
temp = st1.top();
st1.pop();
postorder.push_back(temp->val);
}
} else {
current = temp;
}
}
P a g e | 13
DAARIS AMEEN
}
return postorder;
}
};
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<pair<TreeNode*,int>> st;
P a g e | 14
DAARIS AMEEN
st.push({root, 1});
vector<int> pre, in, post;
if(root == NULL) return post;
while(!st.empty()) {
auto it = st.top();
st.pop();
if(it.first->left != NULL) {
st.push({it.first->left, 1});
}
}
// this is a part of in
// increment 2 to 3
// push right
else if(it.second == 2) {
in.push_back(it.first->val);
it.second++;
st.push(it);
if(it.first->right != NULL) {
st.push({it.first->right, 1});
}
}
// don't push it back again
else {
post.push_back(it.first->val);
}
}
return post;
}
};
Max depth of BT
class Solution {
public:
P a g e | 15
DAARIS AMEEN
int lh = maxDepth(root->left);
int rh = maxDepth(root->right);
Diameter of BT
P a g e | 17
DAARIS AMEEN
Zig-Zag traversal
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
if (root == NULL) {
return result;
}
queue<TreeNode*> nodesQueue;
nodesQueue.push(root);
bool leftToRight = true;
while ( !nodesQueue.empty()) {
int size = nodesQueue.size();
vector<int> row(size);
for (int i = 0; i < size; i++) {
TreeNode* node = nodesQueue.front();
nodesQueue.pop();
row[index] = node->val;
if (node->left) {
nodesQueue.push(node->left);
}
if (node->right) {
nodesQueue.push(node->right);
}
}
// after this level
leftToRight = !leftToRight;
result.push_back(row);
}
return result;
}
};
P a g e | 20
DAARIS AMEEN
Boundary Traversal
class Solution {
bool isLeaf(Node* root) {
return !root->left && !root->right;
}
if (!isLeaf(root)) res.push_back(root->data);
addLeftBoundary(root, res);
addRightBoundary(root, res);
P a g e | 21
DAARIS AMEEN
return res;
}
};
Top view of BT
class Solution
{
public:
//Function to return a list of nodes visible from the top view
//from left to right in Binary Tree.
vector<int> topView(Node *root)
{
vector<int> ans;
if(root == NULL) return ans;
map<int,int> mpp;
queue<pair<Node*, int>> q;
q.push({root, 0});
P a g e | 22
DAARIS AMEEN
while(!q.empty()) {
auto it = q.front();
q.pop();
Node* node = it.first;
int line = it.second;
if(mpp.find(line) == mpp.end()) mpp[line] = node->data;
if(node->left != NULL) {
q.push({node->left, line-1});
}
if(node->right != NULL) {
q.push({node->right, line + 1});
}
for(auto it : mpp) {
ans.push_back(it.second);
}
return ans;
}
};
Bottom View of BT
class Solution {
public:
vector <int> bottomView(Node *root) {
vector<int> ans;
if(root == NULL) return ans;
map<int,int> mpp;
queue<pair<Node*, int>> q;
q.push({root, 0});
while(!q.empty()) {
auto it = q.front();
q.pop();
Node* node = it.first;
int line = it.second;
mpp[line] = node->data;
if(node->left != NULL) {
q.push({node->left, line-1});
}
if(node->right != NULL) {
q.push({node->right, line + 1});
}
for(auto it : mpp) {
P a g e | 23
DAARIS AMEEN
ans.push_back(it.second);
}
return ans;
}
};
Right/Left View of BT
class Solution {
public:
void recursion(TreeNode *root, int level, vector<int> &res)
{
if(root==NULL) return ;
if(res.size()==level) res.push_back(root->val);
recursion(root->right, level+1, res);
recursion(root->left, level+1, res);
}
Symmetrical BT
class Solution {
public:
bool f(TreeNode *root1, TreeNode* root2) {
if(!root1) return !root2;
if(!root2) return !root1;
return (root1->val == root2->val) && f(root1->left, root2-
>right) && f(root1->right, root2->left);
}
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return f(root->left, root->right);
}
};
// return true
if (root->val == x)
return true;
//result
if(left == NULL) {
return right;
}
else if(right == NULL) {
return left;
}
else { //both left and right are not null, we found our result
return root;
}
}
};
P a g e | 25
DAARIS AMEEN
Maximum width of BT
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if(!root)
return 0;
int ans = 0;
queue<pair<TreeNode*, int>> q;
q.push({root,0});
while(!q.empty()){
int size = q.size();
int mmin = q.front().second; //to make the id starting
from zero
int first,last;
for(int i=0; i<size; i++){
int cur_id = q.front().second-mmin;
TreeNode* node = q.front().first;
q.pop();
if(i==0) first = cur_id;
if(i==size-1) last = cur_id;
if(node->left)
q.push({node->left, cur_id*2+1});
if(node->right)
q.push({node->right, cur_id*2+2});
}
ans = max(ans, last-first+1);
}
return ans;
}
};
reorder(root->left);
P a g e | 26
DAARIS AMEEN
reorder(root->right);
int tot = 0;
if(root->left) tot += root->left->data;
if(root->right) tot+= root->right->data;
if(root->left or root->right) root->data = tot;
}
void changeTree(TreeNode* root) {
reorder(root);
}
Nodes at distance K in BT
class Solution {
void markParents(TreeNode* root, unordered_map<TreeNode*,
TreeNode*> &parent_track, TreeNode* target) {
queue<TreeNode*> queue;
queue.push(root);
while(!queue.empty()) {
TreeNode* current = queue.front();
queue.pop();
if(current->left) {
parent_track[current->left] = current;
queue.push(current->left);
}
if(current->right) {
parent_track[current->right] = current;
queue.push(current->right);
}
}
}
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
unordered_map<TreeNode*, TreeNode*> parent_track; // node ->
parent
markParents(root, parent_track, target);
}
if(current->right && !visited[current->right]) {
queue.push(current->right);
visited[current->right] = true;
}
if(parent_track[current] && !
visited[parent_track[current]]) {
queue.push(parent_track[current]);
visited[parent_track[current]] = true;
}
}
}
vector<int> result;
while(!queue.empty()) {
TreeNode* current = queue.front(); queue.pop();
result.push_back(current->val);
}
return result;
}
};
q.push(mpp[node]);
}
}
if(fl) maxi++;
}
return maxi;
}
TreeNode* bfsToMapParents(TreeNode* root, map<TreeNode*, TreeNode*>
&mpp, int start) {
queue<TreeNode*> q;
q.push(root);
TreeNode* res;
while(!q.empty()) {
TreeNode* node = q.front();
if(node->data == start) res = node;
q.pop();
if(node->left) {
mpp[node->left] = node;
q.push(node->left);
}
if(node->right) {
mpp[node->right] = node;
q.push(node->right);
}
}
return res;
}
int timeToBurnTree(TreeNode* root, int start)
{
map<TreeNode*, TreeNode*> mpp;
TreeNode* target = bfsToMapParents(root, mpp, start);
int maxi = findMaxDistance(mpp, target);
return maxi;
}
int lh = findHeightLeft(root);
int rh = findHeightRight(root);
int hght = 0;
while(node) {
hght++;
node = node->left;
}
return hght;
}
int findHeightRight(TreeNode* node) {
int hght = 0;
while(node) {
hght++;
node = node->right;
}
return hght;
}
};
return root;
}
};
P a g e | 30
DAARIS AMEEN
return root;
}
string s ="";
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
TreeNode* curNode = q.front();
q.pop();
if(curNode==NULL) s.append("#,");
P a g e | 31
DAARIS AMEEN
else s.append(to_string(curNode->val)+',');
if(curNode != NULL){
q.push(curNode->left);
q.push(curNode->right);
}
}
return s;
}
if(prev->right == NULL) {
prev->right = cur;
cur = cur->left;
}
else {
prev->right = NULL;
inorder.push_back(cur->val);
cur = cur->right;
}
}
}
return inorder;
}
};
if(prev->right == NULL) {
prev->right = cur;
P a g e | 33
DAARIS AMEEN
preorder.push_back(cur->val);
cur = cur->left;
}
else {
prev->right = NULL;
cur = cur->right;
}
}
}
return preorder;
}
};
flatten(root->right);
flatten(root->left);
root->right = prev;
root->left = NULL;
prev = root;
}
};
// TC - O(N)
// SC - O(N)
// Iterative
class Solution {
public:
void flatten(TreeNode* root) {
if(root == NULL) return;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()) {
TreeNode* cur = st.top();
st.pop();
if(cur->right != NULL) {
st.push(cur->right);
}
if(cur->left != NULL) {
st.push(cur->left);
}
P a g e | 34
DAARIS AMEEN
if(!st.empty()) {
cur->right = st.top();
}
cur->left = NULL;
}
}
};
// TC - O(N)
// SC - O(1)
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode* cur = root;
while (cur)
{
if(cur->left)
{
TreeNode* pre = cur->left;
while(pre->right)
{
pre = pre->right;
}
pre->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
}
cur = cur->right;
}
}
};
BST
Search in BST
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root != NULL && root->val != val){
root = val<root->val? root->left:root->right;
}
return root;
}
};
P a g e | 35
DAARIS AMEEN
Ceil in BST
int findCeil(TreeNode *root, int key){
if (root->data == key) {
ceil = root->data;
return ceil;
}
Floor in BST
int floorInBST(TreeNode * root, int key)
{
int floor = -1;
while (root) {
if (root->val == key) {
floor = root->val;
return floor;
}
{
if (root->right != NULL and root->right->val == key)
{
root->right = helper(root->right);
break;
}
else
root = root->right;
}
else
{
if (root->left != NULL and root->left->val == key)
{
root->left = helper(root->left);
break;
}
else
root = root->left;
}
}
return dummy;
}
TreeNode* right=kthlargest(root->right,k);
if(right!=NULL)
return right;
k--;
if(k==0)
return root;
return kthlargest(root->left,k);
}
TreeNode* left=kthsmallest(root->left,k);
if(left!=NULL)
return left;
k--;
if(k==0)
P a g e | 38
DAARIS AMEEN
return root;
return kthsmallest(root->right,k);
}
Check if BT is BST
bool isValidBST(TreeNode* root) {
return isValidBST(root, INT_MIN, INT_MAX);
}
LCA in BST
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p,
TreeNode* q) {
if(!root) return NULL;
int curr = root->val;
if(curr < p->val && curr < q->val) {
return lowestCommonAncestor(root->right, p, q);
}
if(curr > p->val && curr > q->val) {
return lowestCommonAncestor(root->left, p, q);
}
return root;
}
};
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
TreeNode* successor = NULL;
return successor;
}
};
private:
void pushAll(TreeNode *node) {
for (; node != NULL; myStack.push(node), node = node->left);
}
};
private:
void pushAll(TreeNode *node) {
for(;node != NULL; ) {
myStack.push(node);
if(reverse == true) {
node = node->right;
} else {
node = node->left;
}
}
}
P a g e | 41
DAARIS AMEEN
};
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
if(!root) return false;
BSTIterator l(root, false);
BSTIterator r(root, true);
int i = l.next();
int j = r.next();
while(i<j) {
if(i + j == k) return true;
else if(i + j < k) i = l.next();
else j = r.next();
}
return false;
}
};
inorder(root->left);
inorder(root->right);
}
public:
void recoverTree(TreeNode* root) {
first = middle = last = NULL;
prev = new TreeNode(INT_MIN);
inorder(root);
if(first && last) swap(first->val, last->val);
else if(first && middle) swap(first->val, middle->val);
}
};
class Solution {
private:
NodeValue largestBSTSubtreeHelper(TreeNode* root) {
// An empty tree is a BST of size 0.
if (!root) {
return NodeValue(INT_MAX, INT_MIN, 0);
}
LINKED LIST
Reverse a Linked List
Given the head of a singly linked list, write a program to reverse the linked list, and return
the head pointer to the reversed list.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
//step 1
ListNode* prev_p = NULL;
ListNode* current_p = head;
ListNode* next_p;
//step 2
while(current_p) {
next_p = current_p->next;
current_p->next = prev_p;
prev_p = current_p;
current_p = next_p;
}
if (head == NULL||head->next==NULL)
return head;
head->next->next = head;
head->next = NULL;
return nnode;
}
temp = head;
return temp;
}
};
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
return res;
}
};
while(fast->next != NULL)
{
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return start->next;
P a g e | 47
DAARIS AMEEN
}
};
TC- O(N), SC- O(1)
if(l2 != NULL) {
sum += l2 -> val;
l2 = l2 -> next;
}
sum += carry;
carry = sum / 10;
ListNode *node = new ListNode(sum % 10);
temp -> next = node;
temp = temp -> next;
}
return dummy -> next;
}
};
TC and SC is O(max(M,N))
class node {
P a g e | 48
DAARIS AMEEN
public:
int num;
node* next;
node(int a) {
num = a;
next = NULL;
}
};
//function to insert node at the end of the list
void insertNode(node* &head,int val) {
node* newNode = new node(val);
if(head == NULL) {
head = newNode;
return;
}
node* temp = head;
while(temp->next != NULL) temp = temp->next;
temp->next = newNode;
}
//function to get reference of the node to delete
node* getNode(node* head,int val) {
while(head->num != val) head = head->next;
return head;
}
//delete function as per the question
void deleteNode(node* t) {
t->num = t->next->num;
t->next = t->next->next;
return;
}
//printing the list function
void printList(node* head) {
while(head->next != NULL) {
cout<<head->num<<"->";
head = head->next;
}
cout<<head->num<<"\n";
}
int main() {
node* head = NULL;
//inserting node
insertNode(head,1);
insertNode(head,4);
insertNode(head,2);
insertNode(head,3);
//printing given list
cout<<"Given Linked List:\n";
printList(head);
P a g e | 49
DAARIS AMEEN
node* t = getNode(head,2);
//delete node
deleteNode(t);
//list after deletion operation
cout<<"Linked List after deletion:\n";
printList(head);
return 0;
}
while(head != NULL) {
if(hashTable.find(head) != hashTable.end()) return true;
hashTable.insert(head);
head = head->next;
}
return false;
}
while(length >= k) {
cur = pre->next;
nex = cur->next;
for(int i=1;i<k;i++) {
cur->next = nex->next;
nex->next = pre->next;
pre->next = nex;
nex = cur->next;
}
pre = cur;
length -= k;
}
return dummyHead->next;
}
P a g e | 51
DAARIS AMEEN
while(fast->next!=NULL&&fast->next->next!=NULL) {
slow = slow->next;
fast = fast->next->next;
}
slow->next = reverse(slow->next);
slow = slow->next;
node* dummy = head;
while(slow!=NULL) {
if(dummy->num != slow->num) return false;
dummy = dummy->next;
slow = slow->next;
}
return true;
}
node that the tail’s next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note
that pos is not passed as a parameter.
Do not modify the linked list.
node* detectCycle(node* head) {
unordered_set<node*> st;
while(head != NULL) {
if(st.find(head) != st.end()) return head;
st.insert(head);
head = head->next;
}
return NULL;
}
if(slow == fast) {
while(slow != entry) {
slow = slow->next;
entry = entry->next;
}
return slow;
}
}
return NULL;
}
Note: The flattened list will be printed using the bottom pointer instead of the next pointer.
if(a) temp->bottom = a;
else temp->bottom = b;
}
Node *flatten(Node *root)
{
return root;
// now merge
root = mergeTwoLists(root, root->next);
return head;
}
P a g e | 55
DAARIS AMEEN
BINARY SEARCH
BS on Reverse sorted array
#include<bits/stdc++.h>
using namespace std;
int solve()
{
int n,target; cin>>n>>target;
vector<int>nums(n);
for(int i=0;i<n;i++)
cin>>nums[i];
int solve()
{
int n,target; cin>>n>>target;
vector<int>nums(n);
for(int i=0;i<n;i++)
cin>>nums[i];
if(order==0)
{
while(start<=end)
{
int mid = (end-start)/2 + start;
if(nums[i]==mid)
return mid;
if(nums[i]>target)
start=mid+1;
else
end=mid-1;
}
}
else
{
while(start<=end)
{
int mid = (end-start)/2 + start;
if(nums[i]==mid)
return mid;
if(nums[i]>target)
end=mid-1;
else
start=mid+1;
}
}
return -1;
}
{
if(nums[mid]==target)
last=mid;
start=mid+1;
}
else
end=mid-1;
}
if(first==-1 || last==-1)
return 0;
else
return last-first+1;
}
P a g e | 58
DAARIS AMEEN
}
return -1;
}
return 0;
}
}
return -1;
}
char z = letters[0];
while (start <= end)
{
int mid = (end - start) / 2 + start;
if (letters[mid] > target)
{
z = letters[mid];
end = mid - 1;
}
else
start = mid + 1;
}
return z;
}
}
end = start;
start /= 2;
start = 0, end = n - 1;
while (start <= end)
{
int mid = (end - start) / 2 + start;
if (nums[mid] <= target)
{
ceil_ele = nums[mid];
start = mid + 1;
}
else
end = mid - 1;
}
P a g e | 63
DAARIS AMEEN
BS on Answer concept
Binary Search on answer concept - BSA
1. Applicable on unsorted array.
2. criteria is needed to check whether mid is the answer.
3. criteria is needed to move the array left of right.
Peak Element
// Binary Search on answer concept - BSA
// 1. Applicable on unsorted array.
// 2. criteria is needed to check whether mid is the answer.
// 3. criteria is needed to move the array left of right.
class Solution
{
public:
int findPeakElement(vector<int> &nums)
{
int n = nums.size(), start = 0, end = n - 1;
if (n == 1)
return 0;
while (start <= end)
{
int mid = (end - start) / 2 + start;
if (mid > 0 and mid < n - 1)
{
if (nums[mid] > nums[mid - 1] and nums[mid] >
nums[mid + 1])
return mid;
else if (nums[mid + 1] > nums[mid - 1])
start = mid + 1;
else
end = mid - 1;
}
if (mid == 0)
{
if (nums[mid] > nums[mid + 1])
return mid;
else
return mid + 1;
}
if (mid == n - 1)
{
if (nums[mid] > nums[mid - 1])
return mid;
else
return mid - 1;
P a g e | 64
DAARIS AMEEN
}
}
return -1;
}
};
return -1;
}
A.size());
// cout<<maximum_bitonic_array;
int start = 0, end = maximum_bitonic_array - 1;
while (start <= end)
{
int mid = (end - start) / 2 + start;
if (A[mid] == B)
return mid;
if (A[mid] > B)
end = mid - 1;
else
start = mid + 1;
}
#include <bits/stdc++.h>
using namespace std;
// update curr_sum
curr_sum = arr[i];
if (n < m)
return -1;
else
// if not possible means pages should be
// increased so update start = mid + 1
start = mid + 1;
}
// Drivers code
int main()
{
// Number of pages in books
int arr[] = { 12, 34, 67, 90 };
int n = sizeof arr / sizeof arr[0];
int m = 2; // No. of students
}
int main() {
int n=3, m=27;
getNthRoot(n, m);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int desired = (r * c + 1) / 2;
while (min < max)
{
int mid = min + (max - min) / 2;
int place = 0;
if (mid % 2 == 0) {
if (nums[mid] != nums[mid + 1])
//Checking whether we are in right half
return nums[low];
}
};
int main() {
Solution obj;
vector < int > v {1,1,2,3,3,4,4,8,8
};
}
P a g e | 72
DAARIS AMEEN
int low=0,high=m,medianPos=((m+n)+1)/2;
while(low<=high) {
int cut1 = (low+high)>>1;
int cut2 = medianPos - cut1;
int main() {
int nums1[] = {1,4,7,10,12};
int nums2[] = {2,3,6,15};
int m = sizeof(nums1)/sizeof(nums1[0]);
int n = sizeof(nums2)/sizeof(nums2[0]);
cout<<"The Median of two sorted arrays is"<<fixed<<setprecision(5)
<<median(nums1,nums2,m,n);
return 0;
}
P a g e | 73
DAARIS AMEEN
Aggressive Cows
There is a new barn with N stalls and C cows. The stalls are located on a straight line at
positions x1,….,xN (0 <= xi <= 1,000,000,000). We want to assign the cows to the stalls,
such that the minimum distance between any two of them is as large as possible. What is
the largest minimum distance?
Input: No of stalls = 5 Array: {1,2,8,4,9} And number of cows: 3
Output: One integer, the largest minimum distance 3
#include <bits/stdc++.h>
return 0;
}
TC : O(N*log(M))
SC: O(1)
P a g e | 75
DAARIS AMEEN
int main() {
vector < int > arr{3,1,2};
Solution ob;
vector < int > ans = ob.subsetSums(arr, arr.size());
sort(ans.begin(), ans.end());
cout<<"The sum of each subset is "<<endl;
for (auto sum: ans) {
cout << sum << " ";
}
cout << endl;
return 0;
}
Output:
Time Complexity: O(2^n)+O(2^n log(2^n)). Each index has two ways. You
can either pick it up or not pick it. So for n index time complexity
P a g e | 76
DAARIS AMEEN
Space Complexity: O(2^n) for storing subset sums, since 2^n subsets
can be generated for an array of size n.
return 0;
}
Output:
Combination Sum – 1
Given an array of distinct integers and a target, you have to return the list of all unique
combinations where the chosen numbers sum to target. You may return the combinations
in any order.
The same number may be chosen from the given array an unlimited number of times. Two
combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than
150 combinations for the given input.
#include<bits/stdc++.h>
}
public:
P a g e | 78
DAARIS AMEEN
vector < vector < int >> combinationSum(vector < int > &
candidates, int target) {
vector < vector < int >> ans;
vector < int > ds;
findCombination(0, target, candidates, ans, ds);
return ans;
}
};
int main() {
Solution obj;
vector < int > v {2,3,6,7};
int target = 7;
Combinations are:
2 2 3
7
#include<bits/stdc++.h>
[ [ 1 1 6 ][ 1 2 5 ][ 1 7 ][ 2 6 ] ]
Time Complexity:O(2^n*k)
Reason: Assume if all the elements in the array are unique then the
no. of subsequence you will get will be O(2^n). we also add the ds to
our ans when we reach the base case that will take “k”//average space
for the ds.
Space Complexity:O(k*x)
P a g e | 80
DAARIS AMEEN
Palindrome Partitioning
You are given a string s, partition it in such a way that every substring is a palindrome.
Return all such palindromic partitions of s.
#include <bits/stdc++.h>
class Solution {
public:
vector < vector < string >> partition(string s) {
vector < vector < string > > res;
vector < string > path;
func(0, s, path, res);
return res;
}
void func(int index, string s, vector < string > & path,
vector < vector < string > > & res) {
if (index == s.size()) {
res.push_back(path);
return;
}
for (int i = index; i < s.size(); ++i) {
if (isPalindrome(s, index, i)) {
path.push_back(s.substr(index, i - index + 1));
func(i + 1, s, path, res);
path.pop_back();
}
}
}
return 0;
}
Output:
Reason: The space complexity can vary depending upon the length of the
answer. k is the average length of the list of palindromes and if we
have x such list of palindromes in our final answer. The depth of the
recursion tree is n, so the auxiliary space required is equal to the
O(n).
Note: 1<=K<=N!
Hence for a given input its Kth permutation always exists
#include <bits/stdc++.h>
class Solution {
public:
string getPermutation(int n, int k) {
int fact = 1;
vector < int > numbers;
for (int i = 1; i < n; i++) {
fact = fact * i;
numbers.push_back(i);
}
numbers.push_back(n);
string ans = "";
k = k - 1;
while (true) {
ans = ans + to_string(numbers[k / fact]);
numbers.erase(numbers.begin() + k / fact);
if (numbers.size() == 0) {
P a g e | 83
DAARIS AMEEN
break;
}
k = k % fact;
fact = fact / numbers.size();
}
return ans;
}
};
int main() {
int n = 3, k = 3;
Solution obj;
string ans = obj.getPermutation(n, k);
cout << "The Kth permutation sequence is " << ans << endl;
return 0;
}
Output:
ds.push_back(nums[i]);
freq[i] = 1;
recurPermute(ds, nums, ans, freq);
freq[i] = 0;
ds.pop_back();
}
}
}
public:
vector < vector < int >> permute(vector < int > & nums) {
vector < vector < int >> ans;
vector < int > ds;
int freq[nums.size()];
for (int i = 0; i < nums.size(); i++) freq[i] = 0;
recurPermute(ds, nums, ans, freq);
return ans;
}
};
int main() {
Solution obj;
vector<int> v{1,2,3};
vector < vector < int >> sum = obj.permute(v);
cout << "All Permutations are " << endl;
for (int i = 0; i < sum.size(); i++) {
for (int j = 0; j < sum[i].size(); j++)
cout << sum[i][j] << " ";
cout << endl;
}
}
Time Complexity: N! x N
#include<bits/stdc++.h>
swap(nums[index], nums[i]);
recurPermute(index + 1, nums, ans);
swap(nums[index], nums[i]);
}
}
public:
vector < vector < int >> permute(vector < int > & nums) {
vector < vector < int >> ans;
recurPermute(0, nums, ans);
return ans;
}
};
int main() {
Solution obj;
vector < int > v {1,2,3};
vector < vector < int >> sum = obj.permute(v);
cout << "All Permutations are" << endl;
for (int i = 0; i < sum.size(); i++) {
for (int j = 0; j < sum[i].size(); j++)
cout << sum[i][j] << " ";
cout << endl;
}
}
col--;
}
col = dupcol;
row = duprow;
while (col >= 0) {
if (board[row][col] == 'Q')
return false;
col--;
}
row = duprow;
col = dupcol;
while (row < n && col >= 0) {
if (board[row][col] == 'Q')
return false;
row++;
col--;
}
return true;
}
public:
void solve(int col, vector < string > & board, vector < vector <
string >> & ans, int n) {
if (col == n) {
ans.push_back(board);
return;
}
for (int row = 0; row < n; row++) {
if (isSafe1(row, col, board, n)) {
board[row][col] = 'Q';
solve(col + 1, board, ans, n);
board[row][col] = '.';
}
}
}
public:
vector < vector < string >> solveNQueens(int n) {
vector < vector < string >> ans;
vector < string > board(n);
string s(n, '.');
for (int i = 0; i < n; i++) {
board[i] = s;
}
solve(0, board, ans, n);
return ans;
}
};
P a g e | 87
DAARIS AMEEN
int main() {
int n = 4; // we are taking 4*4 grid and 4 queens
Solution obj;
vector < vector < string >> ans = obj.solveNQueens(n);
for (int i = 0; i < ans.size(); i++) {
cout << "Arrangement " << i + 1 << "\n";
for (int j = 0; j < ans[0].size(); j++) {
cout << ans[i][j];
cout << endl;
}
cout << endl;
}
return 0;
}
(N! * N) nearly.
_______________________________
class Solution {
public:
void solve(int col, vector < string > & board, vector < vector <
string >> & ans, vector < int > & leftrow, vector < int > &
upperDiagonal, vector < int > & lowerDiagonal, int n) {
if (col == n) {
ans.push_back(board);
return;
}
for (int row = 0; row < n; row++) {
if (leftrow[row] == 0 && lowerDiagonal[row + col] == 0 &&
upperDiagonal[n - 1 + col - row] == 0) {
board[row][col] = 'Q';
leftrow[row] = 1;
lowerDiagonal[row + col] = 1;
upperDiagonal[n - 1 + col - row] = 1;
solve(col + 1, board, ans, leftrow, upperDiagonal,
lowerDiagonal, n);
board[row][col] = '.';
leftrow[row] = 0;
lowerDiagonal[row + col] = 0;
upperDiagonal[n - 1 + col - row] = 0;
P a g e | 88
DAARIS AMEEN
}
}
}
public:
vector < vector < string >> solveNQueens(int n) {
vector < vector < string >> ans;
vector < string > board(n);
string s(n, '.');
for (int i = 0; i < n; i++) {
board[i] = s;
}
vector < int > leftrow(n, 0), upperDiagonal(2 * n - 1, 0),
lowerDiagonal(2 * n - 1, 0);
solve(0, board, ans, leftrow, upperDiagonal, lowerDiagonal, n);
return ans;
}
};
int main() {
int n = 4; // we are taking 4*4 grid and 4 queens
Solution obj;
vector < vector < string >> ans = obj.solveNQueens(n);
for (int i = 0; i < ans.size(); i++) {
cout << "Arrangement " << i + 1 << "\n";
for (int j = 0; j < ans[0].size(); j++) {
cout << ans[i][j];
cout << endl;
}
cout << endl;
}
return 0;
}
Sudoku Solver
Given a 9×9 incomplete sudoku, solve it such that it becomes valid sudoku. Valid sudoku
has the following properties.
1. All the rows should be filled with numbers(1 – 9) exactly
once.
#include <vector>
bool isValid(vector < vector < char >> & board, int row, int col, char
c) {
for (int i = 0; i < 9; i++) {
if (board[i][col] == c)
return false;
if (board[row][i] == c)
return false;
if (solve(board))
return true;
else
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
int main() {
vector<vector<char>>board{
{'9', '5', '7', '.', '1', '3', '.', '8', '4'},
P a g e | 90
DAARIS AMEEN
solve(board);
Time Complexity: O(9(n ^ 2)), in the worst case, for each cell in the
n2 board, we have 9 possible numbers.
Space Complexity: O(1), since we are refilling the given board itself,
there is no extra space required, so constant space complexity.
M – Coloring Problem
Given an undirected graph and a number m, determine if the graph can be colored with at
most m colors such that no two adjacent vertices of the graph are colored with the same
color.
Example 1: Input:
1. N=4
2. M=3
3. E=5
Edges[] = { (0, 1), (1, 2), (2, 3), (3, 0), (0, 2) }
Output: 1
Explanation: It is possible to colour the given graph using 3 colours.
#include<bits/stdc++.h>
return false;
}
}
return true;
}
bool solve(int node, int color[], int m, int N, bool graph[101][101])
{
if (node == N) {
return true;
}
}
return false;
}
int main() {
int N = 4;
int m = 3;
bool graph[101][101] = {
(0, 1),
(1, 2),
(2, 3),
(3, 0),
(0, 2)
};
cout << graphColoring(graph, m, N);
}
P a g e | 92
DAARIS AMEEN
Rat in a Maze
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the
destination at (N – 1, N – 1). Find all possible paths that the rat can take to reach from
source to destination. The directions in which the rat can move are ‘U'(up), ‘D'(down), ‘L’
(left), ‘R’ (right). Value 0 at a cell in the matrix represents that it is blocked and the rat
cannot move to it while value 1 at a cell in the matrix represents that rat can travel through
it.
Note: In a path, no cell can be visited more than one time.
Print the answer in lexicographical(sorted) order
Input: N = 4
m[][] = {{1, 0, 0, 0}, {1, 1, 0, 1}, {1, 1, 0, 0}, {0, 1, 1, 1}}
Output: DDRDRR DRDDRR
#include <bits/stdc++.h>
class Solution {
void solve(int i, int j, vector < vector < int >> & a, int n, vector
< string > & ans, string move,
vector < vector < int >> & vis) {
if (i == n - 1 && j == n - 1) {
ans.push_back(move);
return;
}
// downward
if (i + 1 < n && !vis[i + 1][j] && a[i + 1][j] == 1) {
vis[i][j] = 1;
solve(i + 1, j, a, n, ans, move + 'D', vis);
vis[i][j] = 0;
}
// left
if (j - 1 >= 0 && !vis[i][j - 1] && a[i][j - 1] == 1) {
vis[i][j] = 1;
solve(i, j - 1, a, n, ans, move + 'L', vis);
vis[i][j] = 0;
}
P a g e | 93
DAARIS AMEEN
// right
if (j + 1 < n && !vis[i][j + 1] && a[i][j + 1] == 1) {
vis[i][j] = 1;
solve(i, j + 1, a, n, ans, move + 'R', vis);
vis[i][j] = 0;
}
// upward
if (i - 1 >= 0 && !vis[i - 1][j] && a[i - 1][j] == 1) {
vis[i][j] = 1;
solve(i - 1, j, a, n, ans, move + 'U', vis);
vis[i][j] = 0;
}
}
public:
vector < string > findPath(vector < vector < int >> & m, int n) {
vector < string > ans;
vector < vector < int >> vis(n, vector < int > (n, 0));
int main() {
int n = 4;
Solution obj;
vector < string > result = obj.findPath(m, n);
if (result.size() == 0)
cout << -1;
else
for (int i = 0; i < result.size(); i++) cout << result[i] << " ";
cout << endl;
return 0;
}
Word Break I
Given an input string and a dictionary of words, find out if the input string can be
segmented into a space-separated sequence of dictionary words.
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice, cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string can be segmented as "i like".
RECURSION---
#include <iostream>
using namespace std;
// Base case
if (size == 0) return true;
return false;
}
P a g e | 95
DAARIS AMEEN
int main()
{
wordBreak("ilikesamsung")? cout <<"Yes\n": cout << "No\n";
return 0;
}
#include <unordered_set>
using namespace std;
/*
Start exploring the sentence from the index until we wouldn't
find 'j' such that substring [index,j] exists in the dictionary as a
word.
P a g e | 96
DAARIS AMEEN
*/
for (int j = idx; j < size; j++)
{
word.push_back(s[j]);
if (dictSet.count(word) == 0)
{
continue;
}
GRAPHS
P a g e | 98
DAARIS AMEEN
P a g e | 99
DAARIS AMEEN
P a g e | 100
DAARIS AMEEN
P a g e | 101
DAARIS AMEEN
P a g e | 102
DAARIS AMEEN
P a g e | 103
DAARIS AMEEN
P a g e | 104
DAARIS AMEEN
P a g e | 105
DAARIS AMEEN
P a g e | 106
DAARIS AMEEN
P a g e | 107
DAARIS AMEEN
P a g e | 108
DAARIS AMEEN
P a g e | 109
DAARIS AMEEN
P a g e | 110
DAARIS AMEEN
P a g e | 111
DAARIS AMEEN
P a g e | 112
DAARIS AMEEN
P a g e | 113
DAARIS AMEEN
return ans;
}
{
while (s.size() > 0 and s.top() < arr[i])
{
s.pop();
}
if (s.size() == 0)
ans.push_back(-1);
else
ans.push_back(s.top());
}
s.push(arr[i]);
}
reverse(ans.begin(), ans.end());
return ans;
}
stack<int> s;
vector<int> ans;
for (int i = n - 1; i >= 0; i--)
{
if (s.size() == 0)
ans.push_back(-1);
vector<int> ans;
for (int i = 0; i < n; i++)
{
if (s.size() == 0)
ans.push_back(i + 1);
else if (s.size() > 0 and s.top().first > price[i])
ans.push_back(i - s.top().second);
else if (s.size() > 0 and s.top().first <= price[i])
{
while (s.size() > 0 and s.top().first <= price[i])
{
s.pop();
}
if (s.size() == 0)
ans.push_back(i + 1);
else
ans.push_back(i - s.top().second);
P a g e | 116
DAARIS AMEEN
}
s.push({ price[i],
i });
}
return ans;
}
else
ansr.push_back(sr.top().second);
}
sr.push({ heights[i],
i });
}
reverse(ansr.begin(), ansr.end());
ansr.push_back(n);
if (sr.size() > 0 and sr.top().first < height[i])
ansr.push_back(sr.top().second);
else if (sr.size() > 0 and sr.top().first >=
height[i])
{
while (sr.size() > 0 and sr.top().first >=
height[i])
{
sr.pop();
}
if (sr.size() == 0)
ansr.push_back(n);
else
ansr.push_back(sr.top().second);
}
sr.push({ height[i],
i });
}
reverse(ansr.begin(), ansr.end());
int res = 0;
for (int i = 0; i < n; i++)
{
res = max(res, height[i] *((i - ansl[i]) + (ansr[i] -
i) - 1));
}
return res;
}
int maximalRectangle(vector<vector < char>> &matrix)
{
int m = matrix.size(), n = matrix[0].size();
vector<int> histogram(n, 0);
int result = 0;
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[0].size(); j++)
{
if (matrix[i][j] == '1')
histogram[j] += 1;
else
histogram[j] = 0;
}
result = max(result, max_rectangle_histogram(histogram));
}
return result;
}
P a g e | 119
DAARIS AMEEN
vector<int> res;
ansr.push_back(sr.top());
}
if (sr.size() > 0 and sr.top() > height[i])
continue;
else
sr.push(height[i]);
}
reverse(ansr.begin(), ansr.end());
int ans = 0;
MinStack()
{}
if (ss.size() == 0)
{
ss.push(val);
}
else if (ss.top() >= val)
{
ss.push(val);
}
}
void pop()
{
if (ss.top() == s.top())
ss.pop();
s.pop();
}
P a g e | 121
DAARIS AMEEN
int top()
{
int a = s.top();
// cout<<a;
return a;
}
int getMin()
{
int a = ss.top();
return a;
}
};
MinStack() {}
void pop() {
s.pop();
}
int top() {
return s.top().first;
}
int getMin() {
return s.top().second;
}
};
P a g e | 122
DAARIS AMEEN
// Driver code
int main()
{
Stack* s=new Stack();
s->push(1);
s->push(2);
s->push(3);
while(!s->isEmpty()){
cout<<s->top()<<endl;
s->pop();
}
}
Celebrity Problem
A celebrity is a person who is known to all but does not know anyone at a party. If you go to
a party of N people, find if there is a celebrity in the party or not.
A square NxN matrix M[][] is used to represent people at the party such that if an element
of row i and column j is set to 1 it means ith person knows jth person. Here M[i][i] will
always be 0.
Note: Follow 0 based indexing.
// C++ program to find celebrity - GRAPH APPROACH
#include <bits/stdc++.h>
#include <list>
using namespace std;
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
int findCelebrity(int n)
{
P a g e | 124
DAARIS AMEEN
//degree array;
int indegree[n]={0},outdegree[n]={0};
return -1;
}
// Driver code
int main()
{
int n = 4;
int id = findCelebrity(n);
id == -1 ? cout << "No celebrity" :
cout << "Celebrity ID " << id;
return 0;
}
// if there is no celebrity
return -1;
}
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
// a wrapper over findCelebrity
int Celebrity(int n)
P a g e | 126
DAARIS AMEEN
{
// find the celebrity
int id = findPotentialCelebrity(n);
return -1;
}
}
// Driver code
int main()
{
int n = 4;
int id = Celebrity(n);
id == -1 ? cout << "No celebrity"
: cout << "Celebrity ID " << id;
return 0;
}
else {
if (!st.empty()) {
if (s[st.top()] == '(') st.pop();
else st.push(i);
}
else st.push(i);
}
}
if (st.empty()) longest = n;
else {
int a = n, b = 0;
while (!st.empty()) {
b = st.top(); st.pop();
longest = max(longest, a-b-1);
a = b;
}
longest = max(longest, a);
}
return longest;
}
};
Iterative TOH
The tower of Hanoi is a famous puzzle where we have three rods and N disks. The objective
of the puzzle is to move the entire stack to another rod. You are given the number of discs
N. Initially, these discs are in the rod 1. You need to print all the steps of discs movement so
that all the discs reach the 3rd rod. Also, you need to find the total moves.
Note: The discs are arranged such that the top disc is numbered 1 and the bottom-most
disc is numbered N. Also, all the discs have different sizes and a bigger disc cannot be put
on the top of a smaller disc. Refer the provided link to get a better clarity about the puzzle.
Input:
N=2
Output:
move disk 1 from rod 1 to rod 2
move disk 2 from rod 1 to rod 3
move disk 1 from rod 2 to rod 3
3
Explanation: For N=2 , steps will be
as follows in the example and total
3 steps will be taken.
P a g e | 128
DAARIS AMEEN
// Driver code
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}
else if (i % 3 == 2)
moveDisksBetweenTwoPoles(src, aux, s, a);
else if (i % 3 == 0)
moveDisksBetweenTwoPoles(aux, dest, a, d);
}
}
// Driver Program
int main()
{
if(s.size()==0)
{
P a g e | 132
DAARIS AMEEN
s.push(val);
min = val;
}
else if(val>=min)
{
s.push(val);
}
else
{
long long int p = 2*(long long)val-min;
s.push(p);
min = val;
}
}
void pop() {
if(s.size()==0) return;
else
{
if(s.top()>=min)
{
s.pop();
}
else
{
int ov = min;
min = 2*min-s.top();
s.pop();
}
}
}
int top() {
if(s.size()==0) return -1;
else
{
if(s.top()>=min)
{
return s.top();
}
P a g e | 133
DAARIS AMEEN
else
{
return min;
}
}
}
int getMin() {
return min;
}
Stack s;
s.push(6);
s.push(3);
s.push(7);
cout << "Top of stack is before deleting any element " << s.Top() <<
endl;
P a g e | 134
DAARIS AMEEN
cout << "Size of stack before deleting any element " << s.Size() <<
endl;
cout << "The element deleted is " << s.pop() << endl;
cout << "Size of stack after deleting an element " << s.Size() <<
endl;
cout << "Top of stack after deleting an element " << s.Top() <<
endl;
return 0;
}
Queue(int maxSize) {
( * this).maxSize = maxSize;
arr = new int[maxSize];
start = -1;
end = -1;
currSize = 0;
}
void push(int newElement) {
if (currSize == maxSize) {
cout << "Queue is full\nExiting..." << endl;
exit(1);
}
if (end == -1) {
start = 0;
end = 0;
} else
end = (end + 1) % maxSize;
arr[end] = newElement;
cout << "The element pushed is " << newElement << endl;
currSize++;
}
int pop() {
if (start == -1) {
cout << "Queue Empty\nExiting..." << endl;
}
P a g e | 135
DAARIS AMEEN
};
int main() {
Queue q(6);
q.push(4);
q.push(14);
q.push(24);
q.push(34);
cout << "The peek of the queue before deleting any element " <<
q.top() << endl;
cout << "The size of the queue before deletion " << q.size() <<
endl;
cout << "The first element to be deleted " << q.pop() << endl;
cout << "The peek of the queue after deleting an element " <<
q.top() << endl;
cout << "The size of the queue after deleting an element " <<
q.size() << endl;
return 0;
}
class Stack {
queue < int > q;
public:
void Push(int x) {
P a g e | 136
DAARIS AMEEN
int s = q.size();
q.push(x);
for (int i = 0; i < s; i++) {
q.push(q.front());
q.pop();
}
}
int Pop() {
int n = q.front();
q.pop();
return n;
}
int Top() {
return q.front();
}
int Size() {
return q.size();
}
};
int main() {
Stack s;
s.Push(3);
s.Push(2);
s.Push(4);
s.Push(1);
cout << "Top of the stack: " << s.Top() << endl;
cout << "Size of the stack before removing element: " << s.Size() <<
endl;
cout << "The deleted element is: " << s.Pop() << endl;
cout << "Top of the stack after removing element: " << s.Top() <<
endl;
cout << "Size of the stack after removing element: " << s.Size();
struct Queue {
stack < int > input, output;
input.pop();
}
// Insert the desired element in the stack input
cout << "The element pushed is " << data << endl;
input.push(data);
// Pop out elements from the stack output and push them into the
stack input
while (!output.empty()) {
input.push(output.top());
output.pop();
}
}
// Pop the element from the Queue
int Pop() {
if (input.empty()) {
cout << "Stack is empty";
exit(0);
}
int val = input.top();
input.pop();
return val;
}
// Return the Topmost element from the Queue
int Top() {
if (input.empty()) {
cout << "Stack is empty";
exit(0);
}
return input.top();
}
// Return the size of the Queue
int size() {
return input.size();
}
};
int main() {
Queue q;
q.Push(3);
q.Push(4);
cout << "The element poped is " << q.Pop() << endl;
q.Push(5);
cout << "The top of the queue is " << q.Top() << endl;
cout << "The size of the queue is " << q.size() << endl;
}
#include <bits/stdc++.h>
P a g e | 138
DAARIS AMEEN
class MyQueue {
public:
stack < int > input, output;
/** Initialize your data structure here. */
MyQueue() {
/** Removes the element from in front of queue and returns that
element. */
int pop() {
// shift input to output
if (output.empty())
while (input.size())
output.push(input.top()), input.pop();
int x = output.top();
output.pop();
return x;
}
int size() {
return (output.size() + input.size());
}
};
int main() {
MyQueue q;
q.push(3);
q.push(4);
cout << "The element poped is " << q.pop() << endl;
q.push(5);
P a g e | 139
DAARIS AMEEN
cout << "The top of the queue is " << q.top() << endl;
cout << "The size of the queue is " << q.size() << endl;
Sort a Stack
// C++ program to sort a stack using recursion
#include <iostream>
using namespace std;
if (p == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
return;
}
p->data = x;
p->next = *s;
*s = p;
}
x = (*s)->data;
temp = *s;
(*s) = (*s)->next;
free(temp);
return x;
}
// Driver code
int main(void)
{
struct stack* top;
initStack(&top);
push(&top, 30);
push(&top, -5);
push(&top, 18);
push(&top, 14);
push(&top, -3);
sortStack(&top);
cout << "\n";
return 0;
}
int cap;
unordered_map < int, node * > m;
LRUCache(int capacity) {
P a g e | 143
DAARIS AMEEN
cap = capacity;
head -> next = tail;
tail -> prev = head;
}
return -1;
}
LFU Cache
Implement the LFUCache class:
1. LFUCache(int capacity) Initializes the object with the capacity of the data structure.
2. int get(int key) Gets the value of the key if the key exists in the cache. Otherwise,
returns -1.
3. void put(int key, int value) Update the value of the key if present, or inserts the key
if not already present. When the cache reaches its capacity, it should invalidate and
remove the least frequently used key before inserting a new item. For this problem,
when there is a tie (i.e., two or more keys with the same frequency), the least
recently used key would be invalidated.
To determine the least frequently used key, a use counter is maintained for each key in the
cache. The key with the smallest use counter is the least frequently used key.
When a key is first inserted into the cache, its use counter is set to 1 (due to the put
operation). The use counter for a key in the cache is incremented either a get or put
operation is called on it.
The functions get and put must each run in O(1) average time complexity.
class LFUCache {
int cap;
int size;
int minFreq;
unordered_map<int, pair<int, int>> m; //key to {value,freq};
unordered_map<int, list<int>::iterator> mIter; //key to list
iterator;
unordered_map<int, list<int>> fm; //freq to key list;
public:
LFUCache(int capacity) {
cap=capacity;
size=0;
}
fm[m[key].second].erase(mIter[key]);
m[key].second++;
fm[m[key].second].push_back(key);
mIter[key]=--fm[m[key].second].end();
if(fm[minFreq].size()==0 )
minFreq++;
return m[key].first;
}
P a g e | 145
DAARIS AMEEN
int storedValue=get(key);
if(storedValue!=-1)
{
m[key].first=value;
return;
}
if(size>=cap )
{
m.erase( fm[minFreq].front() );
mIter.erase( fm[minFreq].front() );
fm[minFreq].pop_front();
size--;
}
m[key]={value, 1};
fm[1].push_back(key);
mIter[key]=--fm[1].end();
minFreq=1;
size++;
}
};
if(grid[i][j] != 0) tot++;
if(grid[i][j] == 2) rotten.push({i, j});
}
}
while(!rotten.empty()){
int k = rotten.size();
cnt += k;
while(k--){
int x = rotten.front().first, y =
rotten.front().second;
rotten.pop();
for(int i = 0; i < 4; ++i){
int nx = x + dx[i], ny = y + dy[i];
if(nx < 0 || ny < 0 || nx >= m || ny >= n ||
grid[nx][ny] != 1) continue;
grid[nx][ny] = 2;
rotten.push({nx, ny});
}
}
if(!rotten.empty()) days++;
}
int main()
{
vector<vector<int>> v{ {2,1,1} , {1,1,0} , {0,1,1} } ;
int rotting = orangesRotting(v);
cout<<"Minimum Number of Minutes Required "<<rotting<<endl;
Time Complexity: O ( n x n ) x 4
Space Complexity: O ( n x n )
P a g e | 147
DAARIS AMEEN
DYNAMIC PROGRAMMING
0-1 KNAPSACK
knapsack_recursive.cpp
#include <bits/stdc++.h>
// recursive cases
if (wt[n - 1] <= W) {
return max(val[n - 1] + Knapsack(wt, val, W - wt[n - 1], n
- 1),
Knapsack(wt, val, W, n - 1));
}
else if (wt[n - 1] > W)
return Knapsack(wt, val, W, n - 1);
else
return -1; // to avoid warning
}
signed main() {
int n; cin >> n; // number of items
int val[n], wt[n]; // values and wts array
for (int i = 0; i < n; i++)
cin >> wt[i];
for (int i = 0; i < n; i++)
cin >> val[i];
int W; cin >> W; // Knappsack capacity
knapsack_memoization.cpp
#include <bits/stdc++.h>
using namespace std;
if (n == 0 || W == 0)
return 0;
// if already calculated
if (t[n][W] != -1)
return t[n][W];
// else calculate
else {
if (wt[n - 1] <= W)
t[n][W] = max(val[n - 1] + Knapsack(wt, val, W - wt[n
- 1], n - 1),
Knapsack(wt, val, W, n - 1));
else if (wt[n - 1] > W)
t[n][W] = Knapsack(wt, val, W, n - 1);
return t[n][W];
}
}
signed main() {
int n; cin >> n; // number of items
int val[n], wt[n]; // values and wts array
for (int i = 0; i < n; i++)
cin >> wt[i];
for (int i = 0; i < n; i++)
cin >> val[i];
int W; cin >> W; // capacity
// matrix initialization
for (int i = 0; i <= n; i++)
for (int j = 0; j <= W; j++)
t[i][j] = -1;
knapsack_top_down_dp.cpp
#include <bits/stdc++.h>
using namespace std;
bag
int val1 = val[i - 1] + t[i - 1][j - wt[i - 1]];
// take current wt
int val2 = t[i - 1][j]; // skip current wt
t[i][j] = max(val1, val2);
}
else if (wt[i - 1] > j) // current wt doesn't fit in
bag
t[i][j] = t[i - 1][j];
}
}
return t[n][W];
}
signed main() {
int n; cin >> n; // number of items
int val[n], wt[n]; // values and wts array
for (int i = 0; i < n; i++)
cin >> wt[i];
for (int i = 0; i < n; i++)
cin >> val[i];
int W; cin >> W; // capacity
subset_sum_problem_dp.cpp
// Subset Sum problem
#include <bits/stdc++.h>
using namespace std;
return t[n][sum];
}
signed main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
int sum; cin >> sum;
equal_sum_partition_problem.cpp
// Equal sum Partition Problem
#include <bits/stdc++.h>
using namespace std;
return t[n][sum];
}
signed main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
count_of_subsets_with_given_sum.cpp
// Count of Subsets with given Sum
#include <bits/stdc++.h>
using namespace std;
[j];
else
t[i][j] = t[i - 1][j];
}
}
return t[n][sum];
}
signed main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
int sum; cin >> sum;
#include <bits/stdc++.h>
using namespace std;
elements
for (int j = 0; j <= sum; j++)
if (t[n][j] == true)
v.push_back(j);
return v;
}
return mn;
}
signed main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
count_of_subset_with_given_diff.cpp
// Count of Subsets with given Sum
#include <bits/stdc++.h>
using namespace std;
return t[n][sum];
}
if ((sumOfArray + diff) % 2 != 0)
return 0;
else
return CountSubsetsWithSum(arr, n, (sumOfArray + diff) /
2);
}
signed main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
int diff; cin >> diff;
target sum
// Target Sum
#include <bits/stdc++.h>
using namespace std;
if (i == 0 && j > 0)
t[i][j] = 0;
if (j == 0 && i > 0) {
if (arr[i - 1] == 0) {
t[i][j] = pow(2, k);
k++;
}
else
t[i][j] = t[i - 1][j];
}
}
}
return t[n][sum];
}
if ((sumOfArray + diff) % 2 != 0)
return 0;
else
return CountSubsetsWithSum(arr, n, (sumOfArray + diff) /
2);
}
signed main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
int sum; cin >> sum;
UNBOUNDED KNAPSACK
P a g e | 156
DAARIS AMEEN
rod_cutting_problem.cpp
// Rod Cutting Problem
#include <bits/stdc++.h>
using namespace std;
return dp[n][L];
}
signed main() {
int n; cin >> n;
int length[n], price[n];
for (int i = 0; i < n; i++)
cin >> length[i];
for (int i = 0; i < n; i++)
cin >> price[i];
int L; cin >> L;
coin_change_max_ways.cpp
// Unbounded Knapsack -> Coin Change - I (max number of ways)
#include <bits/stdc++.h>
using namespace std;
return t[n][sum];
}
signed main() {
int n; cin >> n;
int coins[n];
for (int i = 0; i < n; i++)
cin >> coins[i];
int sum; cin >> sum;
coin_change_min_coins.cpp
// Unbounded Knapsack -> Coin Change - II (min number of coins)
#include <bits/stdc++.h>
using namespace std;
#define INF INT_MAX-1
if (j % coins[i - 1] == 0)
t[i][j] = j / coins[i - 1];
else
t[i][j] = INF;
}
}
}
t[0][0] = 0;
return t[n][sum];
}
signed main() {
int n; cin >> n;
int coins[n];
for (int i = 0; i < n; i++)
cin >> coins[i];
int sum; cin >> sum;
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
LCS_memoization.cpp
#include <bits/stdc++.h>
using namespace std;
if (dp[n][m] != -1)
return dp[n][m];
return dp[n][m];
}
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
LCS_bottom_up_dp.cpp
#include <bits/stdc++.h>
using namespace std;
P a g e | 160
DAARIS AMEEN
return dp[n][m];
}
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
LCSubstring.cpp
#include <bits/stdc++.h>
using namespace std;
int mx = INT_MIN;
P a g e | 161
DAARIS AMEEN
return mx;
}
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
print_LCS.cpp
#include <bits/stdc++.h>
using namespace std;
int i = n, j = m;
string lcs = "";
while (i > 0 && j > 0) {
if (X[i - 1] == Y[j - 1]) {
lcs += X[i - 1];
i--, j--;
}
else {
if (dp[i][j - 1] > dp[i - 1][j])
j--;
else
i--;
}
P a g e | 162
DAARIS AMEEN
}
reverse(lcs.begin(), lcs.end());
return lcs;
}
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
SCS.cpp
// Shortest Common Supersequence
#include <bits/stdc++.h>
using namespace std;
return dp[n][m];
}
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
return 0;
}
min_insertion_del to_convert_a_to_b.cpp
#include <bits/stdc++.h>
using namespace std;
return dp[n][m];
}
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
longest_pallin_subseq.cpp
#include <bits/stdc++.h>
using namespace std;
return dp[n][m];
}
signed main() {
string X, Y; cin >> X;
int n = X.length();
min_del_to_make_pallindrome.cpp
#include <bits/stdc++.h>
using namespace std;
return dp[n][m];
}
signed main() {
string X, Y; cin >> X;
int n = X.length();
print_SCS.cpp
// Shortest Common Supersequence
#include <bits/stdc++.h>
using namespace std;
int i = n, j = m;
string scs = "";
while (i > 0 && j > 0) {
if (X[i - 1] == Y[j - 1]) {
P a g e | 166
DAARIS AMEEN
while (i > 0) {
scs += X[i - 1];
i--;
}
while (j > 0) {
scs += Y[j - 1];
j--;
}
reverse(scs.begin(), scs.end());
return scs;
}
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
longest_repeating_subseq.cpp
#include <bits/stdc++.h>
using namespace std;
return dp[n][m];
}
signed main() {
string X; cin >> X;
int n = X.length();
sequence_patttern_matching.cpp
#include <bits/stdc++.h>
using namespace std;
return dp[n][m];
}
signed main() {
string X, Y; cin >> X >> Y;
int n = X.length(), m = Y.length();
return 0;
}
min_insertion_to_make_string_pallindrome.cpp
#include <bits/stdc++.h>
using namespace std;
return dp[n][m];
}
signed main() {
string X, Y; cin >> X;
int n = X.length();
#include <bits/stdc++.h>
using namespace std;
return ans;
}
signed main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
MCM_memoization.cpp
#include <bits/stdc++.h>
using namespace std;
if (t[i][j] != -1)
return t[i][j];
signed main() {
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
pallindrome_partitioning_recursive.cpp
#include <bits/stdc++.h>
using namespace std;
return true;
}
return ans;
}
int main() {
string X; cin >> X;
return 0;
}
pallindrome_partitioning_memoization.cpp
#include <bits/stdc++.h>
using namespace std;
return true;
}
if (t[i][j] != -1)
return t[i][j];
int main() {
string X; cin >> X;
pallindrome_partitioning_memoized_optimization.cpp
P a g e | 172
DAARIS AMEEN
#include <bits/stdc++.h>
using namespace std;
return true;
}
int main() {
string X; cin >> X;
evaluate_expression_to_true.cpp
#include <bits/stdc++.h>
using namespace std;
int ans = 0;
for (int k = i + 1; k < j; k += 2) {
int l_T = Solve(X, i, k - 1, true);
int l_F = Solve(X, i, k - 1, false);
int r_T = Solve(X, k + 1, j, true);
int r_F = Solve(X, k + 1, j, false);
if (X[k] == '|') {
if (isTrue == true)
ans += l_T * r_T + l_T * r_F + l_F * r_T;
else
ans += l_F * r_F;
}
else if (X[k] == '&') {
if (isTrue == true)
ans += l_T * r_T;
else
ans += l_T * r_F + l_F * r_T + l_F * r_F;
}
else if (X[k] == '^') {
if (isTrue == true)
ans += l_T * r_F + l_F * r_T;
else
ans += l_T * r_T + l_F * r_F;
}
return ans;
}
signed main() {
P a g e | 174
DAARIS AMEEN
evaluate_expression_to_true_memoization_using_map.cpp
#include <bits/stdc++.h>
using namespace std;
if (ump.find(key) != ump.end())
return ump[key];
if (i >= j) {
if (isTrue)
ump[key] = X[i] == 'T';
else
ump[key] = X[i] == 'F';
return ump[key];
}
int ans = 0;
for (int k = i + 1; k < j; k += 2) {
int l_T = Solve(X, i, k - 1, true);
int l_F = Solve(X, i, k - 1, false);
int r_T = Solve(X, k + 1, j, true);
int r_F = Solve(X, k + 1, j, false);
if (X[k] == '|') {
if (isTrue == true)
ans += l_T * r_T + l_T * r_F + l_F * r_T;
else
ans += l_F * r_F;
}
else if (X[k] == '&') {
if (isTrue == true)
ans += l_T * r_T;
else
ans += l_T * r_F + l_F * r_T + l_F * r_F;
}
else if (X[k] == '^') {
if (isTrue == true)
ans += l_T * r_F + l_F * r_T;
else
P a g e | 175
DAARIS AMEEN
signed main() {
string X; cin >> X;
ump.clear();
cout << Solve(X, 0, X.length() - 1, true) << endl;
return 0;
}
evaluate_expression_to_true_memoization_using_3d_array.cpp
#include <bits/stdc++.h>
using namespace std;
if (dp[isTrue][i][j] != -1)
return dp[isTrue][i][j];
int ans = 0;
for (int k = i + 1; k < j; k += 2) {
int l_T = Solve(X, i, k - 1, true);
int l_F = Solve(X, i, k - 1, false);
int r_T = Solve(X, k + 1, j, true);
int r_F = Solve(X, k + 1, j, false);
if (X[k] == '|') {
if (isTrue == true)
ans += l_T * r_T + l_T * r_F + l_F * r_T;
else
ans += l_F * r_F;
}
else if (X[k] == '&') {
if (isTrue == true)
P a g e | 176
DAARIS AMEEN
dp[isTrue][i][j] = ans;
return ans;
}
signed main() {
string X; cin >> X;
scramble_strings_recursive.cpp
#include <bits/stdc++.h>
using namespace std;
int n = X.length();
int flag = false;
for (int i = 1; i <= n - 1; i++) {
if ((Solve(X.substr(0, i), Y.substr(n - i, i)) &&
Solve(X.substr(i), Y.substr(0, n - i))) ||
(Solve(X.substr(0, i), Y.substr(0, i)) &&
Solve(X.substr(i), Y.substr(i)))) {
flag = true;
break;
}
}
P a g e | 177
DAARIS AMEEN
return flag;
}
int main() {
string X, Y; cin >> X >> Y;
if (X.length() != Y.length())
cout << "No\n";
else
Solve(X, Y) ? cout << "Yes\n" : cout << "No\n";
return 0;
}
scramble_strings_memoization.cpp
#include <bits/stdc++.h>
using namespace std;
if (X.compare(Y) == 0) {
ump[key] = true;
return true;
}
if (X.length() <= 1) {
ump[key] = false;
return false;
}
int n = X.length();
int flag = false;
for (int i = 1; i <= n - 1; i++) {
if ((Solve(X.substr(0, i), Y.substr(n - i, i)) &&
Solve(X.substr(i), Y.substr(0, n - i))) ||
(Solve(X.substr(0, i), Y.substr(0, i)) &&
Solve(X.substr(i), Y.substr(i)))) {
flag = true;
break;
}
}
int main() {
string X, Y; cin >> X >> Y;
ump.clear();
if (X.length() != Y.length())
cout << "No\n";
else
Solve(X, Y) ? cout << "Yes\n" : cout << "No\n";
return 0;
}
egg_dropping_problem_recursive.cpp
#include <bits/stdc++.h>
using namespace std;
int mn = INT_MAX;
for (int k = 1; k <= floors; k++) {
int temp_ans = 1 + max(Solve(eggs - 1, k - 1), Solve(eggs,
floors - k));
mn = min(mn, temp_ans);
}
return mn;
}
signed main() {
int eggs, floors;
cin >> eggs >> floors;
egg_dropping_problem_memoization.cpp
#include <bits/stdc++.h>
using namespace std;
if (t[eggs][floors] != -1)
return t[eggs][floors];
int mn = INT_MAX;
for (int k = 1; k <= floors; k++) {
int temp_ans = 1 + max(Solve(eggs - 1, k - 1), Solve(eggs,
floors - k));
mn = min(mn, temp_ans);
}
signed main() {
int eggs, floors;
cin >> eggs >> floors;
egg_dropping_problem_memoized_optimization.cpp
#include <bits/stdc++.h>
using namespace std;
int mn = INT_MAX;
for (int k = 1; k <= floors; k++) {
int top, bottom;
if (dp[eggs - 1][k - 1] != -1)
top = dp[eggs - 1][k - 1];
P a g e | 180
DAARIS AMEEN
else {
top = Solve(eggs - 1, k - 1);
dp[eggs - 1][k - 1] = top;
}
if (dp[eggs][floors - k] != -1)
bottom = dp[eggs][floors - k];
else {
bottom = Solve(eggs, floors - k);
dp[eggs][floors - k] = bottom;
}
int temp_ans = 1 + max(top, bottom);
mn = min(mn, temp_ans);
}
signed main() {
int eggs, floors;
cin >> eggs >> floors;
egg_dropping_problem_binary-search.cpp
class Solution {
int dp[107][10007];
public:
int Solve(int eggs, int floors) {
if (dp[eggs][floors] != -1)
return dp[eggs][floors];
int main() {
int n=3;
vector<int> dp(n+1,-1);
dp[0]= 1;
dp[1]= 1;
#include <bits/stdc++.h>
int main() {
int n=3;
int prev2 = 1;
int prev = 1;
Frog Jump
Given a number of stairs and a frog, the frog wants to climb from the 0th stair to the (N-
1)th stair. At a time the frog can climb either one or two steps. A height[N] array is also
P a g e | 183
DAARIS AMEEN
given. Whenever the frog jumps from a stair i to stair j, the energy consumed in the jump is
abs(height[i]- height[j]), where abs() means the absolute difference. We need to return the
minimum energy that can be used by the frog to jump from stair 0 to stair N-1.
#include <bits/stdc++.h>
int main() {
int main() {
vector<int> height{30,10,60,10,60,50};
int n=height.size();
vector<int> dp(n,-1);
dp[0]=0;
for(int ind=1;ind<n;ind++){
int jumpTwo = INT_MAX;
int jumpOne= dp[ind-1] + abs(height[ind]-height[ind-1]);
if(ind>1)
jumpTwo = dp[ind-2] + abs(height[ind]-height[ind-2]);
dp[ind]=min(jumpOne, jumpTwo);
}
cout<<dp[n-1];
}
P a g e | 184
DAARIS AMEEN
for(int j=1;j<=k;j++){
if(ind-j>=0){
int jump = solveUtil(ind-j, height, dp, k)+ abs(height[ind]-
height[ind-j]);
mmSteps= min(jump, mmSteps);
}
}
return dp[ind]= mmSteps;
int main() {
for(int j=1;j<=k;j++){
if(i-j>=0){
int jump = dp[i-j]+ abs(height[i]- height[i-j]);
mmSteps= min(jump, mmSteps);
}
}
dp[i]= mmSteps;
}
return dp[n-1];
}
int main() {
int main() {
vector<int> arr{2,1,4,9};
int n=arr.size();
cout<<solve(n,arr);
#include <bits/stdc++.h>
dp[0]= arr[0];
return dp[n-1];
}
int main() {
vector<int> arr{2,1,4,9};
int n=arr.size();
cout<<solve(n,arr);
P a g e | 187
DAARIS AMEEN
House Robber
A thief needs to rob money in a street. The houses in the street are arranged in a circular
manner. Therefore the first and the last house are adjacent to each other. The security
system in the street is such that if adjacent houses are robbed, the police will get notified.
Given an array of integers “Arr” which represents money at each house, we need to return
the maximum amount of money that the thief can rob without alerting the police.
#include <bits/stdc++.h>
}
return prev;
}
if(n==1)
return arr[0];
if(i!=0) arr1.push_back(arr[i]);
if(i!=n-1) arr2.push_back(arr[i]);
}
return max(ans1,ans2);
}
int main() {
vector<int> arr{1,5,1,2,6};
int n=arr.size();
cout<<robStreet(n,arr);
}
Ninja’s Training
A Ninja has an ‘N’ Day training schedule. He has to perform one of these three activities
(Running, Fighting Practice, or Learning New Moves) each day. There are merit points
associated with performing an activity each day. The same activity can’t be performed on
two consecutive days. We need to find the maximum merit points the ninja can attain in N
Days.
We are given a 2D Array POINTS of size ‘N*3’ which tells us the merit point of specific
activity on that particular day. Our task is to calculate the maximum number of merit points
that the ninja can earn.
#include <bits/stdc++.h>
if (day == 0) {
int maxi = 0;
for (int i = 0; i <= 2; i++) {
if (i != last)
maxi = max(maxi, points[0][i]);
}
return dp[day][last] = maxi;
}
int maxi = 0;
for (int i = 0; i <= 2; i++) {
if (i != last) {
int activity = points[day][i] + f(day - 1, i, points, dp);
maxi = max(maxi, activity);
}
P a g e | 189
DAARIS AMEEN
int ninjaTraining(int n, vector < vector < int > > & points) {
vector < vector < int > > dp(n, vector < int > (4, -1));
return f(n - 1, 3, points, dp);
}
int main() {
int n = points.size();
cout << ninjaTraining(n, points);
}
#include <bits/stdc++.h>
int ninjaTraining(int n, vector < vector < int > > & points) {
vector < vector < int > > dp(n, vector < int > (4, 0));
int main() {
#include <bits/stdc++.h>
int ninjaTraining(int n, vector < vector < int > > & points) {
prev = temp;
return prev[3];
}
int main() {
{30,60,90}};
int n = points.size();
cout << ninjaTraining(n, points);
}
DP on Grids
Given two values M and N, which represent a matrix[M][N]. We need to find the total
unique paths from the top-left cell (matrix[0][0]) to the rightmost cell (matrix[M-1][N-1]).
At any cell we are allowed to move in only two directions:- bottom and right.
#include <bits/stdc++.h>
int up = countWaysUtil(i-1,j,dp);
int left = countWaysUtil(i,j-1,dp);
int main() {
int m=3;
int n=2;
cout<<countWays(m,n);
}
#include <bits/stdc++.h>
P a g e | 192
DAARIS AMEEN
//base condition
if(i==0 && j==0){
dp[i][j]=1;
continue;
}
int up=0;
int left = 0;
if(i>0)
up = dp[i-1][j];
if(j>0)
left = dp[i][j-1];
dp[i][j] = up+left;
}
}
return dp[m-1][n-1];
int main() {
int m=3;
int n=2;
cout<<countWays(m,n);
}
#include <bits/stdc++.h>
int up=0;
int left =0;
if(i>0)
up = prev[j];
if(j>0)
left = temp[j-1];
temp[j] = up + left;
}
prev = temp;
}
return prev[n-1];
int main() {
int m=3;
int n=2;
cout<<countWays(m,n);
}
//base conditions
if(i>0 && j>0 && maze[i][j]==-1){
dp[i][j]=0;
continue;
}
if(i==0 && j==0){
dp[i][j]=1;
continue;
}
int up=0;
int left = 0;
if(i>0)
up = dp[i-1][j];
if(j>0)
left = dp[i][j-1];
dp[i][j] = up+left;
}
}
return dp[n-1][m-1];
int main() {
int n = maze.size();
int m = maze[0].size();
P a g e | 195
DAARIS AMEEN
cout<<mazeObstacles(n,m,maze);
}
int up = matrix[i][j]+minSumPathUtil(i-1,j,matrix,dp);
int left = matrix[i][j]+minSumPathUtil(i,j-1,matrix,dp);
int main() {
int n = matrix.size();
int m = matrix[0].size();
cout<<minSumPath(n,m,matrix);
}
P a g e | 196
DAARIS AMEEN
#include <bits/stdc++.h>
int up = matrix[i][j];
if(i>0) up += dp[i-1][j];
else up += 1e9;
dp[i][j] = min(up,left);
}
}
}
return dp[n-1][m-1];
int main() {
int n = matrix.size();
int m = matrix[0].size();
cout<<minSumPath(n,m,matrix);
}
#include <bits/stdc++.h>
vector<int> prev(m,0);
for(int i=0; i<n ; i++){
vector<int> temp(m,0);
for(int j=0; j<m; j++){
if(i==0 && j==0) temp[j] = matrix[i][j];
else{
int up = matrix[i][j];
if(i>0) up += prev[j];
else up += 1e9;
temp[j] = min(up,left);
}
}
prev=temp;
}
return prev[m-1];
int main() {
int n = matrix.size();
int m = matrix[0].size();
cout<<minSumPath(n,m,matrix);
}
#include <bits/stdc++.h>
if(dp[i][j]!=-1)
return dp[i][j];
int main() {
int n = triangle.size();
cout<<minimumPathSum(triangle,n);
}
#include <bits/stdc++.h>
for(int j=0;j<n;j++){
P a g e | 199
DAARIS AMEEN
dp[n-1][j] = triangle[n-1][j];
}
return dp[0][0];
int main() {
int n = triangle.size();
cout<<minimumPathSum(triangle,n);
}
#include <bits/stdc++.h>
for(int j=0;j<n;j++){
front[j] = triangle[n-1][j];
}
}
front=cur;
}
return front[0];
int main() {
int n = triangle.size();
cout<<minimumPathSum(triangle,n);
}
// Base Conditions
if(j<0 || j>=m)
return -1e9;
if(i==0)
return matrix[0][j];
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> dp(n,vector<int>(m,-1));
return maxi;
}
int main() {
cout<<getMaxPathSum(matrix);
}
#include <bits/stdc++.h>
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> dp(n,vector<int>(m,0));
}
}
return maxi;
}
int main() {
cout<<getMaxPathSum(matrix);
}
#include <bits/stdc++.h>
int n = matrix.size();
int m = matrix[0].size();
P a g e | 203
DAARIS AMEEN
prev = cur;
}
return maxi;
int main() {
cout<<getMaxPathSum(matrix);
}
int maxChocoUtil(int i, int j1, int j2, int n, int m, vector < vector
< int >>
& grid, vector < vector < vector < int >>> & dp) {
if (j1 < 0 || j1 >= m || j2 < 0 || j2 >= m)
return -1e9;
if (i == n - 1) {
if (j1 == j2)
return grid[i][j1];
else
return grid[i][j1] + grid[i][j2];
}
if (dp[i][j1][j2] != -1)
return dp[i][j1][j2];
int maximumChocolates(int n, int m, vector < vector < int >> & grid) {
vector < vector < vector < int >>> dp(n, vector < vector < int >>
(m, vector < int
> (m, -1)));
int main() {
int n = matrix.size();
int m = matrix[0].size();
#include<bits/stdc++.h>
int maximumChocolates(int n, int m, vector < vector < int >> & grid) {
// Write your code here.
vector < vector < vector < int >>> dp(n, vector < vector < int >>
(m,
vector < int > (m, 0)));
int ans;
if (j1 == j2)
ans = grid[i][j1];
else
ans = grid[i][j1] + grid[i][j2];
ans += -1e9;
else
ans += dp[i + 1][j1 + di][j2 + dj];
int main() {
int n = matrix.size();
int m = matrix[0].size();
#include<bits/stdc++.h>
int maximumChocolates(int n, int m, vector < vector < int >> & grid) {
// Write your code here.
vector < vector < int >> front(m, vector < int > (m, 0)), cur(m,
vector < int >
(m, 0));
int ans;
if (j1 == j2)
ans = grid[i][j1];
else
ans = grid[i][j1] + grid[i][j2];
ans += -1e9;
else
ans += front[j1 + di][j2 + dj];
}
}
cur[j1][j2] = maxi;
}
}
front = cur;
}
int main() {
int n = matrix.size();
int m = matrix[0].size();
Distinct Subsequences
We are given two strings S1 and S2, we want to know how many distinct subsequences of
S2 are present in S1.
#include <bits/stdc++.h>
if(dp[ind1][ind2]!=-1)
P a g e | 209
DAARIS AMEEN
return dp[ind1][ind2];
if(s1[ind1]==s2[ind2]){
int leaveOne = countUtil(s1,s2,ind1-1,ind2-1,dp);
int stay = countUtil(s1,s2,ind1-1,ind2,dp);
else{
return dp[ind1][ind2] = countUtil(s1,s2,ind1-1,ind2,dp);
}
}
vector<vector<int>> dp(lt,vector<int>(ls,-1));
return countUtil(t,s,lt-1,ls-1,dp);
}
int main() {
string s1 = "babgbag";
string s2 = "bag";
#include <bits/stdc++.h>
vector<vector<int>> dp(n+1,vector<int>(m+1,0));
for(int i=0;i<n+1;i++){
dp[i][0]=1;
}
P a g e | 210
DAARIS AMEEN
for(int i=1;i<m+1;i++){
dp[0][i]=0;
}
for(int i=1;i<n+1;i++){
for(int j=1;j<m+1;j++){
if(s1[i-1]==s2[j-1])
dp[i][j] = (dp[i-1][j-1] + dp[i-1][j])%prime;
else
dp[i][j] = dp[i-1][j];
}
}
return dp[n][m];
}
int main() {
string s1 = "babgbag";
string s2 = "bag";
#include <bits/stdc++.h>
vector<int> prev(m+1,0);
prev[0]=1;
for(int i=1;i<n+1;i++){
for(int j=m;j>=1;j--){ // Reverse direction
if(s1[i-1]==s2[j-1])
P a g e | 211
DAARIS AMEEN
return prev[m];
}
int main() {
string s1 = "babgbag";
string s2 = "bag";
Edit Distance
We are given two strings ‘S1’ and ‘S2’. We need to convert S1 to S2. The following three
operations are allowed:
1. Deletion of a character.
2. Replacement of a character with another one.
3. Insertion of a character.
We have to return the minimum number of operations required to convert S1 to S2 as our
answer.
#include <bits/stdc++.h>
using namespace std;
if(i<0)
return j+1;
if(j<0)
return i+1;
if(S1[i]==S2[j])
return dp[i][j] = 0+editDistanceUtil(S1,S2,i-1,j-1,dp);
P a g e | 212
DAARIS AMEEN
int n = S1.size();
int m = S2.size();
vector<vector<int>> dp(n,vector<int>(m,-1));
return editDistanceUtil(S1,S2,n-1,m-1,dp);
int main() {
string s1 = "horse";
string s2 = "ros";
#include <bits/stdc++.h>
int n = S1.size();
int m = S2.size();
vector<vector<int>> dp(n+1,vector<int>(m+1,0));
for(int i=0;i<=n;i++){
dp[i][0] = i;
}
for(int j=0;j<=m;j++){
dp[0][j] = j;
}
for(int i=1;i<n+1;i++){
for(int j=1;j<m+1;j++){
P a g e | 213
DAARIS AMEEN
if(S1[i-1]==S2[j-1])
dp[i][j] = 0+dp[i-1][j-1];
return dp[n][m];
int main() {
string s1 = "horse";
string s2 = "ros";
#include <bits/stdc++.h>
int n = S1.size();
int m = S2.size();
vector<int> prev(m+1,0);
vector<int> cur(m+1,0);
for(int j=0;j<=m;j++){
prev[j] = j;
}
for(int i=1;i<n+1;i++){
cur[0]=i;
for(int j=1;j<m+1;j++){
if(S1[i-1]==S2[j-1])
cur[j] = 0+prev[j-1];
prev = cur;
}
return prev[m];
int main() {
string s1 = "horse";
string s2 = "ros";
Wildcard Matching
We are given two strings ‘S1’ and ‘S2’. String S1 can have the following two special
characters:
1. ‘?’ can be matched to a single character of S2.
2. ‘*’ can be matched to any sequence of characters of S2. (sequence can be of length
zero or more).
We need to check whether strings S1 and S2 match or not.
#include <bits/stdc++.h>
//Base Conditions
if (i < 0 && j < 0)
return true;
if (i < 0 && j >= 0)
return false;
P a g e | 215
DAARIS AMEEN
else {
if (S1[i] == '*')
return wildcardMatchingUtil(S1, S2, i - 1, j, dp) ||
wildcardMatchingUtil(S1, S2, i, j - 1, dp);
else return false;
}
}
int n = S1.size();
int m = S2.size();
vector < vector < bool >> dp(n, vector < bool > (m, -1));
return wildcardMatchingUtil(S1, S2, n - 1, m - 1, dp);
int main() {
string S1 = "ab*cd";
string S2 = "abdefcd";
if (wildcardMatching(S1, S2))
cout << "String S1 and S2 do match";
else cout << "String S1 and S2 do not match";
}
#include <bits/stdc++.h>
}
return true;
}
int n = S1.size();
int m = S2.size();
vector < vector < bool >> dp(n + 1, vector < bool > (m, false));
dp[0][0] = true;
else {
if (S1[i - 1] == '*')
dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
return dp[n][m];
int main() {
string S1 = "ab*cd";
string S2 = "abdefcd";
if (wildcardMatching(S1, S2))
cout << "String S1 and S2 do match";
else cout << "String S1 and S2 do not match";
}
P a g e | 217
DAARIS AMEEN
#include <bits/stdc++.h>
int n = S1.size();
int m = S2.size();
prev[0] = true;
else {
if (S1[i - 1] == '*')
cur[j] = prev[j] || cur[j - 1];
return prev[m];
int main() {
P a g e | 218
DAARIS AMEEN
string S1 = "ab*cd";
string S2 = "abdefcd";
if (wildcardMatching(S1, S2))
cout << "String S1 and S2 do match";
else cout << "String S1 and S2 do not match";
}
for(int i=1;i<Arr.size();i++){
int curProfit = Arr[i] - mini;
maxProfit = max(maxProfit,curProfit);
mini = min(mini,Arr[i]);
}
return maxProfit;
}
int main() {
if(dp[ind][buy]!=-1)
return dp[ind][buy];
long profit;
vector<vector<long>> dp(n,vector<long>(2,-1));
if(n==0) return 0;
long ans = getAns(Arr,0,0,n,dp);
return ans;
}
P a g e | 220
DAARIS AMEEN
int main() {
int n =6;
long Arr[n] = {7,1,5,3,6,4};
#include <bits/stdc++.h>
vector<vector<long>> dp(n+1,vector<long>(2,-1));
//base condition
dp[n][0] = dp[n][1] = 0;
long profit;
dp[ind][buy] = profit;
}
}
return dp[0][0];
}
int main() {
int n =6;
long Arr[n] = {7,1,5,3,6,4};
P a g e | 221
DAARIS AMEEN
#include <bits/stdc++.h>
//base condition
ahead[0] = ahead[1] = 0;
long profit;
ahead = cur;
}
return cur[0];
}
int main() {
int n =6;
long Arr[n] = {7,1,5,3,6,4};
int getAns(vector<int>& Arr, int n, int ind, int buy, int cap,
vector<vector<vector<int>>>& dp ){
if(dp[ind][buy][cap]!=-1)
return dp[ind][buy][cap];
int profit;
return getAns(prices,n,0,0,2,dp);
int main() {
#include <bits/stdc++.h>
return dp[0][0][2];
P a g e | 224
DAARIS AMEEN
int main() {
#include <bits/stdc++.h>
return ahead[0][2];
}
P a g e | 225
DAARIS AMEEN
int main() {
int getAns(vector<int>& Arr, int n, int ind, int buy, int cap,
vector<vector<vector<int>>>& dp ){
if(dp[ind][buy][cap]!=-1)
return dp[ind][buy][cap];
int profit;
return getAns(prices,n,0,0,k,dp);
int main() {
#include <bits/stdc++.h>
return dp[0][0][k];
int main() {
#include <bits/stdc++.h>
cur[buy][cap] = max(0+ahead[1][cap],
Arr[ind] + ahead[0][cap-1]);
}
}
}
ahead = cur;
}
return ahead[0][k];
int main() {
if(dp[ind][buy]!=-1)
return dp[ind][buy];
int profit;
P a g e | 229
DAARIS AMEEN
int main() {
#include <bits/stdc++.h>
dp[ind][buy] = profit;
}
}
return dp[0][0];
}
int main() {
#include <bits/stdc++.h>
cur[buy] = profit;
}
P a g e | 231
DAARIS AMEEN
front2 = front1;
front1 = cur;
return cur[0];
}
int main() {
if(dp[ind][buy]!=-1)
return dp[ind][buy];
int profit;
vector<vector<int>> dp(n,vector<int>(2,-1));
if(n==0) return 0;
int ans = getAns(Arr,0,0,n,fee,dp);
return ans;
}
int main() {
#include <bits/stdc++.h>
vector<vector<int>> dp(n+1,vector<int>(2,0));
dp[ind][buy] = profit;
}
}
return dp[0][0];
}
int main() {
#include <bits/stdc++.h>
//base condition
ahead[0] = ahead[1] = 0;
long profit;
ahead = cur;
}
return cur[0];
int main() {
GREEDY
N meetings in one room
Problem Statement: There is one meeting room in a firm. You are given two arrays, start
and end each of size N.For an index ‘i’, start[i] denotes the starting time of the ith meeting
while end[i] will denote the ending time of the ith meeting. Find the maximum number of
meetings that can be accommodated if only one meeting can happen in the room at a
particular time. Print the order in which these meetings will be performed.
#include <bits/stdc++.h>
using namespace std;
struct meeting {
int start;
int end;
int pos;
};
class Solution {
public:
bool static comparator(struct meeting m1, meeting m2) {
if (m1.end < m2.end) return true;
else if (m1.end > m2.end) return false;
else if (m1.pos < m2.pos) return true;
return false;
}
void maxMeetings(int s[], int e[], int n) {
struct meeting meet[n];
for (int i = 0; i < n; i++) {
meet[i].start = s[i], meet[i].end = e[i], meet[i].pos = i +
1;
}
P a g e | 236
DAARIS AMEEN
};
int main() {
Solution obj;
int n = 6;
int start[] = {1,3,0,5,8,5};
int end[] = {2,4,5,7,9,9};
obj.maxMeetings(start, end, n);
return 0;
}
// through sorting
#include<bits/stdc++.h>
using namespace std;
int ans=1;
int count=1;
int i=1,j=0;
while(i<n && j<n)
{
if(arr[i]<=dep[j]) //one more platform needed
{
count++;
i++;
}
else //one platform can be reduced
{
count--;
j++;
}
ans=max(ans,count); //updating the value with the current
maximum
P a g e | 238
DAARIS AMEEN
}
return ans;
}
int main()
{
int arr[]={900,945,955,1100,1500,1800};
int dep[]={920,1200,1130,1150,1900,2000};
int n=sizeof(dep)/sizeof(dep[0]);
cout<<"Minimum number of Platforms required
"<<countPlatforms(n,arr,dep)<<endl;
}
# Output:
#include<bits/stdc++.h>
Solution ob;
//function call
pair < int, int > ans = ob.JobScheduling(arr, n);
cout << ans.first << " " << ans.second << endl;
return 0;
P a g e | 240
DAARIS AMEEN
# Output: 3 90
# Space Complexity: O(M) for an array that keeps track on which day
which job is performed if M is the maximum deadline available.
#include <bits/stdc++.h>
struct Item {
int value;
int weight;
};
class Solution {
public:
bool static comp(Item a, Item b) {
double r1 = (double) a.value / (double) a.weight;
double r2 = (double) b.value / (double) b.weight;
return r1 > r2;
}
// function to return fractionalweights
double fractionalKnapsack(int W, Item arr[], int n) {
int curWeight = 0;
double finalvalue = 0.0;
return finalvalue;
}
};
int main() {
int n = 3, weight = 50;
Item arr[n] = { {100,20},{60,10},{120,30} };
Solution obj;
double ans = obj.fractionalKnapsack(weight, arr, n);
cout << "The maximum value is " << setprecision(2) << fixed << ans;
return 0;
}
# Output:
# Time Complexity: O(n log n + n). O(n log n) to sort the items and
O(n) to iterate through all the items for calculating the answer.
#include<bits/stdc++.h>
return 0;
}
# Output:
# Time Complexity:O(V)
# Space Complexity:O(1)
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(),nums.end());
set<vector<int>> sv;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
for(int k=j+1;k<n;k++)
{
if(binary_search(nums.begin()
+k+1,nums.end(),x)){
vector<int> v;
v.push_back(nums[i]);
v.push_back(nums[j]);
v.push_back(nums[k]);
v.push_back(x);
sort(v.begin(),v.end());
sv.insert(v);
}
}
}
}
vector<vector<int>> res(sv.begin(),sv.end());
return res;
}
};
int main()
{
Solution obj;
vector<int> v{1,0,-1,0,-2,2};
vector<vector<int>> sum=obj.fourSum(v,0);
cout<<"The unique quadruplets are"<<endl;
for (int i = 0; i < sum.size(); i++) {
for (int j = 0; j < sum[i].size(); j++)
P a g e | 245
DAARIS AMEEN
___________________________________________________
// Optimised Approach
# Sort the array, and then fix two pointers, so the remaining sum will
be (target – (nums[i] + nums[j])).
# Now we can fix two-pointers, one front, and another back, and easily
use a two-pointer to find the remaining two numbers of the quad.
# In order to avoid duplications, we jump the duplicates, because
taking duplicates will result in repeating quads.
# We can easily jump duplicates, by skipping the same elements by
running a loop.
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& num, int target) {
vector<vector<int> > res;
if (num.empty())
return res;
int n = num.size();
sort(num.begin(),num.end());
int front = j + 1;
int back = n - 1;
else {
}
}
return res;
}
};
int main()
{
Solution obj;
P a g e | 247
DAARIS AMEEN
vector<int> v{1,0,-1,0,-2,2};
vector<vector<int>> sum=obj.fourSum(v,0);
cout<<"The unique quadruplets are"<<endl;
for (int i = 0; i < sum.size(); i++) {
for (int j = 0; j < sum[i].size(); j++)
cout << sum[i][j] << " ";
cout << endl;
}
}
P a g e | 248
DAARIS AMEEN
SEGMENT TREE
int RMQUtil(int *st, int ss, int se, int qs, int qe, int index)
{
if (ss == se)
{
st[si] = arr[ss];
return arr[ss];
}
int x = (int)(ceil(log2(n)));
int max_size = 2*(int)pow(2, x) - 1;
int *st = new int[max_size];
constructSTUtil(arr, 0, n-1, st, 0);
return st;
}
int RMQUtil1(int *st, int ss, int se, int qs, int qe, int index)
{
if (ss == se)
{
st[si] = arr[ss];
return arr[ss];
}
int x = (int)(ceil(log2(n)));
return st;
}
int main()
{
vector<int> arr={1,5,2,7,9};
int *st= constructST(arr, n);
}
P a g e | 251
DAARIS AMEEN
SLIDING WINDOW
FIXED WINDOW
Maximum sum subarray of size K
//Time Complexity : O(n)
//Auxiliary Space : O(1)
class Solution{
public:
int maximumSumSubarray(int K, vector<int> &Arr , int N){
int i=0;
int j=0;
int sum=0;
int mx=INT_MIN;
while (j<N){
sum = sum + Arr[j]; // do calculation to reduse tc
if (j-i+1 < K) j++; // increament j upto when the size of the size
of window is not equal to required size
else if ((j-i+1) == K) // when sindow size hit to the required
window size
{
mx = max(mx,sum); // selecting ans from the candidates
sum = sum - Arr[i]; // start removing from the first
i++;
j++;
}
}
return mx;
}
};
ans.push_back(0);
else
ans.push_back(l.front());
if(A[i]<0)
l.pop_front();
i++;
j++;
}
}
return ans;
}
int k = pat.size();
int count = m.size();
int ans = 0;
int i = 0, j = 0;
if(m.find(txt[j]) != m.end()) {
m[txt[j]]--;
if(m[txt[j]] == 0)
count--;
}
else if(j - i + 1 == k) {
if(count == 0)
ans++;
P a g e | 253
DAARIS AMEEN
if(m.find(txt[i]) != m.end()) {
m[txt[i]]++;
if(m[txt[i]] == 1)
count++;
}
i++; j++;
}
}
return ans;
}
};
while (j<nums.size())
{
while(l.size()>0 && l.back() <nums[j])
{
l.pop_back();
}
l.push_back(nums[j]);
if ((j-i+1)<k)
j++;
else if (j-i+1==k)
{
ans.push_back(l.front());
if (l.front()==nums[i])
l.pop_front();
i++;
j++;
}
}
P a g e | 254
DAARIS AMEEN
return ans;
}
};
VARIABLE WINDOW
Largest subarray of sum k
#include<bits/stdc++.h>
if (sum == k)
maxLength = max(maxLength, (end - start + 1));
sum -= arr[start];
start++;
}
return maxLength;
}
int main() {
cout << "Length of the longest subarray with sum K is " <<
longestSubArrWithSumK_Optimal(arr, n, k);
return 0;
}
Output: 1
Explanation: Since all the characters of the strings are different, the substring length with K
distinct characters depends on K itself.
int KDistinct(string input, int K)
{
// define a hash table to store the frequencies
// of characters in the window
unordered_map<char, int> table;
if (table[startCharacter] == 0)
{
table.erase(startCharacter);
}
}
longest = max(longest, end - start + 1);
}
return longest;
}
int main()
{
string input = "ababcbcca";
int K = 2;
cout << KDistinct(input, K) << endl;
P a g e | 256
DAARIS AMEEN
return 0;
}
}
j++;
}
return mx;
}
};
THANK YOU