Professional Documents
Culture Documents
Demux Academy
Demux Academy
DAY 2:
Introduction to Searching
#include <bits/stdc++.h>
using namespace std;
int main () {
int n, q;
cin >> n >> q;
vector<int> arr(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
while(q--) {
int k;
cin >> k;
// Actual code begin.
// First occurrence.
int lo = 0, hi = n-1, mid;
// p(x): arr[mid] >= k
// first T
while (lo < hi) {
// Mid computation
mid = lo + (hi - lo)/2;
// Decision.
if (arr[mid] >= k)
hi = mid;
else
lo = mid + 1;
}
// Sanity check.
// Not present.
if (arr[lo] != k) {
cout << "-1 -1" << endl;
continue;
}
cout << lo << " ";
// Last occurrence.
lo = 0, hi = n-1;
// p(x): arr[mid] > k
// last F
while (lo < hi) {
// Mid computation.
mid = lo + (hi - lo + 1)/2;
// Decision.
if (arr[mid] > k)
hi = mid - 1;
else
lo = mid;
}
// No Sanity check.
cout << lo << endl;
}
}
DAY3::
#include <bits/stdc++.h>
using namespace std;
int main () {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// Actual code begins.
// p(x): arr[mid] > arr[mid+1]
// first T
int lo = 0, hi = n - 1, mid;
while (lo < hi) {
// Mid computation.
mid = lo + (hi - lo)/2;
// Decision.
if (arr[mid] > arr[mid+1])
hi = mid;
else
lo = mid + 1;
}
// Sanity check.
cout << lo+1 << endl;
}
#include <bits/stdc++.h>
using namespace std;
int main () {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// Actual code begins here.
// p(x): arr[mid] < arr[0]
// first T.
int lo = 0, hi = n - 1, mid;
while (lo < hi) {
mid = lo + (hi - lo)/2;
if (arr[mid] < arr[0])
hi = mid;
else
lo = mid + 1;
}
// Sanity check.
if (arr[lo] < arr[0])
cout << arr[lo] << endl;
// Increasing array with 0 rotations, n rotations, 2n
rotations.
else
cout << arr[0] << endl;
}
● https://problems.demux.in/problem/rotatedarray2
● https://leetcode.com/problems/find-in-mountain-array/
DAY 4:
Optimization Problems: Smallest Good Divisor
Optimization Problems: Smallest Divisor Explanation
#include <bits/stdc++.h>
int sum = 0;
sum += ceil((float)arr[i]/divisor);
return sum;
int main() {
vector<int> arr(n);
// first T
// Mid computation
// Decision
hi = mid;
else
lo = mid + 1;
#include <bits/stdc++.h>
curr_trip_capacity += packages[i];
} else {
trip_count++;
curr_trip_capacity = packages[i];
int main () {
vector<int> packages(n);
sum_weights += packages[i];
// Searching packages.
// max(packages[i]) to sum(packages[i])
// First T
hi = mid;
else
lo = mid + 1;
}
// No sanity check.
Problems:
● https://problems.demux.in/problem/targetarraysum
● https://problems.demux.in/problem/dudleychocolates
Reading:
https://drive.google.com/file/d/1-EgrW363YVKJ_juM4uSM8LJQgGPUPqXd/view?usp=s
haring
● Client-Server Architecture
● DNS
● HTTP Request/Response models
● HTTP Request methods and response codes.
This is the second video in our series of "How Internet works". In this session we talk
about Server side technologies and architectures.
We discussed that a web server‘s fundamental job is to accept and fulfill requests from
clients for static content from a website (HTML pages, files, images, video, and so on)
while an application server provide its clients with access to what is commonly called
business logic, which generates dynamic content. An application server’s clients are
often applications themselves, and can include web servers and other application
servers
We also discussed most commonly used software bundles like LAMP, MERN, MEAN
etc. and their applications in both 2-tier and 3 tier server architectures.
In the end we bring light to a high level view of how server ecosystems looks like with
Elastic load balancers and multiple servers.
This is the third session in our series of "How Internet Works". We have done a live
mockup of both Client and Server to see how does a request travels
Session notes are available here
https://youtu.be/v1-SgLL55mA
Code:
class Solution {
public:
freq[tasks[i]-'A']++;
int count_max_freq = 0;
if (freq[i] == max_freq)
count_max_freq++;
int start_length;
if (n >= count_max_freq-1)
else
return k;
};
Code:
class Solution {
public:
lo = 0, hi = n-1;
return mid;
if (mid - 1 >= 0 && nums[mid-1] > nums[mid])
hi = mid - 1;
else
lo = mid + 1;
// NF: Non-functional.
return -1;
};
DAY 1:Preprocessing
Preprocessing Introduction
The Problem can be viewed and practiced here: Range Sum Query - Immutable
1D RANGE SUM QUERY EXPLANATION
Range Sum Query - Code
Problem link: https://leetcode.com/problems/range-sum-query-immutable/
Code:
class NumArray {
public:
NumArray(vector<int>& nums) {
int n = nums.size();
P.resize(n);
P[0] = nums[0];
};
/**
*/
Preprocessing - Examples
The Problem can be viewed and practiced here: Product of Array Except Self
Code:
class Solution {
public:
int n = nums.size();
vector<int> out(n);
// Preprocessing.
// Compute the Suffix Product Array.
out[n-1] = nums[n-1];
// Main logic.
out[0] = out[1];
prod_so_far *= nums[i];
out[n-1] = prod_so_far;
return out;
}
};
Preprocessing examples
The Problem can be viewed and practised here: Best Time to Buy and Sell Stock
III
Code:
class Solution {
public:
// Preprocessing.
if (n == 1) return 0;
vector<int> max_profit_one(n);
max_profit_one[0] = 0;
min_so_far = prices[0];
// 2 choices
// Sell at i
max_profit_one[i] = max(max_profit_one[i-1],
prices[i] - min_so_far);
// Main logic.
int max_so_far;
int ans = 0;
// For n-1
int pi = max_profit_one[n-2];
ans = max(ans, pi);
max_so_far = prices[n-1];
// For n-2 to 1
// For 0.
pi = max_so_far - prices[0];
return ans;
};
Direct Access Tables
The Problem can be viewed and practiced here: Find the Duplicate Number
Code:
class Solution {
public:
int n = nums.size();
if (nums[abs(nums[i])] < 0)
return abs(nums[i]);
nums[abs(nums[i])] *= -1;
// NF: Non-Functional.
return -1;
}
};
The Problem can be viewed and practised here: First Missing Positive
Code:
class Solution {
public:
int n = nums.size(), i, j;
i = 0, j = n - 1;
while (i <= j) {
// Do Nothing.
if (nums[i] > 0) {
i++;
continue;
swap(nums[i], nums[j]);
j--;
int new_size = j + 1;
continue;
if (nums[abs(nums[i]) - 1] > 0)
nums[abs(nums[i]) - 1] *= -1;
}
// Find the first missing positive.
if (nums[i] > 0)
return i + 1;
return new_size + 1;
};
Practice Problems
Bookmark this page
● Task Scheduler
● Move Zeroes
● Jump Game
● Increasing Triplet Subsequence
DAY 2:
2D Arrays
Code:
class Solution {
public:
// Matrix representation.
// 4 boundaries.
// Top
res.push_back(matrix[top][i]);
// Right
res.push_back(matrix[i][right]);
// Bottom
if (top != bottom) {
res.push_back(matrix[bottom][i]);
// Left
if (left != right) {
res.push_back(matrix[i][left]);
return res;
};
The Problem can be viewed and practiced here: Range Sum Query 2D -
Immutable
Code:
class NumMatrix {
public:
vector<vector<int>> prefix_sum;
NumMatrix(vector<vector<int>>& matrix) {
prefix_sum[i][j] = matrix[i][j];
if (j - 1 >= 0)
if (i - 1 >= 0)
if (col1 - 1 >= 0)
if (row1 - 1 >= 0)
return res;
}
};
/**
*/
Practice Problems
● Rotate Array
● Count Servers that Communicate
● Valid Sudoku
● set-matrix-zeroes
Solution:
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> v;
int n,temp;
cin >> n;
for(int i=0;i<n;i++){
cin >> temp;
v.push_back(temp);
}
// 0 or 1 elements inside array
if(n==0 || n==1){
printArray(v,n);
return 0;
}
// to mark all unique values
int p1=0;
// running pointer
int p2=1;
while(p2<n){
if(v[p1]==v[p2]) p2++;
else{
p1 = p1+1;
swap(v[p1],v[p2]);
p2++;
}
}
printArray(v,p1+1);
return 0;
}
Practise Problems
Bookmark this page
Please practise these questions, these are the most basic and standard questions of 2
pointers.
● https://leetcode.com/problems/remove-duplicates-from-sorted-array/
● https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
● https://leetcode.com/problems/reverse-words-in-a-string-ii/
● https://leetcode.com/problems/rotate-array/
● https://leetcode.com/problems/valid-palindrome/
● https://leetcode.com/problems/container-with-most-water/
in this video, we will discuss 3 types of patterns which we apply in 3 pointer problems.
Method
Problem Statement - Given an integer unsorted array, return all the triplets which sums
to zero..
Code -
class Solution {
public:
vector<vector<int>> res;
sort(nums.begin(),nums.end());
int n = nums.size();
for(int a=0;a<n-2;a++){
if(nums[a]>0) break;
int A = nums[a];
for(int b=a+1,c=n-1;b<c;){
int B = nums[b];
int C = nums[c];
int sum = A+B+C;
if(sum==0){
res.push_back({nums[a],nums[b],nums[c]});
} else{
if(sum>0) c--;
else b++;
return res;
};
In this video, we will look at one of the classical Container with maximum water problem
and solve via 2 pointer (Index based) technique.
Problem Statement - Given n non-negative integers a1, a2, ..., an , where each
represents a point at coordinate (i, ai). n vertical lines are drawn such that the two
endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis
forms a container, such that the container contains the most water.
Code -
class Solution {
public:
int n = height.size();
if(n==0) return 0;
int p1=0,p2=n-1;
int maxvol = 0;
while(p1<p2){
maxvol =
max(maxvol,min(height[p1],height[p2])*abs(p2-p1));
if(height[p1]>height[p2]){
int temp = height[p2--];
} else{
return maxvol;
};
1. https://leetcode.com/problems/reverse-vowels-of-a-string/
2. https://leetcode.com/problems/4sum/
3. https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
4. https://leetcode.com/problems/most-profit-assigning-work/
Slow-Fast Pointer Approach + Questions
When to apply?
Method
1. Position pointers
2. Move slow pointer by 1 unit, fast pointer by 2 units
3. Terminate when they meet or you reach end
In above video, we will look at one of the classical Cycle detection in Linked List
problem and solve via 2 pointer (Slow-fast pointer) technique.
Problem Statement - Given head, the head of a linked list, determine if the linked list
has a cycle in it.
Code -
/**
* int val;
* ListNode *next;
* };
*/
class Solution {
public:
while(slow!=fast){
slow = slow->next;
fast = fast->next->next;
return true;
}
};
In above video, we will look at one of the classical finding middle element of linked list
problem and solve via 2 pointer (Slow-fast) Approach.
Problem Statement - Given a non-empty, singly linked list with head node head, return a
middle node of linked list.
Code -
/**
* struct ListNode {
* int val;
* ListNode *next;
*/
class Solution {
public:
slow = slow->next;
fast = fast->next->next;
return slow;
}
};
1. https://leetcode.com/problems/circular-array-loop/
2.
3. https://leetcode.com/problems/find-the-duplicate-number/
4.
5. https://leetcode.com/problems/linked-list-cycle-ii/
Method
Problem Statement - Given a string s, find the length of the longest substring without
repeating characters.
Code -
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> hash(256,0);
int p1=0,p2=0;
int res=0,count=0;
while(p2<s.size()){
if(hash[s[p2]]>0) count++;
hash[s[p2]]++;
p2++;
while(count>0){
if(hash[s[p1]]>1) count--;
hash[s[p1]]--;
p1++;
res = max(res,p2-p1);
return res;
};
1. https://leetcode.com/problems/substring-with-concatenation-of-all-words/
2. https://leetcode.com/problems/minimum-window-substring/
3. https://leetcode.com/problems/minimum-size-subarray-sum/
4. https://leetcode.com/problems/longest-repeating-character-replacement/
5. https://leetcode.com/problems/find-all-anagrams-in-a-string/
Doubt Session + Questions: Practise Together
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> pos(26,0);
for(int i=0;i<s.size();i++){
pos[s[i]-'a']=i;
int maxIdx=-1,lastIdx=0;
vector<int> result;
for(int i=0;i<s.size();i++){
maxIdx=max(maxIdx,pos[s[i]-'a']);
if(maxIdx==i){
result.push_back(maxIdx-lastIdx+1);
lastIdx=i+1;
return result;
};
class Solution {
public:
// Window parameters
int start=0,end=0;
int length=INT_MAX,head=0;
int count=0;
while(end<s.size()){
if(hash[s[end]]>0) count++;
hash[s[end]]--;
end++;
// until size of window match criteria
while(count==t.size()){
length=end-start;
head=start;
if(hash[s[start]]==0) count--;
hash[s[start]]++;
start++;
}
};
class Solution {
public:
sort(nums.begin(),nums.end());
int n = nums.size();
for(int i=0;i<n-2;i++){
for(int j=i+1,k=n-1;j<k;){
if(sum<target) j++;
else k--;
}
}
return res;
};
Problem Link -
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
/**
* struct ListNode {
* int val;
* ListNode *next;
* };
*/
class Solution {
public:
ListNode *slow=head,*fast=head;
while(fast->next!=NULL){
slow=slow->next;
fast=fast->next;
slow->next = slow->next->next;
return head;
};
Question Link -
https://leetcode.com/problems/trapping-rain-water/
class Solution {
public:
int l_idx=0,r_idx=height.size()-1,res=0,minVol=0;
while(l_idx<r_idx){
res+=minVol-height[l_idx];
l_idx++;
res+=minVol-height[r_idx];
r_idx--;
// Update MinVol
minVol=min(height[r_idx],height[l_idx]);
return res;
}
};
Digits of a number
Solution:
class Solution {
public:
int res = 0;
count++;
if (count % 2 == 0)
res++;
return res;
};
class Solution {
public:
int res = 0;
pow *= 26;
return res;
};
Code:
class Solution {
public:
string res;
res.push_back(ch);
// Reverse
reverse(res.begin(), res.end());
return res;
};
Practice Questions
https://leetcode.com/problems/integer-to-roman/
https://leetcode.com/problems/roman-to-integer/
https://leetcode.com/problems/integer-to-english-words/
https://leetcode.com/problems/add-digits/
Computer Memory
Bitwise Operators
Bitwise Operators
Magic of XOR
Code:
class Solution {
public:
int res = 0;
// Cumulative xor.
res ^= nums[i];
return res;
};
Practice Problems
https://leetcode.com/problems/xor-queries-of-a-subarray/
https://leetcode.com/problems/single-number/
https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-
one/
https://leetcode.com/problems/bitwise-ors-of-subarrays/
DAY 3:Bit tricks: Test ith bit
Test if ith bit is set
Code:
class Solution {
public:
int res = 0;
continue;
if (!c_set && a_set && b_set)
res += 2;
else
res++;
return res;
};
Code:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
int count = 0;
if (count%3 == 1) {
return res;
}
};
Code:
class Solution {
public:
// Get axorb.
long axorb = 0;
axorb ^= nums[i];
int b = 0, a = 0;
if (nums[i]&mask)
b ^= nums[i];
else
a ^= nums[i];
};
Practice Problems
Bookmark this page
https://leetcode.com/problems/bitwise-and-of-numbers-range/
https://leetcode.com/problems/missing-number/
https://leetcode.com/problems/counting-bits/
https://leetcode.com/problems/sum-of-two-integers/
Intro to STL
// custom namspace
namespace Myspace{
int a =6;
int main(){
// vector<int> v;
// v.push_back(5);
// v.push_back(10);
// for(int i=0;i<v.size();i++){
// }
// 2. through iterator
// vector<int>::iterator it;
// for(auto it=v.begin();it!=v.end();it++){
// }
// while(!v.empty()){
// v.pop_back();
// }
// / pair + container(vector)
vector<pair<int,int>> v;
v.push_back(make_pair(2,3));
v.push_back({4,5});
for(auto it=v.begin();it!=v.end();it++){
cout << it->first << " " << it->second << endl;
// n*m
vector<int> v(n,0);
vector<vector<int>> matrix(n,vector<int>(m,0)); //
initialize a 2d vector of size n*m with all values 0
return 0;
// Sequential containers
// Deque
// List
// Strings
int main() {
// deque
// deque<int> dq;
// dq.push_back(5);
// dq.push_back(10);
// dq.push_back(19);
// dq.push_front(90);
// dq.push_front(100);
// // for(int i=0;i<dq.size();i++){
// // }
// deque<int>::iterator it;
// for(it=dq.begin();it!=dq.end();it++){
// }
// List
// list<int> li;
// li.push_back(10);
// li.push_front(20);
// li.push_back(19);
// li.pop_back();
// // for(int i=0;i<li.size();i++){
// // }
// for(auto it=li.begin();it!=li.end();it++){
// }
// strings
string s1 = "valar";
string s2 = "morghulis";
return 0;
Standard Template Library (STL) - Set, Map and Unordered Map
Set
set is an associative container that contains a sorted set of unique objects of type Key.
Sorting is done using the key comparison function Compare. Search, removal, and
insertion operations have logarithmic complexity. Sets are usually implemented as
red-black trees.
Map
map is a sorted associative container that contains key-value pairs with unique keys.
Keys are sorted by using the comparison function Compare. Search, removal, and
insertion operations have logarithmic complexity. Maps are usually implemented as
red-black trees.
Unordered Map
Unordered map is an associative container that contains key-value pairs with unique
keys. Search, insertion, and removal of elements have average constant-time
complexity.
Internally, the elements are not sorted in any particular order, but organized into
buckets. Which bucket an element is placed into depends entirely on the hash of its key.
This allows fast access to individual elements, since once the hash is computed, it
refers to the exact bucket the element is placed into.
#include <bits/stdc++.h>
using namespace std;
// Unordered_container - unordered_map
int main() {
// set
// set<int> s;
// s.insert(10);
// s.insert(20);
// s.insert(30);
// s.insert(10);
// s.erase(30);
// for(auto it=s.begin();it!=s.end();it++){
// }
// maps - Red Black trees
// map<int,string> mp;
// mp[4]="hello";
// mp.insert({4,"world"});
// for(auto it=mp.begin();it!=mp.end();it++){
// cout << it->first << " " << it->second << endl;
// }
unordered_map<int,string> umap;
umap[6]="hello";
umap[7]="world";
umap[6] = "bye";
for(auto it=umap.begin();it!=umap.end();it++){
cout << it->first << " " << it->second << endl;
}return 0;}
Standard Template Library (STL) - Stack, Queue and Priority Q…
Stack
stack class is a container adapter that gives the programmer the functionality of a
stack - specifically, a LIFO (last-in, first-out) data structure.
The class template acts as a wrapper to the underlying container - only a specific set of
functions is provided. The stack pushes and pops the element from the back of the
underlying container, known as the top of the stack.
Queue
queue class is a container adapter that gives the programmer the functionality of a
queue - specifically, a FIFO (first-in, first-out) data structure.
The class template acts as a wrapper to the underlying container - only a specific set of
functions is provided. The queue pushes the elements on the back of the underlying
container and pops them from the front.
Priority Queue
priority queue is a container adaptor that provides constant time lookup of the largest
(by default) element, at the expense of logarithmic insertion and extraction.
#include <bits/stdc++.h>
// adaptive Containers
// stack
// queue
// priority_queue
int main() {
// stack
// stk.push(56);
// stk.push(36);
// stk.push(87);
// stk.push(198);
// while(!stk.empty()){
// }
// queue - FIFO
// queue<int> q;
// q.push(18);
// q.push(26);
// q.push(87);
// q.push(54);
// while(!q.empty()){
// q.pop();
// }
maxq.push(54);
maxq.push(65);
maxq.push(8);
maxq.push(199);
while(!maxq.empty()){
maxq.pop();
return 0;
Further Readings
Bookmark this page
object. In C and C++, the link is the address of that object in the program
memory. Pointers allow to refer to the same object from multiple locations
of the source code without copying the object. Also, the same pointer
variable may refer to different objects during its lifetime.
When a variable is declared, the memory needed to store its value is assigned a
specific location in memory (its memory address). Generally, C++ programs do
not actively decide the exact memory addresses where its variables are stored.
Fortunately, that task is left to the environment where the program is run -
generally, an operating system that decides the particular memory locations on
runtime. However, it may be useful for a program to be able to obtain the address
of a variable during runtime in order to access data cells that are at a certain
position relative to it.
Pointers to pointers
C++ allows the use of pointers that point to pointers, that these, in its turn, point
to data (or even to other pointers). The syntax simply requires an asterisk (*) for
each level of indirection in the declaration of the pointer.
#include <bits/stdc++.h>
int main() {
// Basic Pointers
int *ptr;
ptr = &var;
// cout << ptr << endl;
*ptr = 1036;
// pointer to pointer
int **ptr2;
//
ptr2 = &ptr;
// pointers in array
// A[i] = *(A+i)
*(ptrA+2) = 12;
*(ptrA) = 23;
*(ptrA+1) = 20;
return 0;
public:
lo = 0, hi = n-1;
return nums[mid];
if (mid%2 == 1)
lo = mid + 1;
else
hi = mid - 1;
} else {
if (mid%2 == 1)
hi = mid - 1;
else
lo = mid + 1;
// NF - Non Functional
return -1;
};
https://leetcode.com/problems/bitwise-and-of-numbers-range/
class Solution {
public:
int rangeBitwiseAnd(int left, int right) {
int i, ans = 0;
if ((left>>i) != (right>>i))
break;
else if (left&(1<<i))
return ans;
};
https://leetcode.com/problems/valid-palindrome-ii/
class Solution {
public:
// Is s[left...right] a palindrome
if (s[left] != s[right])
return false;
left++; right--;
return true;
bool validPalindrome(string s) {
int i = 0, j = s.size() - 1;
while(i <= j) {
if (s[i] != s[j])
break;
i++; j--;
// Delete i or j
}
};
Week 4
Intro to Recursion
https://youtu.be/q3q9Yv-Q0OU
Memory Layout of Recursive stack
https://youtu.be/nJuIQqXXO-0
A call stack is composed of stack frames (also called activation records or activation
frames). These are machine dependent data structures containing subroutine (Next call)
state information. Each stack frame corresponds to a call to a subroutine which has not
yet terminated with a return
The stack frame at the top of the stack is for the currently executing routine. The stack
frame usually includes at least the following items (in push order):
Call by Value
In call by value, the argument expression is evaluated, and the resulting value is bound
to the corresponding variable in the function (frequently by copying the value into a new
memory region). If the function or procedure is able to assign values to its parameters,
only its local variable is assigned—that is, anything passed into a function call is
unchanged in the caller's scope when the function returns.
Call by Reference
Tribonacci Number
https://youtu.be/BPvV5PO2n9c
Code -
class Solution {
public:
int tribonacci(int n) {
if(n<=1) return n;
if(n==2) return 1;
// arr[n] =
tribonacci(n-1)+tribonacci(n-2)+tribonacci(n-3);
// return arr[n];
int a=0,b=1,c=1;
for(int i=0;i<n-2;i++){
int d=c;
c=a+b+c;
a=b;
b=d;
return c;
};
Add Digits
https://youtu.be/5_ruAT2rv-4
Problem link - https://leetcode.com/problems/add-digits/
Code -
class Solution {
public:
int ans=0;
while(num){
ans+=num%10;
num=num/10;
};
https://youtu.be/iwy7e-ynVtk
Backtracking framework
Subsets - Implementation
https://youtu.be/oCpZkzUiq5s
Code:
class Solution {
public:
// Base case.
// Construct C2.
vector<vector<int>> c2 = temp;
// Construct C1.
vector<vector<int>> c1;
temp[i].push_back(nums[start]);
c1.push_back(temp[i]);
// Construct S.
// S = c1 U c2.
vector<vector<int>> s = c1;
s.push_back(c2[i]);
// Return S.
return s;
int n = nums.size();
};
Combination Sum
Code:
class Solution {
public:
// Base cases.
// Smallest target.
// Recursive.
// Compute C2.
// Compute C1.
vector<vector<int>> c1;
c1.push_back(temp[i]);
res.push_back(c2[i]);
return res;
};
Framework revisited
Bookmark this page
Framework Revisited
https://youtu.be/zsjHSC9r8wI
Code:
class Solution {
public:
vector<vector<int>> res;
// Base cases.
if (target == 0)
res.push_back(contribution);
return;
// target <= 0.
if (target == 0) {
res.push_back(contribution);
return;
if (target < 0)
return;
// Recursive step.
// For c2 no contribution.
// For c1.
contribution.push_back(candidates[start]);
return res;
};
Code:
class Solution {
public:
vector<vector<int>> res;
if (n == 0 && k == 0) {
res.push_back(contri);
return;
if (n == 0 || k == 0 || n < 0)
return;
return;
// Recursive step.
// c1.
// c2.
contri.push_back(start);
f(1, 9, n, k, {});
return res;
};
Pruning
Combinations Explanation
https://youtu.be/TOD-v_9eAiM
https://youtu.be/2c0jvxSpiCk
https://youtu.be/qXcQGEr1rDA
Code:
class Solution {
public:
vector<vector<int>> res;
// Base case.
if (k == 0) {
res.push_back(contri);
return;
}
// k > 0.
return;
// Pruning step.
if (k > end-start+1)
return;
// Recursive step.
// c1.
// c2.
contri.push_back(start);
f(1, n, k, {});
return res;
};
Permutations
https://youtu.be/FBKIIttxZ_w
Permutations Implementation
https://youtu.be/fOIEcW6lir8
Permutations code
https://youtu.be/87avzO0yyco
https://youtu.be/yWYZXqCZyws
class Solution {
public:
vector<vector<int>> res;
void f(vector<int>& nums, vector<bool>& B, vector<int>
contribution) {
// Base case.
// Empty subset.
if (contribution.size() == nums.size()) {
res.push_back(contribution);
return;
// Recursive step.
if (B[i] == false)
continue;
contribution.push_back(nums[i]);
B[i] = false;
f(nums, B, contribution);
// Undo.
contribution.pop_back();
B[i] = true;
vector<int> contribution;
f(nums, B, contribution);
return res;
};
Palindrome Partitioning
https://youtu.be/_o48G97FiDs
https://youtu.be/_iT64Os_YmY
https://youtu.be/-aAEdhI0ojc
class Solution {
public:
bool isPalindrome(string&s) {
if (s[start] != s[end])
return false;
start++; end--;
return true;
vector<vector<string>> res;
// Base step.
res.push_back(contri);
return;
// Recursive step.
if (!isPalindrome(prefix))
continue;
contri.push_back(prefix);
contri.pop_back();
vector<vector<string>> partition(string s) {
vector<string> contri;
return res;
};
Practice Problems
Explicit decision:
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
https://leetcode.com/problems/wildcard-matching/
https://leetcode.com/problems/regular-expression-matching/
Subsets alike:
Basic to intermediate
https://leetcode.com/problems/subsets/
https://leetcode.com/problems/subsets-ii/
https://leetcode.com/problems/combinations/
https://leetcode.com/problems/combination-sum/
https://leetcode.com/problems/combination-sum-iii/
Intermediate to advanced
https://leetcode.com/problems/combination-sum-ii/
https://leetcode.com/problems/palindrome-partitioning/
https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
Arrangement alike:
https://leetcode.com/problems/permutations/
https://leetcode.com/problems/permutations-ii/
https://leetcode.com/problems/beautiful-arrangement/
Others:
https://leetcode.com/problems/restore-ip-addresses/
https://leetcode.com/problems/generate-parentheses/
Decisions on Matrices:
https://leetcode.com/problems/word-search/
https://leetcode.com/problems/unique-paths-iii/
https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/
https://leetcode.com/problems/sudoku-solver/
https://leetcode.com/problems/n-queens/
https://leetcode.com/problems/n-queens-ii/
https://leetcode.com/problems/permutation-sequence/
https://leetcode.com/problems/count-numbers-with-unique-digits/
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/
https://leetcode.com/problems/gray-code/
https://youtu.be/1BeKxavHc2o
WEEK 5:
https://youtu.be/sa9xbwkmnvk
Classification:
Bubble sort
https://youtu.be/GIMTEP3EWSc
Pseudocode Implementation
do
swapped := false
swapped := true
end if
end for
while swapped
end procedure
Selection sort
https://youtu.be/KJJlCp1SFvo
Algorithm
Effectively, we divide the list into two parts: the sublist of items already sorted
and the sublist of items remaining to be sorted.
Insertion sort
https://youtu.be/IrW-KGkgfzQ
Insertion sort is a comparison sort in which the sorted array (or list) is built one
entry at a time.
Algorithm
Every iteration of insertion sort removes an element from the input data, inserting
it into the correct position in the already-sorted list, until no input elements
remain. The choice of which element to remove from the input is arbitrary, and
can be made using almost any choice algorithm.
Sorting is typically done in-place. The resulting array after k iterations has the
property where the first k+1 entries are sorted. In each iteration the first
remaining entry of the input is removed, inserted into the result at the correct
position, thus extending the result.
Practise problem
https://youtu.be/yD_CaJzZEQw
Code -
class Solution {
public:
int n = nums.size();
// // Bubble
// for(int i=0;i<n;i++){
// for(int j=n-1;j>i;j--){
// if(nums[j]<nums[j-1]){
// swap(nums[j],nums[j-1]);
// }
// }
// }
// selection
// for(int i=0;i<n-1;i++){
// int min = i;
// for(int j=i+1;j<n;j++){
// if(nums[min]>nums[j]) min = j;
// }
// if(min!=i) swap(nums[min],nums[i]);
// }
// insertion
for(int i=1;i<n;i++){
int k = nums[i];
int j = i-1;
nums[j+1] = nums[j];
j = j-1;
nums[j+1]=k;
return nums;
};
https://youtu.be/eZ7XFVObovE
Problem - https://leetcode.com/problems/sort-characters-by-frequency/
Code -
// vector<int> freq(256,0);
// }
class Solution {
public:
string frequencySort(string s) {
vector<int> freq(256,0);
});
return s;
};
Problem - https://leetcode.com/problems/custom-sort-string/
Code -
string temp;
};
class Solution {
public:
temp = order;
sort(str.begin(),str.end(),compare);
// return order.find(a)<order.find(b);
// });
return str;
};
Problem - https://leetcode.com/problems/largest-number/
Code -
class Solution {
public:
});
string s="";
return s;
};
Code -
class Solution {
public:
unordered_map<int,bool> vs;
vector<int> v;
for(int i=0;i<nums2.size();i++) {
if(vs[nums2[i]]==true){
v.push_back(nums2[i]);
vs[nums2[i]]=false;
return v;
}
};
Practise Problems
Interval Handling
https://leetcode.com/problems/merge-intervals/
https://leetcode.com/problems/meeting-rooms/
https://leetcode.com/problems/meeting-rooms-ii/
https://leetcode.com/problems/non-overlapping-intervals/
https://leetcode.com/problems/insert-interval/
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/
Counting sort
https://youtu.be/TtFKDT68yfc
It can be proved that a sorting algorithm that involves comparing pairs of values
can never have a worst-case time better than O(N log N), where N is the size of
the array to be sorted. However, under some special conditions having to do with
the values to be sorted, it is possible to design other kinds of sorting algorithms
that have better worst-case times. Three such algorithms are discussed here:
1. Bucket Sort
2. Counting Sort
3. Radix Sort
Counting Sort
● Use an auxiliary array of integers, aux, of size k. aux[0] will hold the
number of times the value min occurs in A; aux[1] will hold the number of
times the value min+1 occurs in A; etc. All entries in aux are initialized to
zero.
● Step 1: Go through array A once; for each value v, increment aux[v-min].
● Step 2: Go through the aux array once; for each index j, put aux[j] copies of
the value min+j back in A.
Bucket sort
https://youtu.be/P8X1uzrXq9E
1. The values to be sorted are evenly distributed in some range min to max.
2. It is possible to divide the range into N equal parts, each of size k.
3. Given a value, it is possible to tell which part of the range it is in.
Note that conditions 2 and 3 hold for numeric values, but not necessarily for
other kinds of values (like strings).
Radix sort
https://youtu.be/A66_Ts4NRHI
To do a radix sort, simply sort on each sequence position in turn, from right to
left, using a stable sort.
Maximum Gap
https://youtu.be/GoBm2OWEfZU
Problem Link - https://leetcode.com/problems/maximum-gap
class Solution {
public:
int n = nums.size();
vector<vector<int>> bucket(n+1);
if(minVal==maxVal) return 0;
for(int i=0;i<n;i++){
bucket[index].push_back(nums[i]);
for(auto b:bucket){
sort(b.begin(),b.end());
for(int i:b){
maxSum = max(maxSum,i-prev_val);
prev_val = i;
return maxSum;
};
Practise Problems
https://leetcode.com/problems/k-closest-points-to-origin/
https://leetcode.com/problems/maximum-gap/
https://youtu.be/A75suSN2AhE
Merge Sort Algorithm
https://youtu.be/tugHzShLEaI
Algorithm
1. A small list will take fewer steps to sort than a large list.
2. Fewer steps are required to construct a sorted list from two sorted lists
than two unsorted lists. For example, you only have to traverse each list
once if they're already sorted.
MergeSort(A, 0, n/2)
https://youtu.be/3g7RtnVetwU
Algorithm
Quicksort sorts by employing a divide and conquer strategy to divide a list into
two sub-lists.
function quicksort(array)
var list less, greater
if length(array) <= 1
return array
Reverse Pairs
https://youtu.be/ZBFzmj87TCg
Code -
class Solution {
public:
if(end-start<=1) return;
merge_sort(start,mid);
merge_sort(mid,end);
for(itr i=start,j=mid;i<mid;i++){
cnt+=j-mid;
inplace_merge(start,mid,end);
}
merge_sort(nums.begin(),nums.end());
return cnt;
};
Sort colors
Problem Link - https://leetcode.com/problems/sort-colors/
Code -
class Solution {
public:
int n = nums.size();
for(int i=0,j=0;i<n;i++){
if(nums[i]<pivot){
swap(nums[i],nums[j++]);
}
int pivot = 1;
partition(nums,pivot);
pivot = 2;
partition(nums,pivot);
};
Practise Problems
Quick Sort:
https://leetcode.com/problems/wiggle-sort-ii/
https://leetcode.com/problems/sort-colors/
Merge Sort:
https://leetcode.com/problems/reverse-pairs/
https://leetcode.com/problems/count-of-smaller-numbers-after-self/
https://leetcode.com/problems/count-of-range-sum/
https://leetcode.com/problems/h-index/
https://leetcode.com/problems/car-fleet/
https://leetcode.com/problems/rearrange-words-in-a-sentence/
https://leetcode.com/problems/diagonal-traverse-ii/
https://leetcode.com/problems/reorganize-string/
https://leetcode.com/problems/queue-reconstruction-by-height/
https://leetcode.com/problems/h-index/
DPP Link -
https://docs.google.com/document/d/1bw85-nPAz4XqaTVw2VGhDiySio5hmn5GR
mO3PG5tcww/edit?usp=sharing
DPP On Arrays
DPP Link -
https://docs.google.com/document/d/1YGBGGCxXg0d-cRzV2lluMu_7Z2dpmbveF
Es6I2pNgMI/edit?usp=sharing
https://youtu.be/ApIJAr_TTGk
WEEK-6
Linked Lists
https://youtu.be/I9w0tnJYdPk
https://youtu.be/X1RC80w18Ig
/**
* struct ListNode {
* int val;
* ListNode *next;
* // Constructors
* };
*/
class Solution {
public:
slow = slow->next;
fast = fast->next->next;
}
return slow;
};
Traversal contd..
https://youtu.be/PINt4EtcJYY
https://youtu.be/Hm8IojIBv68
Problem Statement:
https://leetcode.com/problems/intersection-of-two-linked-lists/
/**
* int val;
* ListNode *next;
* };
*/
class Solution {
public:
ListNode* t1 = headA;
ListNode* t2 = headB;
while(t1 != t2) {
if (t1 == NULL)
t1 = headB;
t2 = headA;
else {
t1 = t1->next;
t2 = t2->next;
return t1;
};
Cycle Detection
https://youtu.be/hNlu4H3DSeg
https://youtu.be/JALdi7ZPk6Q
Problem Statement: https://leetcode.com/problems/linked-list-cycle/
/**
* struct ListNode {
* int val;
* ListNode *next;
* };
*/
class Solution {
public:
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
return false;
};
https://youtu.be/jm1vxLzAOXs
https://youtu.be/YNMZR5tu3xA
Problem link: https://leetcode.com/problems/linked-list-cycle-ii/
Code:
/**
* struct ListNode {
* int val;
* ListNode *next;
* };
*/
class Solution {
public:
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
break;
// No Cycle.
if (!fast || !fast->next)
return NULL;
// Cycle.
slow = head;
while(slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
};
/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode* O = NULL;
ListNode* t = head;
while(t) {
t->next = O;
O = t;
t = temp;
}
return O;
};
/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode dummy;
tail->next = t1;
t1->next = NULL;
t1 = temp;
tail = tail->next;
} else {
tail->next = t2;
t2->next = NULL;
t2 = temp;
tail = tail->next;
if (t1)
tail->next = t1;
if (t2)
tail->next = t2;
return dummy.next;
}
};
Practice Problems
Bookmark this page
https://leetcode.com/problems/find-the-duplicate-number/
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
https://leetcode.com/problems/reverse-linked-list-ii/
https://leetcode.com/problems/palindrome-linked-list/
https://youtu.be/zNLD1vLBqkQ
https://youtu.be/CX_KNjOq-II
/**
* struct ListNode {
* int val;
* ListNode *next;
* };
*/
class Solution {
public:
ListNode *t = head;
int count = 0;
while(t) {
count++;
if (count&1) {
odd_tail->next = t;
ListNode *temp = t->next;
t->next = NULL;
t = temp;
odd_tail = odd_tail->next;
} else {
even_tail->next = t;
t->next = NULL;
t = temp;
even_tail = even_tail->next;
odd_tail->next = even_head->next;
return odd_head->next;
}
};
/**
* struct ListNode {
* int val;
* ListNode *next;
* };
*/
class Solution {
public:
slow = slow->next;
fast = fast->next->next;
while(second_half) {
// Insert elements to the front.
second_half->next = reversed_list;
reversed_list = second_half;
second_half = temp;
ListNode dummy;
output_tail->next = first;
first = temp;
output_tail = output_tail->next;
output_tail->next = second;
temp = second->next;
second->next = NULL;
second = temp;
output_tail = output_tail->next;
if (first == second) {
output_tail->next = first;
first->next = NULL;
output_tail = output_tail->next;
}
head = output_head->next;
};
Practice Problems
Bookmark this page
https://leetcode.com/problems/add-two-numbers/
https://leetcode.com/problems/add-two-numbers-ii/
https://leetcode.com/problems/partition-list/
https://leetcode.com/problems/insertion-sort-list/
Stacks Introduction
Stacks Introduction
https://youtu.be/dwMzqbvTdao
Expression Evaluation
Bookmark this page
Code:
class Solution {
public:
stack<int> s;
s.push(stoi(tokens[i]));
continue;
s.pop();
s.pop();
// Apply.
if (tokens[i] == "+")
s.push(op1 + op2);
s.push(op1 - op2);
else
s.push(op1 / op2);
return s.top();
};
Problem link:
https://leetcode.com/problems/basic-calculator-ii/
Code:
class Solution {
public:
return true;
int calculate(string s) {
s += " ";
vector<string> postfix;
stack<char> st;
continue;
if (curr_num != "") {
postfix.push_back(curr_num);
curr_num = "";
continue;
postfix.push_back(string(1, st.top()));
st.pop();
}
st.push(s[i]);
while(!st.empty()) {
postfix.push_back(string(1, st.top()));
st.pop();
stack<int> st2;
st2.push(stoi(postfix[i]));
continue;
}
int op2 = st2.top();
st2.pop();
st2.pop();
if (postfix[i] == "+")
st2.push(op1 + op2);
st2.push(op1 - op2);
st2.push(op1 * op2);
else
st2.push(op1 / op2);
return st2.top();
}
Practice Problems
https://leetcode.com/problems/basic-calculator/
https://leetcode.com/problems/simplify-path/
https://leetcode.com/problems/decode-string/
https://leetcode.com/problems/longest-absolute-file-path/
};
Monotonic Stacks
Code:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
stack<int> s;
int n = T.size();
res[s.top()] = i - s.top();
s.pop();
s.push(i);
while(!s.empty()) {
res[s.top()] = 0;
s.pop();
}
return res;
};
Problem link:
https://leetcode.com/problems/largest-rectangle-in-histog
ram/
Code:
class Solution {
public:
stack<int> s;
// Find out all the elts for which A[i] is the ans.
next_small[s.top()] = i;
s.pop();
s.push(i);
while(!s.empty()) {
next_small[s.top()] = n;
s.pop();
}
// Previous smaller elts.
previous_small[s.top()] = i;
s.pop();
s.push(i);
while(!s.empty()) {
previous_small[s.top()] = -1;
s.pop();
int max_area = 0;
for (int i = 0; i < n; i++) {
// 2 -- previous small
// 5 -- next small
// width = 2
return max_area;
};
Practice Problems
●
https://leetcode.com/problems/next-greater-element-ii/
Largest Rectangle in Histogram - LeetCode
https://leetcode.com/problems/maximal-rectangle
https://leetcode.com/problems/daily-temperatures/
https://leetcode.com/problems/sum-of-subarray-minimums/
https://youtu.be/uM8XpyBG7JY
WEEK 7:
Data modeling
Code:
class Solution {
public:
long q, r;
while(num) {
q = num/den;
r = num%den;
if (history.find(num) == history.end()) {
history[num] = decimal.size();
decimal += to_string(q);
num = r*10;
else {
// Insert brackets
if (numerator == 0)
return "0";
decimal += "-";
long q = num/den;
long r = num%den;
decimal += to_string(q);
if (r == 0)
return decimal;
decimal += ".";
return decimal;
};
Group Anagrams
The Problem can be viewed and practiced here:
https://leetcode.com/problems/group-anagrams/
Code:
class Solution {
public:
string getGroupId(string& s) {
for(const auto& ch : s) {
freq[ch-'a']++;
return res;
}
// Define history
vector<vector<string>> res;
if (history.find(g_id) == history.end()) {
res.push_back({});
history[g_id] = (int)res.size()-1;
res[history[g_id]].push_back(ana);
}
return res;
};
Problem: https://leetcode.com/problems/max-points-on-a-line/
Code:
class Solution {
public:
if (b == 0) return a;
r = 0;
lines.clear();
if (i == j) continue;
if (num == 0) {
lines["0/1"]++;
r = max(r, lines["0/1"]);
continue;
if (den == 0) {
lines["1/0"]++;
r = max(r, lines["1/0"]);
continue;
// Normalize.
num /= hcf;
den /= hcf;
string slope =
to_string(num)+"/"+to_string(den);
lines[slope]++;
r = max(r, lines[slope]);
}
return res;
};
Link: https://leetcode.com/problems/copy-list-with-random-pointer/
Code:
/*
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
};
*/
class Solution {
public:
Node dummy(-1);
while(curr_old) {
prev->next = temp;
history[curr_old] = temp;
// Update prev
prev = prev->next;
// Update curr
curr_old = curr_old->next;
curr_old = head;
while(curr_old) {
curr_new->random = history[curr_old->random];
curr_old = curr_old->next;
curr_new = curr_new->next;
}
return new_list->next;
};
Brick Wall
Link: Brick Wall - LeetCode Brick Wall - Understanding the Problem Hint 1 Hint 2 code
Link: https://leetcode.com/problems/brick-wall/
Code:
class Solution {
public:
// History.
// Level by level
pos += wall[i][j];
history[pos]++;
return (int)wall.size()-max_val;
};
View of subarrays subarray with sum k -hint 2 subarray with sum k - hint3 subarray with sum k
-Hint 4 subarray with sum k - code
Link: https://leetcode.com/problems/subarray-sum-equals-k/
Code:
class Solution {
public:
unordered_map<int, int> m;
m[0] = 1;
total += nums[i];
res += m[total-k];
m[total]++;
return res;
}
};
Link: https://leetcode.com/problems/subarray-sum-equals-k/
Code:
class Solution {
public:
unordered_map<int, int> m;
m[0] = 1;
total += nums[i];
res += m[total-k];
// Insert this prefix sum into the history.
m[total]++;
return res;
};
Practice Problems
Hash Tables:
https://leetcode.com/problems/max-points-on-a-line/
https://leetcode.com/problems/subarray-sum-equals-k/
https://leetcode.com/problems/subarray-sums-divisible-by-k/
https://leetcode.com/problems/group-anagrams/
https://leetcode.com/problems/fraction-to-recurring-decimal/
https://leetcode.com/problems/prison-cells-after-n-days/
https://leetcode.com/problems/contiguous-array/
Frequency counting:
https://leetcode.com/problems/brick-wall/
https://leetcode.com/problems/rabbits-in-forest/
Lower and upper Bound My calendar - understanding the problem My calendar - Hint 1 My
calendar - Hint 2
Code:
class MyCalendar {
public:
map<int, int> m;
MyCalendar() {
auto it = m.lower_bound(start);
return false;
if (it != m.begin()) {
--it;
return false;
m[start] = end;
return true;
};
/**
*/
Practice Problems
Minimum Size Subarray Sum - LeetCode My Calendar II - LeetCode