LeetCode Dynamic Programming Notes
LeetCode Dynamic Programming Notes
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
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.
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