L(n)eetcode.pdf
L(n)eetcode.pdf
https://leetcode.com/problems/two- use hash map to instantly check for difference value, map will add index of last occurrence of a num,
https://youtu.be/KLlXCFG5TnA Arrays Two Sum sum/ don’t use same element twice;
https://leetcode.com/problems/best-
https://youtu.be/1pkOgXD63yU Arrays Best Time to Buy and Sell Stock time-to-buy-and-sell-stock/ find local min and search for local max, sliding window;
https://leetcode.
https://youtu.be/3OamzN90kPg Arrays Contains Duplicate com/problems/contains-duplicate/ hashset to get unique values in array, to check for duplicates easily
https://leetcode.
com/problems/product-of-array-
https://youtu.be/bNvIQI2wAjk Arrays Product of Array Except Self except-self/ make two passes, first in-order, second in-reverse, to compute products
https://youtu. https://leetcode.
be/5WZl3MMT0Eg Arrays Maximum Subarray com/problems/maximum-subarray/ pattern: prev subarray cant be negative, dynamic programming: compute max sum for each prefix
https://leetcode.
com/problems/maximum-product-
https://youtu.be/lXVy6YWFcRM Arrays Maximum Product Subarray subarray/ dp: compute max and max-abs-val for each prefix subarr;
Find Minimum in Rotated Sorted https://leetcode.com/problems/find- check if half of array is sorted in order to find pivot, arr is guaranteed to be in at most two sorted
https://youtu.be/nIVW4P8b1VA Arrays Array minimum-in-rotated-sorted-array/ subarrays
https://leetcode.
https://youtu. com/problems/search-in-rotated- at most two sorted halfs, mid will be apart of left sorted or right sorted, if target is in range of sorted
be/U8XENwh8Oy8 Arrays Search in Rotated Sorted Array sorted-array/ portion then search it, otherwise search other half
sort input, for each first element, find next two where -a = b+c, if a=prevA, skip a, if b=prevB skip b
https://youtu.be/jzZsG8n2R9A Arrays 3Sum https://leetcode.com/problems/3sum/ to elim duplicates; to find b,c use two pointers, left/right on remaining list;
https://leetcode.
com/problems/container-with-most-
https://youtu.be/UuiTKBwPgAo Arrays Container With Most Water water/ shrinking window, left/right initially at endpoints, shift the pointer with min height;
https://leetcode.com/problems/sum-
https://youtu.be/gVUrDV4tZfY Binary Sum of Two Integers of-two-integers/ add bit by bit, be mindful of carry, after adding, if carry is still 1, then add it as well;
https://leetcode. modulo, and dividing n; mod and div are expensive, to divide use bit shift, instead of mod to get 1's
https://youtu.be/5Km3utixwZs Binary Number of 1 Bits com/problems/number-of-1-bits/ place use bitwise & 1;
https://youtu. https://leetcode. write out result for num=16 to figure out pattern; res[i] = res[i - offset], where offset is the biggest
be/RyBM56RIWrM Binary Counting Bits com/problems/counting-bits/ power of 2 <= I;
https://leetcode.
https://youtu.be/WnPLSRLSANE Binary Missing Number com/problems/missing-number/ compute expected sum - real sum; xor n with each index and value;
https://leetcode.
https://youtu.be/UcoN6UjAI64 Binary Reverse Bits com/problems/reverse-bits/ reverse each of 32 bits;
Dynamic https://leetcode.
https://youtu.be/Y0lT9Fck7qI Programming Climbing Stairs com/problems/climbing-stairs/ subproblem find (n-1) and (n-2), sum = n;
top-down: recursive dfs, for amount, branch for each coin, cache to store prev coin_count for each
Dynamic https://leetcode.com/problems/coin- amount; bottom-up: compute coins for amount = 1, up until n, using for each coin (amount - coin),
https://youtu.be/H9bfqozjoqs Programming Coin Change change/ cache prev values
https://leetcode. recursive: foreach num, get subseq with num and without num, only include num if prev was less,
Dynamic com/problems/longest-increasing- cache solution of each; dp=subseq length which must end with each num, curr num must be after a
https://youtu.be/cjWnW0hdF1Y Programming Longest Increasing Subsequence subsequence/ prev dp or by itself;
https://leetcode. recursive: if first chars are equal find lcs of remaining of each, else max of: lcs of first and remain of
Dynamic com/problems/longest-common- 2nd and lcs of 2nd remain of first, cache result; nested forloop to compute the cache without
https://youtu.be/Ua0GhsJSlWM Programming Longest Common Subsequence subsequence/ recursion;
Dynamic https://leetcode.com/problems/word- for each prefix, if prefix is in dict and wordbreak(remaining str)=True, then return True, cache result
https://youtu.be/Sx9NNgInc3A Programming Word Break Problem break/ of wordbreak;
Dynamic https://leetcode. visualize the decision tree, base case is curSum = or > target, each candidate can have children of
https://youtu.be/GBKI9VSKdGg Programming Combination Sum com/problems/combination-sum/ itself or elements to right of it inorder to elim duplicate solutions;
Dynamic https://leetcode.com/problems/house- for each num, get max of prev subarr, or num + prev subarr not including last element, store results
https://youtu.be/73r3KWiEvyk Programming House Robber robber/ of prev, and prev not including last element
Dynamic https://leetcode.com/problems/house-
https://youtu.be/rWAJCfYYOvM Programming House Robber II robber-ii/ subarr = arr without first & last, get max of subarr, then pick which of first/last should be added to it
Dynamic https://leetcode. can cur char be decoded in one or two ways? Recursion -> cache -> iterative dp solution, a lot of
https://youtu.be/6aEyTjOwlJU Programming Decode Ways com/problems/decode-ways/ edge cases to determine, 52, 31, 29, 10, 20 only decoded one way, 11, 26 decoded two ways
Dynamic https://leetcode. work backwards from solution, store paths for each position in grid, to further optimize, we don’t
https://youtu.be/IlEsdxuD4lY Programming Unique Paths com/problems/unique-paths/ store whole grid, only need to store prev row;
visualize the recursive tree, cache solution for O(n) time/mem complexity, iterative is O(1) mem, just
Dynamic https://leetcode.com/problems/jump- iterate backwards to see if element can reach goal node, if yes, then set it equal to goal node,
https://youtu.be/Yan0cv2cLy8 Programming Jump Game game/ continue;
https://youtu. https://leetcode.com/problems/clone-
be/mQeF6bN8hMk Graph Clone Graph graph/ recursive dfs, hashmap for visited nodes
https://leetcode. build adjacentcy_list with edges, run dfs on each V, if while dfs on V we see V again, then loop exists,
https://youtu.be/EgI5nU9etnU Graph Course Schedule com/problems/course-schedule/ otherwise V isnt in a loop, 3 states= not visited, visited, still visiting
https://leetcode.
com/problems/pacific-atlantic-water- dfs each cell, keep track of visited, and track which reach pac, atl; dfs on cells adjacent to pac, atl,
https://youtu.be/s-VkcjHqkGI Graph Pacific Atlantic Water Flow flow/ find overlap of cells that are visited by both pac and atl cells;
https://leetcode. foreach cell, if cell is 1 and unvisited run dfs, increment cound and marking each contigous 1 as
https://youtu.be/pV2kpPD66nE Graph Number of Islands com/problems/number-of-islands/ visited
https://leetcode. use bruteforce and try to optimize, consider the max subseq containing each num; add each num to
https://youtu. com/problems/longest-consecutive- hashset, for each num if num-1 doesn’t exist, count the consecutive nums after num, ie num+1;
be/P6RZZMu_maU Graph Longest Consecutive Sequence sequence/ there is also a union-find solution;
chars of a word not in order, the words are in order, find adjacency list of each unique char by
Alien Dictionary (Leetcode https://leetcode.com/problems/alien- iterating through adjacent words and finding first chars that are different, run topsort on graph and
https://youtu.be/6kTZYvNNyps Graph Premium) dictionary/ do loop detection;
union find, if union return false, loop exists, at end size must equal n, or its not connected; dfs to get
https://youtu. Graph Valid Tree (Leetcode https://leetcode.com/problems/graph- size and check for loop, since each edge is double, before dfs on neighbor of N, remove N from
be/bXsUuownnoQ Graph Premium) valid-tree/ neighbor list of neighbor;
Number of Connected https://leetcode.
https://youtu. Components in an Undirected com/problems/number-of-connected- dfs on each node that hasn’t been visited, increment component count, adjacency list; bfs and union
be/8f1XPm4WOUc Graph Graph (Leetcode Premium) components-in-an-undirected-graph/ find are possible;
https://youtu. https://leetcode.com/problems/insert- insert new interval in order, then merge intervals; newinterval could only merge with one interval
be/A8NUOmlwOlM Interval Insert Interval interval/ that comes before it, then add remaining intervals;
https://leetcode. sort each interval, overlapping intervals should be adjacent, iterate and build solution; also graph
https://youtu.be/44H3cEC2fFM Interval Merge Intervals com/problems/merge-intervals/ method, less efficient, more complicated
https://youtu. https://leetcode.com/problems/non- instead of removing, count how max num of intervals you can include, sort intervals, dp to compute
be/nONCGxWoUfM Interval Non-overlapping Intervals overlapping-intervals/ max intervals up until the i-th interval;
Meeting Rooms (Leetcode https://leetcode. sort intervals by start time, if second interval doesn’t overlap with first, then third def wont overlap
https://youtu.be/PaJxqZVPhbg Interval Premium) com/problems/meeting-rooms/ with first;
we care about the points in time where we are starting/ending a meeting, we already are given
Meeting Rooms II (Leetcode https://leetcode. those, just separate start/end and traverse counting num of meetings going at these points in time;
https://youtu.be/FdzJmTCVyJU Interval Premium) com/problems/meeting-rooms-ii/ for each meeting check if a prev meeting has finished before curr started, using min heap;
https://leetcode.
https://youtu.be/G0_I-ZF0S38 Linked List Reverse a Linked List com/problems/reverse-linked-list/ iterate through maintaining cur and prev; recursively reverse, return new head of list
https://leetcode.com/problems/linked-
https://youtu.be/gBTe7lFR3vc Linked List Detect Cycle in a Linked List list-cycle/ dict to remember visited nodes; two pointers at different speeds, if they meet there is loop
https://leetcode.
https://youtu.be/XIdigk956u0 Linked List Merge Two Sorted Lists com/problems/merge-two-sorted-lists/ insert each node from one list into the other
https://leetcode. divied and conquer, merge lists, N totalnodes, k-lists, O(N*logk). For each list, find min val, insert it
https://youtu.be/q5a5OiGbT6Q Linked List Merge K Sorted Lists com/problems/merge-k-sorted-lists/ into list, use priorityQ to optimize finding min O(N*logk)
https://leetcode.
Remove Nth Node From End Of com/problems/remove-nth-node-from-
https://youtu.be/XVuQxVej6y8 Linked List List end-of-list/ use dummy node at head of list, compute len of list; two pointers, second has offset of n from first;
https://leetcode.
https://youtu.be/S5bfdUTrKLM Linked List Reorder List com/problems/reorder-list/ reverse second half of list, then easily reorder it; non-optimal way is to store list in array;
https://leetcode.com/problems/set- use sets to keep track of all rows, cols to zero out, after, for each num if it is in a zero row or col then
https://youtu.be/T41rL0L3Pnw Matrix Set Matrix Zeroes matrix-zeroes/ change it to 0; flag first cell in row, and col to mark row/col that needs to be zeroed;
https://youtu. https://leetcode.com/problems/spiral-
be/BJnMZNwUk1M Matrix Spiral Matrix matrix/ keep track of visited cells; keep track of boundaries, layer-by-layer;
https://leetcode.com/problems/rotate- rotate layer-by-layer, use that it's a square as advantage, rotate positions in reverse order, store a in
https://youtu.be/fMSJSS7eO1w Matrix Rotate Image image/ temp, a = b, b = c, c = d, d = temp;
https://leetcode.com/problems/word- dfs on each cell, for each search remember visited cells, and remove cur visited cell right before you
https://youtu.be/pfiQ_PS1g8E Matrix Word Search search/ return from dfs;
https://leetcode.
https://youtu. Longest Substring Without com/problems/longest-substring-
be/wiGpQwVHdE0 String Repeating Characters without-repeating-characters/ sliding window, if we see same char twice within curr window, shift start position;
https://leetcode. PAY ATTENTION: limited to chars A-Z; for each capital char, check if it could create the longest
Longest Repeating Character com/problems/longest-repeating- repeating substr, use sliding window to optimize; check if windowlen=1 works, if yes, increment len,
https://youtu.be/gqXU1UyA8pk String Replacement character-replacement/ if not, shift window right;
https://leetcode. need is num of unique char in T, HAVE is num of char we have valid count for, sliding window, move
com/problems/minimum-window- right until valid, if valid, increment left until invalid, to check validity keep track if the count of each
https://youtu.be/jSto0O4AJbM String Minimum Window Substring substring/ unique char is satisfied;
https://leetcode.com/problems/valid-
https://youtu.be/9UtInBqnCgA String Valid Anagram anagram/ hashmap to count each char in str1, decrement for str2;
https://leetcode.com/problems/group- for each of 26 chars, use count of each char in each word as tuple for key in dict, value is the list of
https://youtu.be/vzdNOK2oB2E String Group Anagrams anagrams/ anagrams;
https://leetcode.com/problems/valid-
https://youtu.be/WTzjTskDFMg String Valid Parentheses parentheses/ push opening brace on stack, pop if matching close brace, at end if stack empty, return true;
https://leetcode.com/problems/valid- left, right pointers, update left and right until each points at alphanum, compare left and right,
https://youtu.be/jJXJ16kPFWg String Valid Palindrome palindrome/ continue until left >= right, don’t distinguish between upper/lowercase;
https://leetcode.
com/problems/longest-palindromic-
https://youtu.be/XYQecbcd6_c String Longest Palindromic Substring substring/ foreach char in str, consider it were the middle, consider if pali was odd or even;
https://leetcode. same as longest palindromic string, each char in str as middle and expand outwards, do same for
https://youtu.be/4RACzI5-du8 String Palindromic Substrings com/problems/palindromic-substrings/ pali of even len; maybe read up on manachers alg
https://leetcode.
Encode and Decode Strings com/problems/encode-and-decode-
https://youtu.be/B1k_sxOSgv8 String (Leetcode Premium) strings/ store length of str before each string and delimiter like '#';
https://leetcode.
com/problems/maximum-depth-of-
https://youtu.be/hTM3phVI6YQ Tree Maximum Depth of Binary Tree binary-tree/ recursive dfs to find max-depth of subtrees; iterative bfs to count number of levels in tree
https://leetcode.com/problems/same-
https://youtu.be/vRbbcKXCxOw Tree Same Tree tree/ recursive dfs on both trees at the same time; iterative bfs compare each level of both trees
https://youtu. https://leetcode.com/problems/invert- recursive dfs to invert subtrees; bfs to invert levels, use collections.deque; iterative dfs is easy with
be/OnSn2XEQ4MY Tree Invert/Flip Binary Tree binary-tree/ stack if doing pre-order traversal
https://leetcode.
com/problems/binary-tree-maximum- helper returns maxpathsum without splitting branches, inside helper we also update maxSum by
https://youtu.be/Hr5cWUld4vU Tree Binary Tree Maximum Path Sum path-sum/ computing maxpathsum WITH a split;
https://leetcode.
Binary Tree Level Order com/problems/binary-tree-level-order-
https://youtu.be/6ZnyEApgFYg Tree Traversal traversal/ iterative bfs, add prev level which doesn't have any nulls to the result;
https://leetcode. bfs every single non-null node is added to string, and it's children are added too, even if they're null,
Serialize and Deserialize Binary com/problems/serialize-and- deserialize by adding each non-null node to queue, deque node, it's children are next two nodes in
https://youtu.be/u4JAi2JJhI8 Tree Tree deserialize-binary-tree/ string;
https://leetcode.
com/problems/subtree-of-another-
https://youtu.be/E36O5SWp-LE Tree Subtree of Another Tree tree/ traverse s to check if any subtree in s equals t; merkle hashing?
https://leetcode.
Construct Binary Tree from com/problems/construct-binary-tree- first element in pre-order is root, elements left of root in in-order are left subtree, right of root are
https://youtu.be/ihj4IQGZ2zc Tree Preorder and Inorder Traversal from-preorder-and-inorder-traversal/ right subtree, recursively build subtrees;
https://leetcode.
com/problems/validate-binary-search- trick is use built in python min/max values float("inf"), "-inf", as parameters; iterative in-order
https://youtu.be/s6ATEkipzow Tree Validate Binary Search Tree tree/ traversal, check each val is greater than prev;
https://leetcode.com/problems/kth- non-optimal store tree in sorted array; iterative dfs in-order and return the kth element processed,
https://youtu.be/5LUXSvjmGCw Tree Kth Smallest Element in a BST smallest-element-in-a-bst/ go left until null, pop, go right once;
https://leetcode.
Lowest Common Ancestor of com/problems/lowest-common-
https://youtu.be/gs2LMfuOR9k Tree BST ancestor-of-a-binary-search-tree/ compare p, q values to curr node, base case: one is in left, other in right subtree, then curr is lca;
https://leetcode.
com/problems/implement-trie-prefix- node has children characters, and bool if its an ending character, node DOESN’T have or need char,
https://youtu.be/oobqoCJlHA0 Tree Implement Trie (Prefix Tree) tree/ since root node doesn’t have a char, only children;
https://leetcode.com/problems/add-
and-search-word-data-structure-
https://youtu.be/BTf05gs_8iU Tree Add and Search Word design/ if char = "." run search for remaining portion of word on all of curr nodes children;
trick: I though use trie to store the grid, reverse thinking, instead store dictionary words, dfs on each
https://leetcode.com/problems/word- cell, check if cell's char exists as child of root node in trie, if it does, update currNode, and check
https://youtu.be/asbcE9mZz_U Tree Word Search II search-ii/ neighbors, a word could exist multiple times in grid, so don’t add duplicates;
https://leetcode. we always want the min of the current frontier, we can store frontier in heap of size k for efficient
https://youtu.be/q5a5OiGbT6Q Heap Merge K Sorted Lists com/problems/merge-k-sorted-lists/ pop/push; divide and conquer merging lists;
https://leetcode.com/problems/top-k- minheap that’s kept at size k, if its bigger than k pop the min, by the end it should be left with k
https://youtu.be/YPTqKIgVk-k Heap Top K Frequent Elements frequent-elements/ largest;
https://leetcode.com/problems/find- maintain curr median, and all num greater than med in a minHeap, and all num less than med in a
https://youtu.be/itmhHWaHupI Heap Find Median from Data Stream median-from-data-stream/ maxHeap, after every insertion update median depending on odd/even num of elements;