ABCDEFGHIJKLMNOPQRSTUVWXYZ
1
2
Arrays/Pointers
3
4
Problem NameDifficultyDescriptionMental Model
5
Longest SubstringMediumGiven a string, find longest substring without repeating charactersTwo pointers with a hash that keeps track of characters we've seen and their indexes. Update index whenever we see it again. Move anchor to position after last seen. Update longest whenever it gets larger.
6
Longest Palindrome substringMediumGiven a string, find the longest palindrome substringHave a function that will expand the substring on both sides. You have an x and y that point to the beginning and end of the palindrome. While the substring is a palindrome, keep expanding until it isn't. Keep track of the indexes that make up the longest palindrome and return those at the end. You will need to expand from the same character and from characters that are side by side as palindromes can be even or odd numbered.
7
longest parlidrome subsequenceMediumgiven a string, find longest subsequence that is a palindromesimilar to substring except use the table to keep track of longest length instead of boolean flag. If the characters on the end are the same, add the longest palindrome plus 2. Or get the max from [i][j-1] or [i+1][j]
8
3SumMediumgiven an array and an integer, find all unique triplets to equal the integerSort array and iterate over it. Skip any numbers that have been seen and stop as soon as the numbers become greater than 0. For each number, do a two sum problem breakup.
9
Remote Nth element from listMediumGiven a linked list, remove the nth node from the end of list and return its head.Create a clonehead, a slow pointer and a fast pointer. Maintain the gap between the fast and slow pointers. When fast reaches the end, slow should be behind the target node. Skip over node.
10
Search in Rotated Sorted ArrayMediumSuppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. You are given a target value to search. If found in the array return its index, otherwise return -1Use binary search to find numbers. Check if current number is greater than or equal to first number. If it is, check to see if target number is between the first num and the current number. Search left side, else search right. The opposite is true for if the current number is less than the first number.
11
4SumMediumFind 4 numbers that add up to given targetTwo nested loops keep track of the first two numbers. While doing that, at every iteration, call a twoSum method that finds if the remaining two numbers can be found from the given target. Must sort the array first
12
Shortest Substring with Unique CharactersMediumGiven an array of unique characters, find the shortest substring in a given string that includes those charactersBrute force solution has two loops and two sets to keep track of what has been seen. More efficient has two pointers and a sliding window with a hash table. Hash table keeps track of how many of the unique letters has been seen. Increment right side of window until a substring is found, then increment left side to see if a shorter substring can be found. Go back and forth until right hits the end and left can no longer find a valid substring. Return the shortest that has been found.
13
Spiral MatrixMediumCreate a program that turns a 2d matrix array into a 1d array that is spiral4 loops that correlate to the four directions: right, down, left, up. Have 4 pointers that keep track of row and col start/end. Stop when both are at the same value.
14
Remove Duplicates from Sorted ArrayEasyRemove all duplicate elements from array or move to back of arrayWrite and read pointers, when read does not equal write, increment write index and swap the read and write elements. That will move all the elements to the end of the array. After that, can splice the end of array off
15
Convert Sorted Array to BSTEasyGiven a sorted array, convert it to BSTCan be done recursively. Find middle index and set that to root node, do a divide and conquer to find left and right nodes.
16
max stock profiteasygiven an array of prices, find the max profit that can be found from a single purchasehave three vars: low, high, max. Iterate over array, if current is lower than previous low, change low and high. If high is greater than previous high, change high and update max if need be.
17
max total profiteasygiven an array of prices, find the total max profit from any transactions that can be madea
18
reverse stringeasygiven a string, reverse ittwo pointers at each end, swap characters and then update pointers to get closer to each other
19
valid palindromeeasygiven a string, check if palindrometwo pointers at each end, check if same, increment start and decrement head. go until either not the same or pointers meet
20
quick sortmediumsort array using quick sortassuming array is shuffled, select that last number. THat will be your comparision. Have read and write pointers. increment read every time. Whenever hit number that is less than comparator, increment write and swap places. Once read hits end, put comparator where write value is. Start over until sorted
21
reverse words in stringmediumreverse the words in a string but keep them in the same order.reverse entire string first. Then using anchor and runner pointers, run until a space, then swap all the characters between anchor and runner. Update anchor to value after runner, or in the case of multiple spaces, have anchor be null until encounters first char val.
22
strstreasyReturn the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.Two pointers, anchor / runner. Iterate anchor until it matches first char of needle string. Have runner go and check if correct string. If not, keep iterating anchor.
23
Minimum Size Subarray SummediumGiven an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.Two pointer crawl/accordion. Have an anchor and runner. Runner iterates until the sum is greater than target. Save that length and update if shortest seen so far. Increment anchor and update length until sum is smaller. Keep going until the end.
24
Search insert positionmediumGiven a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.Binary search the array until you have found it. If not found in the initial search, check the last remaining two elements. Either left or right
25
find peak elementmediumA peak element is an element that is greater than its neighbors.binary search and check if value is greater than both left and right. If not, check which direction the slope is increasing and search on that half.
26
search for a rangemediumGiven an array of integers sorted in ascending order, find the starting and ending position of a given target value.Use binary search to find both ends of the range. If character can't be found, return [-1, -1]
27
Find minimum in rotated sorted arraymediumFind the minimum value in a sorted rotated arrayuse binary search to find element that is lowest of neighbors. Find where the slope is decreasing to know which side to search
28
Find minimum value which equals the indexmediumfind minimum value in the array which equals the index value. If not found, return -1use binary search to find element. If current val is greater than index, search left, else search right.
29
valid square rooteasydetermine if input value is a valid perfect squarebinary search from 2 to value to see if value is a square. return true if value is 1
30
pow(x, n)mediumimplement the function pow(x,n) that finds x ^ n powerrecursive solution that halves the n value and squares the x value on every call.
31
medium?mediumfind subarray that has the max sum valueiterate over the array. if current value is greater than the current sum plus the current value, then reassign current max to current val and check it against the global max.
32
longest common prefixeasyfind longest common prefix amoung an array of stringsiterate across all the words and check if all the letters at a certain index is the same. If it's not the same, return the stored result that far.
33
array parition 1easyfind the largest min sum of pairssort array, iterate over array in two steps and add all the mins together.
34
max area of islandeasyfind max area of islanditerate across grid. When encounter 1, find the area. If greater than last max, assign. DFS
35
Get Different Numbereasyfind the lowest number that is not in the array. Distinct non-negative numbers onlySort array based on the index of the value. A number with 2 should go in the 2nd slot of array. Then iterate over again and find the first number that doesn't match their index
36
Matching Time SloteasyFind the earliest time slot that overlaps between two schedules. Return nil if noneTwo pointer solution. Use a while loop and iterate over both arrays at same time. Check if max start time plus duration of meeting is less than min end time. If yes, return. If no, advance times lot with the min end time.
37
subarray summedium?Given an array of integers and an integer target, find a subarray that sums to target and return the start and end indices of the subarray. It's guaranteed to have a unique solution.this involves calculating the prefix sum of the array. The sum of array[i:j] is the same as array[0:j] - array[0:i-1]. So you need to iterate over the array and build a hash map of prefix-sum: index. So then it just becomes a two sum problem where you need to mind a way in the array where prefixSum - target exists in the array and return that index and the current index.
38
maximum scoremedium/hardYou are given two sorted arrays of distinct integers, arr1, and arr2. Your goal is to start from the beginning of one array, and arrive to the end of one array (it could be the same array or not).
For each step, you can either move forward a step on an array, or move to a square in the other array where the number is the same as the number in your current square ("teleport"). Your total score is defined as the sum of all unique numbers that you have been on.
Find the maximum score that you can get given the above rules. Since the result might be very large and cause overflow, return the maximum score modded by 10^9 + 7.
For simplicity, we call numbers that appears multiple times "teleporters". Because both
arrays are ordered and distinct, teleporter number must appear in both array exactly once,
and each teleporter in both arrays must be ordered in the same way.
Consider the interval between two teleporters. If
there are no number between these two numbers that appear in both array, then in those steps
you can only go forward. Therefore, the score in that section would be the sum of the
subarray in that section.
Furthermore, regardless where you start, it does not affect the
choice whether to go top or go bottom in that section. If you start from the top array,
you can go left to continue the top array, and teleport to the bottom array. The same goes
for if you start from the bottom array. In that case, to maximize the score, we only need
to maximize the score of each interval between two teleporters.
Note that the same holds true for numbers before the first teleporter and after the final
teleporter, so we can apply the same logic.
39
trapping rain watermedium/hardGiven a list of non-negative integers representing elevations of
columns, and assuming each column is of equal width of 1, find how much
water is trapped in the columns after a rain. Left and right boundaries
outside of the columns have 0 elevations.
How we caluclate the rain water for any position is finding the left and right wall and using the small of the those to calculate the water area. However, we need to find the max left and max right walls because that dictates how much water can get trapped.
40
linked list IIImedium
41
42
Binary Tree
43
Problem NameDifficultyDescriptionMental Model
44
Lowest Common AncestormediumGiven a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.LCA can be described as the first ancestor who elements are found on either side and not just on one side. Traverse down the tree. At each node, check to see which side elements are on. The first node that has either element on either side, return that node.
45
Insert node into BSTeasygiven a node, insert it into a BSTcheck root. if number is greater, go right, otherwise left. It hit an empty node, create new node and set it equal to that one.
46
Symmetric Treeeasysymmetric treedivide and conquer. Use a helper method that takes two sub trees. Compare left node val to right node val. Then do recursive call to left left tree and right right tree, then left right tree and right left tree
47
Invert a Binary treeeasyinvert binary treeBase case: root is null, return root. Divide into left and right and recurse into each side. When each side returns, swap them and return root.
48
Binary Preorder Traversaleasydo a preorder traversal of node values into an arrayDo an iterative loop with a stack. Start with root node, push the right, left onto stack and then push current value to return array.
49
Validate BSTmediumdetermine if a bst is valid bst tree. Must have same root, and left must always be less and right must always be greaterDivide and conquer. Split by left and right and recurse into each. If end node, return true. Check that the current node is greater than minNode and less than greater node. return left and right side boolean values
50
Same Treeeasygiven two binary trees, write a function to check if they are the same or notTraversal. Traverse both trees in the same order. If they are ever not the same at any point, return false. Return true otherwise
51
balanced treeeasygiven a binary tree, determine if it is height-balancedDivide and conquer. When reach null node, return 0. Increment max and return. Otherwise, return -1. Early return if receive -1 and return false from overall method.
52
max deptheasyfind max depth of treeDivide and conquer. When reach past leaf node, return 0. Increment number as you return and find the max.
53
Inorder successor nodemediumgiven a node, find the next in order successor. If none, return nullCheck if right subtree. If there is, right the last node on the left subtree. If no right subtree, iterate up parent nodes
54
Subtree of another treeeasygiven two trees, write a function to see if second tree is a subtree of the firstTraverse the tree until find a node that has equal value. When same, do a subtree check. If true, return true. If false, keep traversing until end of the tree.
55
Level order traversal of BSTmediumperform a level order traversal of a binary treeUse a queue to traverse across the tree. push each queue to a result array. return when queue is finished.
56
Average levels in BSTmediumfind the average of all the levelsDo a level order traversal, push each level to a result array. When queue is finished, average the rows.
57
Sum Root to Leaf Numbersmediumsum all the nums created from root to leafDivide and conquer. Use helper to generate an array of all nums. Helper adds value to a tracker and returns num if leaf node. Concats returned numbers together.
58
Convert BT to LLmediumconvert binary tree into linked listdivide and conquer. base case is if empty node, return. Call flatten on both left and right. assign right side to a temp and assign right side to left half. Iterate down until end and assign new tail to the temp right var.
59
60
61
62
Linked Lists
63
Problem NameDifficultyDescriptionMental Model
64
Remote Nth element from listMediumGiven a linked list, remove the nth node from the end of list and return its head.Create a clonehead, a slow pointer and a fast pointer. Maintain the gap between the fast and slow pointers. When fast reaches the end, slow should be behind the target node. Skip over node.
65
Remove Linked List duplicateseasyRemove all elements from a linked list of integers that have value val.do recursion. If head equals value, reassign head, otherwise reassign head.next. Iteratively, create a dummy node and current. While current, run down until you find a node that doesn't equal val, then advance current until end.
66
remove duplicates from sorted linked listeasyGiven a sorted linked list, delete all duplicates such that each element appear only once.Recursively, check if current value equals next value. If it does, reassign head, if it doesn't, reassign head.next. Iteratively, create dummy node and set current to dummy. Have a runner that runs down until a node that is not the same as the next. Reassign current.next and keep going.
67
reverse linked listeasyReverse a singly linked list.Keep track of prev node. Assign current.next to prev and prev to current. Then advance current until null.
68
merge two sorted listseasyMerge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.Iterate across both linked lists. Whichever one is less, do a recursive call and assign it to .next of the node. Non-recursive, create a dummy node and assign it's next to the next value. Iterate across links until one of them is empty.
69
reverse linked list IImediumReverse a linked list from position m to n. Do it in-place and in one-pass.3-4 pointer solution. Keep track of anchor, tail, head and next. From m to n, assign next to head.next.next. Head.next is assigned to head.next.next. Head.next.next is assigned to tail. anchor.next goes to head.next.next.
70
remove dups from sorted list 2mediumGiven a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinctnumbers from the original list.Three pointer solution with recursion. Keep track of previous value. If current value is same as next value, reassign head and make prev value current value. If current value is not same as next but same as previous, same as before. If current value is different from previous and next, reassign .next
71
linked Lists cycleeasyGiven a linked list, determine if it has a cycle in it.slow and fast pointers. Make fast advance by 2 while slow only advances by 1. If they ever meet up, return true. Otherwise return false.
72
delete node in linked listeasyWrite a function to delete a node (except the tail) in a singly linked list, given only access to that node.make the current value equal the next value and the .next value equal to .next.next value.
73
partition listmedium
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
Four pointer solution. Lesser tail/head, greater tail/head. For every value, if it is greater, assign to greater head and advance greater head, otherwise do that for lesser head. At the end, assign lesser head to greater tail.next and return lesser tail.next
74
link list cycle IImediumdetect where the beginning of a cycle starts, if no loop, return nullTwo point solution. When both meet, set one to the head node and increment until meet. That is the head node.
75
palindrome linked listeasyGiven a singly linked list, determine if it is a palindrome.Two point solution. Run down it once to get the size. Run down a second time and reverse the linked list from the second half to the end. Then run down half way and have two pointers, one reads at the beginning while the other reads from the middle. They compare values and if they're ever not the same, return false. Second pointer is reversing the linked list as it goes along.
76
77
78
79
Dynamic P.
80
Problem NameDifficultyDescriptionMental Model
81
Generate ParensMediumGiven n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.Must always begin with the open parentheses. From there, a choice can be made between either an open or closed parens. Can only use closed parens if the number of open parens is greater than closed. Also, base case is when the length of string is twice as much as N.
82
Subset IIMediumGiven a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).Sort list first. Iterate through it, pushing every combo to a result array. Do a recursive call and increment starting index by 1. Base case is when starting index reaches length of array.
83
Longest Palindrome substringMediumGiven a string, find the longest palindrome substringUse a dynamic programming table. Have three loops, the last loop is nested. The first loop will look at single characters, the second will look at double characters, and the third nested loop will look at characters length 3 to n. Keep true/false in a boolean table.
84
longest parlidrome subsequenceMediumgiven a string, find longest subsequence that is a palindromesimilar to substring except use the table to keep track of longest length instead of boolean flag. If the characters on the end are the same, add the longest palindrome plus 2. Or get the max from [i][j-1] or [i+1][j]
85
All possible paths in matrixmediumgiven a 2d matrix, find all possible pathsBacktracking with memo. Recursive all the way down to the bottom right of grid. Have a DP table to fill in values. Base case is either end of grid of an invalid square. Return 1 for former, 0 for latter. Each square's possible paths if the sum of the cell below it and to the right. The initial call will be possiblePaths(grid, row + 1, col) + possiblePaths(grid, row, col + 1). Can use a memo cache in case we visit multiple nodesSecond solution is to do iteratively. Any row or col that is zero has a value of 1. Iterate across board and fill in cells as you go along. The final answer will be at the bottom right cell.
86
fibonaccieasyCalculate any step N of fibonacci sequenceDP with memo. Cache the value of n as fib(n-1) + fib(n-2). Return cache[n]
87
climb stairseasyYou are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?Basically fibonacci. The end result is climbStairs(n - 1) + climbStairs(n - 2). Carry a cache or memo around in case you encounter the same step. Set the cache value if it doesn't exist.
88
minimum pathmediumGiven a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.Best to use iterative approach. Great a DP grid that will keep track of the sum of the current value from the grid plus the min value from above or to the left of it. The answer will be at the very end.
89
jump gamemediumGiven an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index.Fastest implementation is a greedy algorithm. Iterate across the array and update max jumps until it surpasses the array length. Then return true. If never surpasses, return false.
90
trianglemediumGiven a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.Dp with memoization. Start with the last row of triangle. Iterate across each element in reverse order starting with the second to last to the first. For each element, find the sum of min of the current element and the next value and add the value from the triangle.
91
possible pathsmediumgiven a number, generate all possible paths to get to the bottom right without crossing halfway line.Use a cache table and calculate sum of previous value and current value. Return the last value.
92
93
94
largest rectangle in histogramhardGiven an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.brute force: Iterate over double loop and keep track of minimum height as you traverse between points and multiply width to min height and keep track of max. Better appraoch: use stack where you add increasing heights. This shows left and right limits. when you encounter number that is less than top of stack, continue to pop and calculate area. And when we reach the end, do the same and pop off of stack and calculate widths and heights
95
largest rectangle in gridhardgrid a 2d grid, find size of maximum rectanglebrute force: Iterate over double loop and keep track of minimum height as you traverse between points and multiply width to min height and keep track of max. Better appraoch: use stack where you add increasing heights. This shows left and right limits. when you encounter number that is less than top of stack, continue to pop and calculate area. And when we reach the end, do the same and pop off of stack and calculate widths and heights
96
01 MatrixmediumGiven an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.
Either bfs starting from each zero and going outwards. Update whenever new min is hit. Or use DP and dp grid. Iterate through grid frontwards and calculate shortest distance from the top and left. Then go backwards and check distance for bottom and right
97
K Closest Points to OriginmediumGiven an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Max heap or quick select using euclid distance formula
98
Binary Tree Level Order TraversalmediumGiven the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).using a queue to traverse over nodes and create a new queue for each level, put node vals into output
99
Course SchedulemediumThere are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.Topological sort of graph is optimal. Can use dfs as well.
100