0% found this document useful (0 votes)
18 views3 pages

LeetCode Dynamic Programming Notes

The document contains a list of coding problems categorized by their respective topics, such as Array, HashMap, Sorting, and Dynamic Programming, along with their links and brief notes on the approaches to solve them. Each entry provides a concise explanation of the algorithmic strategy to tackle the problem. The problems range from basic to advanced levels, covering various concepts in computer science and algorithm design.

Uploaded by

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

LeetCode Dynamic Programming Notes

The document contains a list of coding problems categorized by their respective topics, such as Array, HashMap, Sorting, and Dynamic Programming, along with their links and brief notes on the approaches to solve them. Each entry provides a concise explanation of the algorithmic strategy to tackle the problem. The problems range from basic to advanced levels, covering various concepts in computer science and algorithm design.

Uploaded by

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

Topic Question Name Question Link Note

Array + HashMap Two Sum [Link] Use a hashmap calculate the needed value[target - currVal] if found store ans. Always put the currVal in the map pair with index
store all the remainder with their count in a map. To make negative number pos before storing rem = (ele % k + k) % k. After this
Check array pair are divisible by traverse the map. if count 0 skip. if rem == 0 and count of this rem is not even then pair not possible so return false. Otherwise
Array + HashMap [Link]
k find the complements = k - rem. If count of complement is less than rem count then also pair is not possible. otherwise reduce
count amount of complement_count
convert all times in mintues and store in a array then sort the minuteArray and find the minDifference. Before returning answer
Array + Sorting Minimum Time difference [Link]
check for circular time. ans = min(ans , 1440-arr[n-1] + arr[0])
make a comparetor which will sort to string. Add two string and compare them as sort in ascending. Then just go through the new
Array + Sorting Largest Number [Link]
array and concat all string_num and return ans. edge case it ans[0] == '0' return "0"
first sort the array. Now use 2 pointer left and right. If ele_left + ele_right == prev then store it in ans else return -1. APPROCH-
Divide Players Into Teams of 2: Find the target = total_sum / (total_ele / 2). Now store all the ele in a map. and traverse every ele of the array and search it's
Array + Sorting [Link]
Equal Skills pair such that currEle + X == target and currEle index != X index OR we also can ele and count in map. If find then store as ans
else return -1
Take a prefix array and store all the prefix product excepts self. Same do for postfix array. Store all the postfix product
Prefix_Postfix Product of array except self [Link]
excpects ele. Then take ans array. ans[i] = prefix[i]*postfix[i]
find the longest prefix Palindrome. start from last index and check is palindrome or not. If not then decrease index by one. If
String Shortest Palindrome [Link]
palindrome then break. take the non-palindrome part. from index-J to n and then reverse it. And add with the given string
Dynamic Programming Dp Articals [Link] leetcode Artical: [Link]
take dp vector n+1 , n. use recursion + memoization. Use a for loop to calculate ans. loop range 1 to sqrt(n) and ans = minimum of
Dynamic Programming perfect Squares [Link]
ans and 1 + subProblem ans
calculate for single , take day and increment day by seven and calculate for weekly then save min of oneday , weekly and monthly in
Dynamic Programming Minimum Cost For Tickets [Link]
memo part
Dynamic Programming climbing Stairs [Link]
Using memoization: take base case for n == 0 or 1 ans is 1 for n < 0 ans is 0. ans is total sum of taking one step and two steps
Spce Optimized Method: Minimize the buyPrice and maximize the profit. Tabulation:Use dp array of pair to store min buy and max
Dynamic Programming buy and sell stock i [Link]
profit. always take value from yesterday price and if needed then update
take bool type dp array initialize with false , traverse 2 to n and find the x[use to loop 1 to less than i] if i is divisible by x and dp
Dynamic Programming Divisor Game [Link]
[i-x] is false set dp[i] as true and break at last return dp[n]
take dp array of n size. Base case: if we reach last of the string or out of bounds return 1. Take one digit or 2 digit(only if less
Dynamic Programming Decode Ways [Link]
than equal 26). For 1 digit call as index+1 , for double digit check the condition and call index + 2
Precalculate all values. Use the a loop for to calculate every value and nested loop for dice(1 to 6) and add the result arr[i] += arr
Dynamic Programming Dice Combinations [Link]
[j-i]
Tabulation: calculate 1 to target and store ans. Use nested loop. loop2 for every coins if(i-coins >= 0) and also subAns != INF then
Dynamic Programming Minimize Coins [Link]
update i-th dp ans
Memo: 2 points include curr or exclude curr , update ans arr[currIndex] as max(include , exclude) and return ans . Space
Dynamic Programming Max Sum of non-adjacent [Link]
Optimize: Use 2 variable prev1 and prev2. prev1 -> include , prev2 -> exclude
Solve 1 subproblem. So then there will be (n-1) subproblem. ans = (n-1)*subProblem. There will be 2 case. case1:do for (n-1) , c2: do
Dynamic Programming Count Dearangements [Link]
for (n-2). Ans of subProblem = c1 + c2
Dynamic Programming Coin Combination 1(TLE) [Link]
take base case as n == 0 is 0 and n < 0 is -INF cause can't cut. Save the max of cutting x , y , z and save as 1 + max(ax , by , cz)
Dynamic Programming Cut Into Segments(Rod Cut) [Link]
and return
for n == 0 ans is 0 , n out of bound return -INF. Calculate for sigle day , go forward 7 days and calculate for 7 days also do for 30
Dynamic Programming Ninja's Trip [Link]
days. Store ans minimum of these 3 values
Memoization: include and the exclude the currIndex and take max of these two and store ans. From main function call for every
Dynamic Programming House Robber [Link]
index and track the max ans.
two case: Case-01: 2 adj will be the same color , if same then their remain only n-2 , Case:02: 2 adj will be diff color so there will
Dynamic Programming Paint Fence [Link]
be n - 1 remain. ans will be (2Same + diff)*(k-1). Base case: n == 0 is 0 , 1 fence can be paint by k types and carefully calculate the
value of n==2.
2D Dp[cause 2 parameter is changing Index and capacity] Use 2d array as Dp arr. if lastIndex weight in the capacity then take it
Dynamic Programming 0 1 Knapsack [Link]
else return 0. 2Case: include currIndex or exclude take the max as ans. Before including check capacity
Largest Square formed in a use dp array. calculate for currRow , currCol. find ans from right , down , diagonal . Store 1 + min(right , down , diagonal) and store
Dynamic Programming [Link]
matrix ans and return. Do the same thing for every row , col index and ans will store max of all of these
start from 0-th and (n-1)-th index and take an 2d dp array. if firstIndex comes to the last before then return 0. Otherwise
Minmum Score Triangulation of
Dynamic Programming [Link]
calculate for min ans from i + 1 to j -1 and take the min as the mainANs and store. ALso relation will be multi of 3 value + solve(i to
Polygon
k) + solve(k to j)
in helper func check we reached or not. if reached return 0. check next position is safe or not. if safe go to next pos and return .
Dynamic Programming Minimum SideWay Jumps [Link]
If not safe then find min ans for all safe jump. [check don't jump at same lane and unsafe position]
Similiar as 01 Knapsack. Include the currIndex or exclude the currIndex. If include then increase the time. store ans the max
Dynamic Programming Reducing Dishes [Link]
(include , exclude). NOTE: Sort the array first
Dynamic Programming Longest Increasing Subsequence [Link]
Minimum Path Sum[Pattern:
Dynamic Programming [Link]
start from the [0,0] , choose right , down find min of right , down and add currPos and store.
Max/Min]
start from index[0,0] base case if out of bounds retuns 0. we have 2 choice take currCol , take currCol+1 and row+1. Then min sum
Dynamic Programming Triangle[Patteren: Max/Min] [Link]
of arr[currRow][currCol] + min_of_2_choice. STore and Return the ans.
we have 2 choice. Either we can copy or paste. Copy only when currResource is not equal to currRecourse. Paste only when
2-keys KeyBoard[Patteren:
Dynamic Programming [Link]
currRecource is greater zero. When copy currResource will be same as copyLen. For paste currResource remains same bu currLen
Max/Min]
increased
cal the total sum, then divide into 2 part and try to get any part like the knapsack problem. Try to find part1. If currSum >= part1
Dynamic Programming Last Stone Weight2[Min/max] [Link]
or out of bounds return abs(currsum-(totalSum-currSum)) then same as include or exclude and min part as knapsack
take an 3d array[index , m , n] Include the currIndex or exclude and take the max. Before take include check can we include or
Dynamic Programming Ones and Zeroes [Link]
not. count0 or 1 is greater than m,n then dont include
Unique Paths[Pattern: Distinct if reached return 1 , if any row or col out of bounds no valid paths retun 0. go right and find paths , also for down paths. Sum up all
Dynamic Programming [Link]
Ways] right and down and store and return
if reached return 1 , if any row or col out of bounds no valid paths retun 0. go right if there is no obstacles and find paths , also
Unique Paths 2 [Pattern: Distinct
Dynamic Programming [Link]
for down paths. Sum up all right and down and store and return. Edge Case: if there is 1 at destination position or starting position
Ways]
there no path retun 0
Target Sum[patter: Distinct take a map string , int cause 2 sate is changing index and currSum. So make the by combining index and currSum. return 1 on;y
Dynamic Programming [Link]
Ways] when all ele taken and currSum == target else 0.
Combination Sum IV[Pattern:
Dynamic Programming [Link]
base case: target == 0-->1 way. target < 0-->0 ways. cal ans for every ele and sum and store as dp[target] = ans.
Distinct Ways]
number of dice roll to get target base case: currDice is out of bounds and target == currSum the retun 1 else 0. otherwise ans += solve(). Make sure whille adding i
Dynamic Programming [Link]
[Distinct Ways] to the currSum it doesn't cross target. if(i+currsum <= target) only in this case call the function. dp<n+1 , target+1>
Base Case: move<0 reutn 0 , out of bounds return 1, check dp array. Otherwise calculate for 4 direction ans sum up all . Store and
Dynamic Programming Out Of Boundary[Dictinct Ways] [Link]
return
Dynamic Programming
Dynamic Programming
Dynamic Programming Unique Binary Tree[1D] [Link]
intialize the base case as 0 or less than 1. Take 1 to n-1 as leaf. left and right. ans += left * right. Loop int helper 0 to n-1
Dynamic Programming
Rod Cutting[Unbounded check we can cut or not. if cut then call next for the same index , else call for by updating the index. Take and max of these 2. If
Dynamic Programming [Link]
Knapsack] cut then add the price and update the lenOfRod
check we can take the coins[index] ir not. if we can then take. if taking not return INF then add 1 to take. call for dont Take and
Dynamic Programming coins Change 1 [Link]
stone min of these [Link] take dont update the index cause under proccesing as it's unbounded kanpsack. if not take update the
index
coins Change 2[Unbounded + check can we take currIndex con or not. If can means under proccess dont change index just change sum. If not then call for
Dynamic Programming [Link]
total Ways] next. return take+notTake cause they asked for all ways or total ways
Longest Common Subsequence take a dp array dp[n+1][m+1]. 2 nested loop 1 to last and if(s1[i-1] == s2[j-1] --> 1+dp[i-1][j-1](Diagonal value) else take the max of
Dynamic Programming [Link]
Length [LCS} (i-1 , j) and (i , j-1)
Longest Palindromic Subsequence
Dynamic Programming [Link]
make a copy of s1 to s2 and reverse it. same as longest xommon subsequence
Length [LCS}
same as subsequence but maintain an maxLen to track the ans and in else case dp[i][j] will be 0. ans always update ans = max(ans ,
Dynamic Programming Longest Common Substring [Link]
dp[i][j]) in the if check part
Min Deletion to make a string
Dynamic Programming [Link]
Find the Longest palindromic subsequence and return length_of_string - LPS
palindrome{Pattern: LCS}
Use a 1d array dp. If we are at out_of_bound or at last index return true. Check pre_cal. maxJump = min(index + arr[index] , n -
Dynamic Programming jump game [Link]
1). Now use loop index + 1 to maxJump.
Dynamic Programming jump game 2 [Link]
Use a dp array. If we reached then return 0. Otherwise try every jump possible from 1 to arr[index] ans take the minAns.

Sort the [Link] [Link](sum == target) store sub , if(sum > target || currIndex >= n) return. Start from currIndex and apply
Backtracking Combination Sum 2 [Link]
[Link]: Skip taking same i use a if statement. We can also do it using take currIndex and Not take currIndex , no need
of any loop any where. Just need to increment dublicates of currIndex[Use a while loop]
Backtracking Combination Sum 1 [Link]
use a loop in main function. In solve use same as previous one. No need of any dublicate check
do not need of any loop , maintain currIndex. two dicision include or exclude if include mark as visited and while returning make
Backtracking Subset [Link]
sure to undo
make a helper and pass sub , arr , vis. In helper use a loop from 0 to n-1. if not visited then include in the subAns and mark as
Backtracking Permuations [Link]
visited and call helper. Then again undo
Count number of maximum first calculate the value of all elements or operation[this is the maxValue]. Now instead of genarting all the subsets just
Backtracking [Link]
bitwise-OR subsets ccalculate the OR value like subsets. Base Case: if(currIndex == n) then increase count if currValue == maxValue
Backtracking
Backtracking
Backtracking

if just a single or double digit store in ans and return. else use a for loop 0 to n-1. If digit skip. If operator then take 2 array left
Recursion diff ways to add parenthesis [Link]
and right. Make two substr left and right and call self. there use use nested loop on left and right array calculate ans and return

Graph Graph Graph Graph


Use Dijktra use minHeap with effort and (row , col) . if we reached then return effort. traverse all neiNode don't visited set.
Dijktra Minimum path effort Maintain effortOfRowCol [Link] in heap only if effort of node is greater than effort neiNode. CurrentEffort will be max of
[Link]
(nodeEffort , currEffort)
use Dijktra. No need of visited cause directed graph. At the end find the maxTime. if maxTime == INT_MAX return -1. Ignore
Dijktra Network Delay Time [Link]
index 0 cause node starts from 1
Find City with smallest num of Use dijktra for every vertex and find distance array and then traverse dis array and countCitites . if mainCityCount < currCount ||
Dijktra [Link]
neibours (mainCityCount == currCount && ans < src) then update ans and mainCityCount
Use dijktra based on highest probalility[Use Heap instead of MinHeap]. Take the top of Heap if node == end_node then return
Dijktra Path with max probalility [Link]
prob_of_node otherwise go through every neighbours if nodeprob * neiNodeProb < prob[neiNode] then update. If we not return
from BFS means there is no edge from start to end so return 0
make the adj with u to v with cost. Track cost, stops. In minHeap track cost , node and stops. If we reached return cost , if stops
Dijktra cheapest Flights with k stops [Link]
[node] exceeds k then skip the path. if cost[neiNode] < neiNodeCost + nodeCost Or stopNode + 1 < stops[neiNode] then update
cost of neiNode and stops of neiNode. At the end we can't reach dest then return -1
Dijktra
Dijktra
Dijktra
Dijktra
make the adjList([Link]()). there we store u to v and vice versa with distance as weight. i to j with w wieght and j to i with w
Dijktra Min Cost to connect All points [Link]
weight. Then just apply prim's algo
BFS Number of Islands [Link]
Use BFS Like disconnected components and each call for bfs increase count by 1
find the adj list map<string , vector<string , double>> adj. Then use DFS / BFS for every query where query is src and dest. Like
BFS Evaluate Division [Link]
find distance from src to dest in a DAG
Dont need of any adjList. Use BFS and find the friends of desired levels and then count the movies of desired levels and then
BFS Get Watched Videoes By Friends [Link]
push the map ele in a minheap. Then traverse the minHeap and store the movies and return
count number of fresh orange and also add all rotten orange in queue. Then do level order traversal and if neiNode is fresh orange
BFS Rotting Oranges [Link]
then rot it and decrease [Link] a is_rotten flag After completing one level update time by one if is_rotten is true.
while(![Link] && countFresh > 0) do this thing. At the end if countFresh is 0 then return time else -1
treat it as a undirected graph. So make the adjList as UDG but also store the original edges in a set. use BFS and traverse the
Reorder Routes to make all paths
BFS [Link]
neinode. If neiNode is not visited push in the queue then if the body of same if check next if. *If there is node from node to
lead to the city
neiNode in the set then we have to reorder it so count++. Dont make any change in the set.
Do bipartition. If vis[neiNode] == 0 , mark vis[neiNode] = -1 * vis[node] and call dfs. If dfs return false then return. Condition of
Bipartiate Possible Bipartition [Link]
conflict: if vis[node] == vis[neiNode] it's a conflict so partition is not possible return false. At the end return true.
Nearest Exit from Entrance in Use BFS. in a queue store starting points and dis. if currRow is the exit point retun dis. otherwise traverse the 4 direction if
BFS [Link]
Maze neiNode if node entrance and not vis and also not border then store it in the queue. neiNode_dis = nodeDis + 1. At last return -1
Dijktra
Dijktra
Dijktra
Dijktra
Dijktra
Dijktra
Dijktra
Dijktra
Dijktra
Dijktra

Trie Impement Tire [Link]


Use DFS. from main call dfs for 1 to 9. In DFS function check base case if currNum is greater than n then return. Otherwise
Trie Lexiographical Numbers [Link]
store currNum. Then also go for 1 to 9 like: currNum * 10 + i then if this is limit then call dfs else break
sort the array. Use a prev and curr. If prev is empty then take the curr and update prev. If curr starts with prev then also take it
Trie Remove SubFolder [Link]
as ans. If curr of [Link] index is not equal '/' then also take it as ans

Condition of overlap: Start1 <= end2 and start2 <= end1 Then it's a overlapping interval

Store intevals. Before adding new Interval Every time check is there any Overlap or not. If no overlap then add else skip. Method-
Intervals My Calender 1 [Link]
2: Using BST. Use curr If overlap then return false. If start >= curr->start go right else go left. Before going check if null or not.
If nul then insert the new intervel and return
Intervals My Calender 2 [Link]
Intervals non-Overlapping Intervals [Link]
Sort Based on the Ending [Link] is ending first. Then if overlap then update and take smallest ending. Else update ending
Take all intervals which ends before newInterval. Then merge all the intervals which overlap with newInterval and make a single
Intervals Insert Intervals [Link]
interval[update newInterval]. Then take the newInterval. Then take all the remains intervals
Sort based on the starting value. Then go throug every interval if overlap then just merge it dont take in ans. If it not overlap
Intervals Merge Intervals [Link]
then take it as answer. Don;t need to check starting position cause already sorted.

Binary Search Binary Search Binary Search Binary Search


if arr[mid] == x then we got both floor and ceil so return it. if arr[mid] > X then it can be a ceil so update ceil and go to left part
BS On 1D Array Ceil The Floor [Link]
to find more smaller value. If arr[mid] < X then it can be a floor so update it. And go to the right part to get more greater value
First find the 1st occ then 2nd occ. Finding 1st occ. If arr[mid] == target then update ans and go to left part to find more smaller
Find The first and last position
BS On 1D Array [Link]
index. Similiarly while finding last Occ if arr[mid] == target go to the right part to find the last Occ. For both search if arr[mid] >
of ele in Sorted array
target go the left part else go to the right Part
BS On 1D Array number of Occurrence [Link]
Similiar as prevois one. Find first and last occ if ele not fount return 0 else return lastPos - firstPos + 1
if arr[mid] == target then return mid. Otherwise we have to eliminate one part. Check which part is sorted. if(arr[left] <= arr
BS On 1D Array Search in rotated sorted array [Link]
[mid]) then left part is sorted else right part is sorted. Now check is target lies in the sorted portion? always use <= and >= equal
size must. If it lies in sorted portion then eliminate unsorted part else eliminate sorted part
check if arr[left] == arr[mid] == arr[right] at this point we can tell which part is sorted so shring both left , right by one. Rest of
BS On 1D Array Search in rotated sorted array 2 [Link]
the part is same as previous one
check which part is sorted. if left part is sorted then take the min from the left and move to the right else take min from the
BS On 1D Array Find Min in rotated sorted array [Link]
right and move to left. Left range: left to mid. Right range: mid to right
Find Kth rotation / how many
BS On 1D Array [Link]
Basically it's similar to previous one. But instead of finding minEle we have to find the index of minEle and return it
time rotated
Think like a graph curve. check 1st and last element explictly. Then always find mid if mid is peak return it. Otherwise check is mid
BS On 1D Array Find Peak Element [Link]
is at increasing curve or decresing curve. if in increasing curve go right else go left
BS On 1D Array
BS On 1D Array
BS On Answers Floor Square root [Link]
if mid * mid == n return mid. if mid * mid < n then then try to maximize the answer ans and move to right. Else move to left
BS On Answers N-th Root [Link]
Make a pow(x , n,limit) function. If currAns cross the limit don't go forward back to binary part and update right to lower part.
To avoid overflow use lli. Left = 1 and right = maxElement. then applu BS and insize the BS count the totalHour needed for
BS On Answers Koko Eating Bananas [Link]
currSpeed. hour += (ele + currSpeed - 1)/currSpeed to avoid make ceil division. if we are in time limti take min time as ans and
move left to get more small value otherwise go to the right part
Take right as the maxBloomDay and left = 1. if m*k > n then not possible so return -1[here we need to handle overflow so instead
BS On Answers Minimum Number of days to [Link]
of n < m* k use n/k > m. Then use binary search. Also we have to take adjacent k flower not random k flower so if there is any
make m Bouquets flower that doesn't bloom reset the flowerCount.
Find The Smallest Divisor Given Take right as maxEle and left as 1 and perform BS in the range of left to right. If we are in the thresold then take min of ans and
BS On Answers [Link]
a Thresold currSum and go left to minimize it more else go right to get a valid answer. Note: have a look on division
Capacity to ship package within Find what can be upper and lower bound of capacity. Apply BS on this range. I have to at least 1 product so minWeight can be the
BS On Answers [Link]
days maxEle. If days is 1 then i have to all product at once. So maxEle is the lower bound and totalWeight is the upper bound.
First find the row then find the col. if target lies in the midRow then take the row and break. If ansRow remains invalid return
BS On 2D Array Search in a matrix [Link]
false. Otherwise after finding row find the col.
Start BS with first and last col. Every time find the max ele of the mid col basically row index of mid col. Now check is it a peak
BS On 2D Array Search in a matrix ii [Link]
of not. if peak return else move col. If we are at decreasing curve go left else go right of the cols
BS On 2D Array
BS On 2D Array
BS min_of_max OR Sort the array. Minimum distance is 1 and maxDis can be arr[n-1] - arr[0]. Try to maximizae the result in this range. Make
Aggressive Cows [Link]
max_of_min placeCow function. Start placing cow from 0-th index. If arr[currIndex] - lastCowPos >= mid then countCow++.
Find the range to apply BS. one student have to take the maxPage book which is the minimum pages. Upperbound is
BS min_of_max OR Allocate Book. Or Partion Of
[Link]
sum_of_all_elements. In this range apply BS. make a check function if midPages is a valid ans or not. If valid then store it and
max_of_min Painter.
search more min. If not not valid move to more greater value of pages

Math Power of x ^ n [Link]


Use long long int as n. Handle negative case. If even then x*x and n/2 other wise x*solve(x,n-1)
Math

Count the letter of s1. maintain a window len s1 and add count right letter if s2 always check if countS1 == countS2 if true return
Sliding_Window [Link]
Permuation in string
true. If windowlen cross then resize
Take an array right_max[Here we will store the rightest max_ele of curr_ele]. Then use a left and right. left will be only updated
Sliding_Window Max Width Ramp [Link]
when arr[left] > right_max[left]-->left++. ans = max(ans , right - left)

Start with 2pointers left=0 and right = n - 1. If currSum > target we need smaller value so go 1 step left. If target > currSum go
Two_pointers Two Sum_ii Sorted Array [Link]
left. If we got the target then return. NOTE: Here index is 1 based. before return add 1 in both index
Sort the array. For every curr-ele use a left = currIndex+1 and right = n - 1. If Curr_sum == 0 store currindex,left , right and and
Two_pointers Three Sum [Link] update left and right Then also use while loop in the same if body to avoid dublicates in both left and right pointer. If currSum < 0
go 1 step right else go 1step left
Two_pointers
Two_pointers
Two_pointers
Two_pointers

Start with the largest coin. Take as much as you can take[count = amount / coint_value] then update the amount = amount -
Greedy Minimum number of coins [Link]
count*coins_value. Then use a loop and take count numver of coins in the ans
Sort the array. While counting the minCost take the minCost and skip k number of last elements. And while calculating the
Greedy Shop in a candy store [Link]
maxAmount take the last ele and skip k numbers of first candies
Greedy Assign Mice Holes [Link]
Sort two given array. Then start calculating the find the max_abs_diff between M[i] and H[i].
Minimum Roation to unlock extrack 2 digits from to numbers. Find the clockwise distance and anti_cw distance. CW = abs(d1 - d2) , ACW = 10 - CW. and +=
Greedy [Link]
circular lock min(CW , ACW)
Sort the interval based on ending time of the time ascending order. Choose which meeting ending first. If curr_start > prev_end
Greedy N meetings in a room [Link]
then we can take it also update the end-time
Greedy Job sequencing [Link]
Sort based on profit in decreasing order. try to do the job as closest as the deadline. So use a taak_arr.
Greedy Single Threaded CPU [Link]
Greedy Fractional Knapsack [Link]
Sort based on per kg weight[Max_to_min]. Then start taking elements. If full taking is not possible then take partial
Count Occ of tasks using a map. Then count the maxOcc and numberOfMaxOcc. Ans max of taskSize and (maxOcc - 1) * (n + 1) +
Greedy Task Scheduler [Link]
numberOfMaxOcc
Greedy Assign Cookies [Link]
Sort both array. Then use 2 pointer. If we can assign this cookie then update both else update cookie_pointer
Use Dp. If (index > n || count < 0) return false. If (index >= 0) return count == 0. if s[index] == '(' count + 1 and call for next. If )
Greedy Valid Parenthesis String [Link]
count - 1 and call for next. If s[index] == * then there will be 3 call as opening as closing as empty. and OR this three.
Greedy jump game [Link] Be greedy try to go farthest distance always. If i > farestDis then we can't reach. Else take the farthest distance.
Sort based on arrival time. Go throw every pair. remove all the trains which departure before curr_train_arrival. Add the
Greedy Minimum platfroms [Link]
currtrain departure time. ans = max(ans , heap_size)
Make the digit array and reverse it. Use a maxDigitInRight array. from right to left store the index of the maxElementIndex
Greedy Maximum Swap [Link]
than the currEle. Then go throw digitArray and rightMaxArrayIndexElement if ar[i] < arr[rightMax[i]] then swap and break
Greedy
Greedy
Greedy
Greedy
Greedy
Greedy

Use 2 heaps one to track first workers and another for last workers. Use 2 pointer for first and last employee. if we dont have
Heap Total Cost to hire k workers [Link]
enough employee then take enough workers in both heap. i <= j for first workers. j >= i for last workers. Do this for k time. Also
handle heap empty case

[Link]
Linked_List Merge K lists
sorted-lists/description/

1D Dp

Take to pointer. 1 to traverse the char and anothe write_letter. Use inner loop to count the occ of curr_letter at i by using a
String String Compression [Link]
inner loop. Then write the curr_letter at write_index and update write_index. Then put all the digit in write_index and update it.
Then put i in the next diff letter. At the end return Wirte_index
Topic Question Name Question Link Note
Start from the the last index of arr1. We need 3 pointer. 1 for list2 , 1 for list1 non-zero and 1 for in genral. Edge Case: There can remain ele
Array Merge Sorted Array [Link]
in list2. So add the remains ele's also
Array Remove Element [Link]
use 2 pointer. Find the ele which is euqal to val from the front. Then find the ele which is not equal to val from the last of the list. Swap this 2 ele. update 2 pointer. Repeat the same procces utill these pointer meet or cross each other

You might also like