LC
99.[Tree] Binary Tree Right Side View Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Input: root = [1,2,3,null,5,null,4] Output: [1,3,4]
(1) traversal of the tree is NOT standard pre-order traverse. It checks the RIGHT node first and then the LEFT (2) the line to check currDepth == result.size() makes sure the first element of that level will be added to the result list (3) if reverse the visit order, that is first LEFT and then RIGHT, it will return the left view of the tree.
1641.Count Sorted Vowel Strings Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. Example 1: Input: n = 1......Output: 5 Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"]. Example 2: Input: n = 2...Output: 15 Explanation: The 15 sorted strings that consist of vowels only are ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.
/ first solution that I came up with is backtracking brute force // this is dp (Bottom up -iterative) // There are a few things to realize: // 1) When we list all the solutions for n=2 we realize that there are 2 strings with e at the end (ae, ee), three with i (ai, ei, ii) 2) We line up the table and we notice that dp[i][j] is the sum of the previous rows // 3) To get around summing the previous row, we can use a prefix sum for the first row, and then all we need is the diagnal sum and the last num is the answer // O(n) time | O(n) time complexity
126. Word Ladder II A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: • Every adjacent pair of words differs by a single letter. • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. • sk == endWord Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]. Example 1: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] Explanation: There are 2 shortest transformation sequences: "hit" -> "hot" -> "dot" -> "dog" -> "cog" "hit" -> "hot" -> "lot" -> "log" -> "cog"
// 1) This is a graph problem since there's only one character that separates each // vertex, we can choose to create an adjacency list by inserting 'a' to 'z' //2) We have to use bfs to get the shortest path and keep track of the levels in a hashmap // 3) Then use DFS to find all the possible paths using our adjacency list and levels map // O(nK^2 + a) time where n is the num of words, k is max length of word // and a is the number of edges/paths from beginword ot endword
877. Stone Game Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties. Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins. Example 1: Input: piles = [5,3,4,5] Output: true
// 1) we can figure out that alice always wins since she can pick any combination //of numbers since this problem has even length and the sum is going to be odd //2) we can do a dp, using memo (top down) //we can have boundaries for left and right side and we can increment left or // decrement right side if we pick the left one or right one // 3) Note that if it's lee's turn, we just don't add anything as we are only adding alex's points so we determine whose turn it is if the number of numbers are remaining are even or odd // O(2^n) time | O(n*m)
1277.[DP] Count Square Submatrices with All Ones Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. Example 1: Input: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2.There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15.
// 1) we have to realize that trying to do it brute force will be O(n^3) or so // 2) so we find that dp may be a solution // 3) we look at all the ones, and if they have a value on the top, diagonal, and left neighbor // then we get the min value and add it to current matrix[i][j] value to get dp[i][j] // we do min because our square is limited by the smallest value
815. Bus Routes You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. • For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible. Example 1: Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6 Output: 2 Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. Example 2: Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12 Output: -1
// 1) we have to sort the arrays first in ascending order // 2) then we can build the graph of reachable buses from bus[i] // 3) afterwards we use binary search to find the source and target in the arrays // and add the source bus to seen (as well as the busindex to node with depth of 0) and the target to target // 4) we then use bfs to search for our target bus and returning the depth +1 which represents the busses // we had to explore to get there // otherwise, if we didn't find it, we iterate through the graph list(which is the bus index) for the // bus indexes and add them to our queue // O(N^2) time | O(N^2) space
1937. Maximum Number of Points with Cost Medium Given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. Return the maximum number of points you can achieve. abs(x) is defined as: • x for x >= 0. • -x for x < 0. 123 151 311 Example 1: Input: points = [[1,2,3],[1,5,1],[3,1,1]] Output: 9 Explanation: The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0). You add 3 + 5 + 3 = 11 to your score. However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score. Your final score is 11 - 2 = 9.
// 1) we realize we have to do dp // 2) to computer dp[i[j] we have to // take the max of the left side minus each column // and take the max right side minus each comlum, this is (O(m*n*n) // we can do better // so we can precompute the values for left and right side // 3) one way to calcuate the left side is that we have to // notice that the max calculation is similar, we just have to subtract 1 // and take the max of the above value // dp[i][j]= max(dp[i][j-1] -1, dp[i-1[j]) only for left side // right side is similar // O(n*m) time | O(n*m) space
1466. Reorder Routes to Make All Paths Lead to the City Zero There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. This year, there will be a big event in the capital (city 0), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder. Example 2: example: 0 <- 1 -> 2 <- 3 -> 4 reordere: 0 <- 1 <- 2 <-3 <- 4 Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] Output: 2 Explanation: Change the direction of edges from 1 to 2 and 3 to 4 so each node can reach the node 0 (capital). Example 3: Input: n = 3, connections = [[1,0],[2,0]] Output: 0
// 1)we have to add the parent and child, and child and parent in our adjacency list // since we may not explore all the nodes // 2) we also have to keep track of the directions initially // we can use a set <String> // 3) we increment our res if the direction is out degree
98. Validate Binary Search Tree Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: • The left subtree of a node contains only nodes with keys less than the node's key. • The right subtree of a node contains only nodes with keys greater than the node's key. • Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2,1,3] Output: true
// 5 // / \ // 3 6 // For this instance, we have to ensure that 5 is < the MAX_VALUE, and greater than MIN VALUE // 3 would have to be less than 5 which is the max value now and greater than min value // so we recursively put this restriction on each node and return true or false // TC: O(N) ....SC:O(d) d
349. Intersection of Two Arrays Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note: • Each element in the result must be unique. The result can be in any order.
// Create two hashsets to store both arrays and then use retainAll to get the // ones that exist in both sets
746. Min Cost Climbing Stairs You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor. Example 1: Input: cost = [10,15,20] Output: 15 Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top. Example 2: Input: cost = [1,100,1,1,1,100,1,1,100,1] Output: 6 Explanation: Cheapest is: start on cost[0], and only step on 1s, skipping cost[3].
// DP solution //we know that we can only take 1 or two steps, // for the first two, we have to keep the cost, since it is // an option to start in either // and for cost[2] for instance, we ask ourselves if 20+15 or 20+ 10 is ideal // we take 30, and the top floor, we ask ourrselves if we want to take 0 or the // dp[cost.len-2] since we can move two spaces or 30 +0, we take 15
1143. Longest Common Subsequence Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. • For example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings. Example 1: Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest common subsequence is "ace" and its length is 3. Example 2: Input: text1 = "abc", text2 = "abc" Output: 3
// DP, we set up a matrix of string and ask ourselves what is the longest // string subsequence in each // if character is the same, we take the top diagonal, // otherwise we take the max of the left and the value above // O(m x n) ..SC: O(m x n) or we can improve it to store only two rows to (O (min(n,m))
1699.[SQL] Number of Calls Between Two Persons Table: Calls +-------------+---------+ | Column Name | Type | +-------------+---------+ | from_id | int | | to_id | int | | duration | int | +-------------+---------+ Write an SQL query to report the number of calls and the total call duration between each pair of distinct persons (person1, person2) where person1 < person2. Return the result table in any order. The query result format is in the following example. Example 1: Input: Calls table: +---------+-------+----------+ | from_id | to_id | duration | +---------+-------+----------+ | 1 | 2 | 59 | | 2 | 1 | 11 | | 1 | 3 | 20 | | 3 | 4 | 100 | | 3 | 4 | 200 | | 3 | 4 | 200 | | 4 | 3 | 499 | +---------+-------+----------+ Output: +---------+---------+------------+----------------+ | person1 | person2 | call_count | total_duration | +---------+---------+------------+----------------+ | 1 | 2 | 2 | 70 | | 1 | 3 | 1 | 20 | | 3 | 4 | 4 | 999 | +---------+---------+------------+----------------+ Explanation: Users 1 and 2 had 2 calls and the total duration is 70 (59 + 11). Users 1 and 3 had 1 call and the total duration is 20. Users 3 and 4 had 4 calls and the total duration is 999 (100 + 200 + 200 + 499).
// LEAST selects the lower value as person1 column // Count(*) the number of calls between person1 and person2 // GROUP BY is the most important, as it lets us know what to count and the duration // of person1, person2
210. Course Schedule II There are a total of n courses you have to take labelled from 0 to n - 1. Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai. Given the total number of courses numCourses and a list of the prerequisite pairs, return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
// Similar to CourseSchedule 1, we set up our boolean visited array, graph array, and dp array // we create a new arrayList in the graphs for each course and it's corresponding prereqs // we recursively check if we visited each course and add to our result once we are done // most likely O(E+V) as we explore each vertex and edge
1048. Longest String Chain You are given an array of words where each word consists of lowercase English letters. wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. • For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad". A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1. Return the length of the longest possible word chain with words chosen from the given list of words. Example 1: Input: words = ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: One of the longest word chains is ["a","ba","bda","bdca"]. Example 2: Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] Output: 5 Constraints: • 1 <= words.length <= 1000 • 1 <= words[i].length <= 16 • words[i] only consists of lowercase English letters.
// The trick is traversing the graph in reverse order. //Like that "bac" -> "bc" -> "b". It is easier to calculate next candidate children in reverse order. //For example from "b" -> ... you should try all alphabet letters but in reverse order you can only remove 1 letter // "bc" -> "b" or "bc" -> "c". //Time Complexity = O(NxL), N is the words count, L is the length of words. //Space Complexity = O(NxL) for storing set of words and score are same. (Recursive stack can be O(N) space // at most.) // Map will be used to keep track of visited strings and the number of strings that make the chain // if You look at the picture we start at bdca which has 1 chain, which is just including itsel, bca has 2(bdca // and itself)
72. Edit Distance Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: • Insert a character • Delete a character • Replace a character Example 1: Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')
// This is DP. we calculate the Levenshtein distance by putting the the two strings into a matrix with an // empty string in the beginning // and for each we check how many actions will be needed to create the second char // with this, we can determine that we can produce the current value // by getting the min of the the surrounding values of the left, left-diagonal, and up // and if the chars are the same we get the left diagonal // TC is O(nxm) and space is O(nxm) although we can reduce it to O(min(n,m) by storing only two rows // algoexpert has a video
1893.Check if All the Integers in a Range Are Covered: You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi. Example 1: Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5 Output: true Explanation: Every integer between 2 and 5 is covered: - 2 is covered by the first range. - 3 and 4 are covered by the second range. - 5 is covered by the third range.
// This is not mine, but we create an array of size n =right-left+1 // of all the numbers that must be checked off to be true // we can make sure the range will work by using arr (x-left) to normalize // our array to the beginning of left and have a count // to keep track of how many nums we checked off in our range // O(n) time | O(n) space
188. Best Time to Buy and Sell Stock IV You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Input: k = 2, prices = [2,4,1] Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. Example 2: Input: k = 2, prices = [3,2,6,5,0,3] Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
// We can determine that it is a dp problem as we can build the solution up as we go. //We can create a helper profit array with k rows and length of the price array and ask ourselves what is the max profit that we can make up to price // We can determine that we will have math.max function of the previous value in the profit array which just means we don't sell in the current price, or the current price + the max of (-price[x] +profit[t-1][x]) where x is from 0 to d. //We do this because we want to limit the number of transactions we make, so we look at the previous //transaction and check the profit without that price
1684. Count the Number of Consistent Strings You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words. Example 1: Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"] Output: 2 Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'. Example 2: Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"] Output: 7 Explanation: All strings are consistent.
// We just keep track of the frequency and see if "words" exists in our frequency array
437. Path Sum III Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 Output: 3
// We use a hashmap to store the sums from our traversal // and the frequency // the key point to note is that int numPathToCurr = map.getOrDefault(sum-target, 0); // if the key exists already that means it was a valid path // for instance, when we reach 10 +5 +3 we will have a numPathtoCurr of 1 since 18-8=10, // and a sum of 10 already exists in our hashmap which means our answer // must be somewhere in between the prefix and the current node // for instance if we had a tree like this with target =8; // 10 // 5 // 5 // 3 // // At 3, with sum of 23, we would again ask 23-8=15, since 15 exists, we can assume that // it is a valid path // since we can take away the first 10, and 5 and we would be leftover with a sum of 8 //which is our target
55. Jump Game: Given an array of non-negative integers nums, 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. Example 1: Input: nums = [2,3,1,1,4] Output: true
// We use two variables to keep track of the current possible index we can reach // as soon as we reach that index, we can update our maxReach with that tempReach // for the next jumps
135.Candy aka Min rewards: There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: • Each child must have at least one candy. • Children with a higher rating get more candies than their neighbors. Return the minimum number of candies you need to have to distribute the candies to the children. Ex1: Input: ratings = [1,0,2] Output: 5
// another name for this is get min rewards in algoexpert // we calculate the number of candies from left to right for all local max // and then right to left for local mins // O(n) TC and O(n) SC //Input // [1,0,2] // [1, 1, 2] left to right which is incorrect // [2, 1, 2] so we have to traverse right to left
207.[Graph/DFS/BFS] Course Schedule There 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. • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise, return false. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible
// bfs with graph solution, we create a graph structure link with arraylists // we can use an array for the degrees to check the number of indegrees // and add it to queue //Another solution: DFS // Graph solution using dfs + dp memoization // we create a dfs by creating a boolean array of visited courses // and a dp array to store the result // we go through each of the graph links to see if there's any cycle
238. Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. Note: Please solve it without division and in O(n).
// calculate the products of the left side of the array (the 0th index will be 1), // and then calculate the right side(starting at tail) // and then multiply each other to get the answer //Input: [1,2,3,4] //Left: [1,1,2,6] notice start w/ 1, we don't include 4 as 4 // is rightmost //Right: [24,12,4,1] we don't include 6
724. Find Pivot Index Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1. Example 1: Input: nums = [1,7,3,6,5,6] Output: 3 Explanation: The pivot index is 3. Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 Right sum = nums[4] + nums[5] = 5 + 6 = 11
// calculate the sum all numbers in array // use a separate for loop to calculate the leftsum, and check if the sum- leftSum-currentNums is equal // 100%
1123. Lowest Common Ancestor of Deepest Leaves: Given the root of a binary tree, return the lowest common ancestor of its deepest leaves. Recall that: • The node of a binary tree is a leaf if and only if it has no children • The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1. • The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.3 / \ 5 1 / | / \ 6 2 0 8 / \ 7 4 Input: root = [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest leaf-nodes of the tree. Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.
// compare and store max Depth and node if the left and right nodes have same depth // tried boolean but didn't realize they wanted the longest depth, even if it's a leaf with no siblings // O(n) time | O(n) space
88. Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. Example: Input:nums1 = [1,2,3,0,0,0], m = 3nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
// compare the tails of each arrays and set the higher number at the end of num 1 // since the space of num1 is m+n // edge case for when tail2 is not finished add another while loop for the remaining num 2
448.Find All Numbers Disappeared in an Array Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6]
// create a freq table to keep track of the nums that appears // and then add all the index to resulting array that has a freq of 0 // O(n)
75. Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Example 1: Input: nums = [2,0,2,1,1,0]Output: [0,0,1,1,2,2] Example 2: Input: nums = [2,0,1]Output: [0,1,2]
// create three variables to keep track of the frequency of 0, 1, 2 // and then use a loop to place them in the array
62. Unique Paths Medium A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Example 1: Input: m = 3, n = 7 ...Output: 28 Example 2: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down
// do a dp with recursion and memoization, the initial conditions are key // store the values of the results in array and return if there's a value in memo[i][j] // and since we know that the robot can move only two directions (down, and right) we can easily add it recursively
10. Regular Expression Matching Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: • '.' Matches any single character. • '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Example 1: Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa", p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: Input: s = "ab", p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)".
// dp using memoization // Input: s = "aab", p = "c*a*b" // There are several thigns to note: // 1) We can use a top down dp with i pointing to string s and j pointing to p // 2) when we have '.' it is pretty simple to cover, we can assume it matches with string s[i] // 3) when we encounter * an index ahead, we have two choices, either we repeat the previous character or use // an empty string, we do both to find solutions // if we choose to repeat we can increment i since we know it matched // if we choose not to repeat, then we increment j+2 since // we want to skip ahead two indexes and the * character
1448.[Tree] Count Good Nodes in Binary Tree: Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree. 3 / \ 1 4 / / \ 3 1 5 Input: root = [3,1,4,3,null,1,5] Output: 4 Explanation: Nodes in blue are good. Root Node (3) is always a good node. Node 4 -> (3,4) is the maximum value in the path starting from the root. Node 5 -> (3,4,5) is the maximum value in the path Node 3 -> (3,1,3) is the maximum value in the path.
// for this we have to realize that we have to keep track of // of the max value in a path, otherwise it is not a good node // in our example in the right, the path: 3,4,1, the max value is 4 // so 1 is not a good node since it is smaller than our max // O(n) time | O(n) space
841. Keys and Rooms There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise. Example 1: Input: rooms = [[1],[2],[3],[]] Output: true Explanation: We visit room 0 and pick up key 1. We then visit room 1 and pick up key 2. We then visit room 2 and pick up key 3. We then visit room 3. Since we were able to visit every room, we return true. Example 2: Input: rooms = [[1,3],[3,0,1],[2],[0]] Output: false Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
// graph problem, we just have to traverse each room based on the key using dfs // but it is better to use a explicit stack than a recursive stack as there can be a lot of vertices and edges // O(n*m) time | O (n) space
230. Kth Smallest Element in a BST Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Example 1: Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 Output: 3
// inorder traversals give you the numbers in least to greatest in order in a BST
1899.Merge Triplets to Form Target Triplet: A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): • Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. ○ Ex, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]. Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise. Ex 1: Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] Output: true->Explanation: Perform the following operations: - Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]
// much concise solution compared to mine // this one only takes in a triplet if all numbers are equal or less than our target // if so, stores the max into a new array of size 3 // we then check if the new array matches the target array // O(n) time | O(1) space
269.[Graph] Alien Dictionary There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language. Example 1: Given the following words in dictionary, ["wrt","wrf", "er", "ett","rftt"] The correct order is: "wertf". Example 2: Given the following words in dictionary, ["z", "x"] The correct order is: "zx".
// note that we are given an ordered list of strings where for example // wrt comes before wrf // first we want to build the relationships by building a graph // using a hashmap<char, hashset> where character will lexiographically // come before the value(s) in the hashset //we also keep track of the number of indegrees (which for a char with 0 means // it will come first) // we use it in our topological sort by using a stringbuilder // and a queue. we append to the queue chars from our hashmap key // with an indegree of 0 and add it to our stringbuilder solution // We traverse the values from the key and decrement it and if it's 0 // we add to queue
Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children. From <https://leetcode.com/problems/binary-tree-paths/> Example 1: 1 / \ 2 3 \ 5 Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
// notice that you have to return a list of string so we use stringbuilder // for concatenation // notice that we set the length to backtrack if we finished with left and right side // O(n) time | O(d) space, d for depth of tree
543.[Tree] Diameter of Binary Tree: Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. Example: 1 / \ 2 3 / \ 4 5
// really important that we store the max as a global variable // since we include roots in the subtrees and may not want to include it
104. Maximum Depth of Binary Tree Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3.
// recursive solution public int maxDepth(TreeNode root) { if (root==null) return 0; int left=(maxDepth(root.left)); int right=maxDepth(root.right); return Math.max(left, right)+1; }
538. Convert BST to Greater Tree: Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints: • The left subtree of a node contains only nodes with keys less than the node's key. • The right subtree of a node contains only nodes with keys greater than the node's key. • Both the left and right subtrees must also be binary search trees.
// reverse the inorder tree traversal // public int sum=0; public TreeNode convertBST(TreeNode root) { helper(root); return root; } public void helper(TreeNode root) { if (root==null) return ; helper(root.right); sum+=root.val; root.val=sum; helper(root.left); }
1512. Number of Good Pairs Given an array of integers nums. A pair (i,j) is called good if nums[i] == nums[j] and i < j. Return the number of good pairs. Example 1: Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. Example 2: Input: nums = [1,1,1,1] Output: 6 Explanation: Each pair in the array are good. Example 3: Input: nums = [1,2,3] Output: 0
// store in freq table, and use combination formula to generate max combinations // n_C_r = n! / (r! * (n-r)!)
845. Longest Mountain in Array aka Longest Peak You may recall that an array arr is a mountain array if and only if: • arr.length >= 3 • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: ○ arr[0] < arr[1] < ... < arr[i - 1] < arr[i] ○ arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray. Ex1: Input: arr = [2,1,4,7,3,2,5] Output: 5
// the first step is to find a peak, and then traverse the left // and right side of the peak to find a length // you traverse left side by checking if it is strictly decreasing // you traverse the right side by checking if it is also strictly decreasing // TC: O(N) since we only traverse each values 2 or three times so like O 2N // SC: O(1)
997. Find the Town Judge In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. Example 1: Input: N = 2, trust = [[1,2]]Output: 2 Example 2: Input: N = 3, trust = [[1,3],[2,3]]Output: 3 From <https://leetcode.com/problems/find-the-town-judge/>
// the town judge is trusted by N-1 people // so we can decrement person that trusts someone else // and increment the trusted person
450. Delete Node in a BST Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: 1. Search for a node to remove. If the node is found, delete the node. 5 / \ 3 6 /\ \ 2 4 7 Example 1: Input: root = [5,3,6,2,4,null,7], key = 3 Output: [5,4,6,2,null,null,7]
// there are four cases we have to consider when we delete a node // in a binary search tree: // 1) node doesn't have left or right - return null // 2) node only has left subtree- return the left subtree // 3) node only has right subtree- return the right subtree // 4) node has both left and right - find the minimum value in the right subtree, set that value to the currently found // node, then recursively delete the minimum value in the right subtree // O(log(n)) time | O(d) space where d is the depth of the tree
124.[Tree] Binary Tree Maximum Path Sum A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any path. -10 / \ 9 20 / \ 15 7 Input: root = [-10,9,20,null,null,15,7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42
// to get the max path sum, we need to consider negative numbers, and if we are // going to exculde them // the other issue that may arise is that we store the sum of multiple paths // in like a triangle shape and continue to build on it, this would be incorrect // to resolve this problem we store a max value, that will store all these triangles as possible solutions // and we return only the root.val + the max of the left and right branch
102. Binary Tree Level Order Traversal Medium Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ]
// use a helper function and specifying the depth // we use this depth to add it in our list of list by using it as an index // if depth is equal to the the size of the result list, then add a new sublist // use preorder traversal/DFS
139. Word Break Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Input: s = "leetcode", wordDict = ["leet","code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code". Example 2: Input: s = "applepenapple", wordDict = ["apple","pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
// use boolean dp to store if a word exists by marking the // end of the word as true if it's in the dictionary // if the last index is true, then it is possible to create word breaks // in the word
279. Perfect Squares Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9.
// use dynamic programming to create solutions // we ask ourselves at the i-th index, how many perfect // squares make this number // We use to loops, outer loop from 0 to n and the inner loop from 1 to sqrt(n) dp[0] = 0 , dp[1] = dp[0]+1 = 1 , dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{ dp[3]+1, dp[0]+1 } = 1 dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } = Min{ dp[4]+1, dp[1]+1 } = 2 dp[n]=Min(dp[n-i*i] + 1, dp[n-i*i-1]+1)..where 0 < i < sqrt(n)
1173. Immediate Food Delivery I Table: Delivery +-----------------------------+---------+ | Column Name | Type | +-----------------------------+---------+ | delivery_id | int | | customer_id | int | | order_date | date | | customer_pref_delivery_date | date | +-----------------------------+---------+ delivery_id is the primary key of this table. The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it). If the customer's preferred delivery date is the same as the order date, then the order is called immediate; otherwise, it is called scheduled. Write an SQL query to find the percentage of immediate orders in the table, rounded to 2 decimal places. The query result format is in the following example.
// we basically get the immediate orders/total_orders *100 // where immediate order is the number of rows where order_date=customer_pref_delivery_date // and we divide that by the total number of orders // rounded to two decimal places
128.Longest Consecutive Sequence: Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. Example 1: Input: nums = [100,4,200,1,3,2] Output: 4
// we can do sort and just figure out the longest sequence // but this solution would be O(nlogn) // but we can store all the values in a hashmap // and we will use the hashmap to check if a num to the //right and left of the current num exists in the map // we will also denote the value to false so we don't traverse these numbers // twice // TC: O(n) and SC: O(n)
45.[Array] Jump Game II: Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. Ex 1: Input: nums = [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
// we can do this problem using dp but it's O(n^2) // we just take note of the maxindex we can reach before having to jump // which means storing a temp variable so we can update our // maxReach once we reached maxReach // TC: O(n) SC: O(1)
896. Montonic Array An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic. Ex1: Input: [1,2,2,3] Output: true Ex 2: Input: [6,5,4,4] Output: true
// we can just go through the array to see if it's increasing or decreasing // we set them to true for cases where we have [2222] // O(n) TC, O(1) SC
1913. Maximum Product Difference Between Two Pairs: The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). • For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16. Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference. Example 1: Input: nums = [5,6,2,7,4] Output: 34
// we just get the two highest number and two lowest numbers // O(N) time | O(1) space
1971. Find if Path Exists in Graph There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex start to vertex end. Given edges and the integers n, start, and end, return true if there is a valid path from start to end, or false otherwise. Example 1: Input: n = 3, edges = [[0,1],[1,2],[2,0]], start = 0, end = 2 Output: true Explanation: There are two paths from vertex 0 to vertex 2: - 0 → 1 → 2 - 0 → 2 Example 2: Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], start = 0, end = 5 Output: false Explanation: There is no path from vertex 0 to vertex 5.
// we can use BFS, DFS, Disjoint set // we did BFS here // 1) we create the graph structure using hashset[] array // 2) we need to use a boolean [] to keep track of visited nodes // so we do not revisit the same nodes // 3) we use a queue to add all the unvisited neighbors
107. Binary Tree Level Order Traversal II Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ]
// we create a list of arraylists and we have a counter for level that we use to // add to the list based on the level, note that we will have the top level at index // and so forth, so we would have to reverse the list
518.Coin Change 2 You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. Example 1: Input: amount = 5, coins = [1, 2, 5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1
// we create dp of size n, we get the number of ways to generate an amount by // adding the previous i-coin index and storing it using dp // we basically check for each coin, how many ways can we make the nums up to n // (e.g. if i=3 and coin is 2, // // we know that at dp[3-1]=1 so we can add 2 to 1 have a total of 3 to include coin 2) // note that we have coins in the outer loop since we want to generate all the ways we can use a coin // to make up the ith amount // TC: O(nd) SC: O(n) // TC: O(nd) where n is the amount and d is the denomination SC: O(n) // amount: 5 //coins: [1,2,5] // 0 1 2 3 4 5 //dp: [1,1,2,3,5,9]
581. Shortest Unsorted Continuous Subarray: Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return the shortest such subarray and output its length. Example 1: Input: nums = [2,6,4,8,10,9,15] Output: 5
// we find the min and max number that is out of order first // to do that we have to check the left and right side of our // current index and see if it's increasing // then we check for where our min and max number // should be located in the array // and we get the left and right index of those to get our answer // O(n) time | O(1) space
297.[Tree/Design/Deque] Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. Input: root = [1,2,3,null,null,4,5] Output: [1,2,3,null,null,4,5]
// we first do a preorder traversal to get the string form of the treenode // if there's a null we add X instead, and separate each node by a comma // in our stringbuilder // when we deserialize they add a deque since it's double ended, you have easy access to // the head and tail // note that we reconstruct this tree and create new TreeNodes // (O(n) time for traversing all nodes | and O(n) where n is the number of nodes we store in deque
198. House Robber You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: nums = [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
// we have to ask ourselves if the current value+ (value to houses down) // is greater than previous value, we get the max
189. Rotate Array: Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
// we have to mod k so we don't have to // do extra work, mod by length // if 0, return the array // we start to copy the array from length-k // using an additional array // and then writing to our given array // there's few O(1) space solutions where we can // do three reverses // there's another solution where we can cyclically // swap the next num in array, i+k th index
18. 4Sum Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: • 0 <= a, b, c, d < n • a, b, c, and d are distinct. • nums[a] + nums[b] + nums[c] + nums[d] == target You may return the answer in any order. Example 1: Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
// we iterate through the array to check if the diff exists in our hashmap so we can // add to our solution // then we iterate to the left side until that num to add the sum to our hashmap // so we avoid adding the same solutions // our hashtable will slook like this: key: sum=1, values: [ [-1,2] , [ 0, 1]] // notice how we append to our list if we encountered this sum already // covered in algoex // Average: O(n^2) worst: O(n^3), SC: O(n^2)
42.Trapping Rain Water: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Ex1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
// we just have to calculate the left max of a given index and right max // we do that by storing it in two arrays // TC: O(n) SC: O(n)..could potentially have a space complexity of O(1) \ //AlgoEx
628. Maximum Product of Three Numbers: Given an integer array nums, find three numbers whose product is maximum and return the maximum product. Example 1: Input: nums = [1,2,3] Output: 6
// we just have to find the three highest nums using three // variables and keep track of the index of these locations to find // the second highest num and third highest // edge case where we have [-100, -50, 2, 1, 4] // we just need to get the two lowest to account for negative // nums and multiply it by the highest which is 4 in this case -100*-50*4
409.[String/Array] Longest Palindrome: Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here. Example 1: Input: s = "abccccdd" Output: 7
// we know that in a palindrome, two sides would have to be the same // so we can take an even number of characters as an answer // and one other in the middle // O(n) time | O(1) space
103.Binary Tree Zigzag Level Order Traversal Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ]
// we recursively add the values in a preorder fashion into a list of list and // use the depth to add to the specified index // we use a modular to indicate that we to add the second level and on in a different manner // i.e add to the beginning of list // O(n)
56.Merge Intervals: Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Ex 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
// we sort the array based on the starting index // and then we compare the end index with the starting index to see if there's any overlap // TC: O(nlogn) SC: O(n)
354. Russian Doll Envelopes You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). Note: You cannot rotate an envelope. Example 1: Input: envelopes = [[5,4],[6,4],[6,7],[2,3]] Output: 3 Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). Example 2: Input: envelopes = [[1,1],[1,1],[1,1]] Output: 1
// we sort the envelopes by the width or height, we sorted it by height // we create a dp array to store how many ways we stack envelopes // {{2,3}, {3,4}, {2,5}, {4,6}} our dp array would be {1,2,1,3} // we have two loops where we iterate to i from 0, so we can check if // each envelope fits the criteria and add onto it's dp if it does // if an envelope fits, we get the max of dp[j]+1 of the element to the left, or current // element dp[i] since envelopes will fit in each other so we build it up // TC: O(n^2) SC:O(n)
447. Number of Boomerangs: You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Return the number of boomerangs. Example 1: Input: points = [[0,0],[1,0],[2,0]] Output: 2
// we store the distance and the frequency of the distances of points in a hashmap // note that for distance, you don't have to calculate the square root... // distance=sqrt((x2-x1)^2 + (y2-y1)^2)) // we then have to multiply the freq * freq-1 since that is number of // permutations we will have for a given frequency // O(n^2) time | O(n) space
532.K-diff Pairs in an Array: Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: • 0 <= i , j < nums.length • |nums[i] - nums[j]| == k Notice that |val| denotes the absolute value of val. Ex1:Input: nums = [3,1,4,1,5], k = 2 Output: 2
// we store the frequencies of each nums[i] in // HashMap iterate through all the keys to get rid of duplicates // since each answer has to be unique // special cases for when k==0, we would havve to make sure that // there's more than one frequency of that element // note that we check for x+k which is key
226. Invert Binary Tree Given the root of a binary tree, invert the tree, and return its root. Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]
// we traverse the tree in each level and store the Treenode to switch the left and the right nodes public TreeNode invertTree(TreeNode root) { if(root==null) return null; TreeNode right= invertTree(root.right); TreeNode left=invertTree(root.left); root.right=left; root.left=right; return root; }
322.Coin Change You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2], amount = 3 Output: -1
// we use dp of size n+1 to store the number of coins possible to make n amount // we expect to require less than n amount of coins // we have to ask ourselves for the current dp[i] if dp[i] is smaller than dp[i-coin] // i-coin indicates the last value we can add to to have n (i.e. if i=3 and coin is 2, // we know that at dp[3-1]=1 so we can add 2 to 1 have a total of 3 to include the coin 2 in our solution) // Note we have coins in inner loop compared to coin change 2, since we want to generate the optimal coins // at the ith index // TC: O(N*d) where d is the denomination and SC is O(amount) // 0 1 2 3 4 5 6 7 8 9 10 11 [1 , 2, 5] 11 // 0 1 1 2....
1557. Minimum Number of Vertices to Reach All Nodes Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi. Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. Example 1: Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]] Output: [0,3] Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3]. Constraints: All pairs (from i, to i) are distinct.
// we want vertexes that have no indegree
1302. Deepest Leaves Sum Given the root of a binary tree, return the sum of values of its deepest leaves.
//BFS traversal // you traverse in level order and and reset the sum at each level // so you will only get the sum at the deepest level // O(n) time | O(n) space
300.Longest Increasing Subsequence Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. Example 1: Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: Input: nums = [0,1,0,3,2,3] Output: 4 Example 3: Input: nums = [7,7,7,7,7,7,7] Output: 1
//Dp, Note this problem can be done with binary search to reduce the time complexity to O(nlogn) // dynamic programming we store the number of ways we can get to an index i // by iterating from j to i and storing the max possible paths in a variable and add one // to the current max value and store it into our dp array, and get the max paths so far https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/ // for example take {2, 5, 3, 7, 11, 8} if we insert 8 at the end, our solution can be {2,3,7,8} we know that // 8 is less than 11 and greater than 7 so we can insert it after 7, we want to minimize the number at the end //O(nlogn) time | O(n) space
105. Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] // preorder gives you the root first inorder = [9,3,15,20,7] // tells you the left and right side if you know the root 3 / \ 9 20 / \ 15 7
//Recursion
101. Symmetric Tree Easy Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3
//Recursive solution // BFS in pic public boolean isSymmetric(TreeNode root) { return isMirror(root, root); } public boolean isMirror(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) return true; if (t1 == null || t2 == null) return false; return (t1.val == t2.val) && isMirror(t1.right, t2.left) && isMirror(t1.left, t2.right); }
183.[SQL] Customers Who Never Order Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything. Table: Customers. +----+-------+ | Id | Name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+ Table: Orders. +----+------------+ | Id | CustomerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+ Using the above tables as example, return the following: +-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
//The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the //right table (table2). The result is 0 records from the right side, if there is no match.
1010.Pairs of Songs With Total Durations Divisible by 60: You are given a list of songs where the ith song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0. Example 1: Input: time = [30,20,150,100,40] Output: 3
//we can use a freq array table of sizze 60 to keep track of divisibility // you have to realize that we have to count all the // nums that are divisible by 60 or if they're not, // we have add the freq of nums by taking 60-num % 60 // for instance for 110 %60, the mod is 50, so all that is required is 10 // to get 10 we do 60- (110 % 60)
637. Average of Levels in Binary Tree Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1: Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
BFS
235. Lowest Common Ancestor of a Binary Search Tree: Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."
BFS/DFS public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { return helper(root, p, q); } private TreeNode helper(TreeNode root, TreeNode p, TreeNode q){ if (p.val < root.val && q.val < root.val) return helper(root.left, p, q); else if( p.val > root.val && q.val > root.val) return helper (root.right, p, q); else return root; }
287. Find the Duplicate Number Medium Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one duplicate number in nums, return this duplicate number. Follow-ups: How can we prove that at least one duplicate number must exist in nums? Can you solve the problem without modifying the array nums? Can you solve the problem using only constant, O(1) extra space? Can you solve the problem with runtime complexity less than O(n2)? Example 1: Input: nums = [1,3,4,2,2]Output: 2 Example 2: Input: nums = [3,1,3,4,2]
Create a frequency table or tortoise and hare cyclic detection:
53. Maximum Subarray Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6
DP/ kadane's algorithm 0 1 2 3 45 6 7 8 Input: [-2,1,-3,4,-1,2,1,-5,4] DP: [-2,1,-2,4,3,5,6, 1,5]
110. Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1. Example 1: 3 / \ 9 20 / \ 15 7 Input: root = [3,9,20,null,null,15,7] Output: true
DFS
236. Lowest Common Ancestor of a Binary Tree Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)." Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3.
DFS
617. [Tree]Merge Two Binary Trees: You are given two binary trees root1 and root2. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree. Return the merged tree. Note: The merging process must start from the root nodes of both trees Example : 1 2 3 / \ / \ / \ 3 2 + 1 3 => 4 5 / \ \ / \ \ 5 4 7 5 4 7 Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7] Output: [3,4,5,5,4,null,7]
DFS
690. Employee Importance You have a data structure of employee information, which includes the employee's unique id, their importance value, and their direct subordinates' id. You are given an array of employees employees where: • employees[i].id is the ID of the ith employee. • employees[i].importance is the importance value of the ith employee. • employees[i].subordinates is a list of the IDs of the subordinates of the ith employee. Given an integer id that represents the ID of an employee, return the total importance value of this employee and all their subordinates. ID=1(importance=5) / \ ID=2(import=3) ID=3(Importance=3) Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1 Output: 11 Explanation: Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.
DFS solution: static Map<Integer, Employee> emap; public static int getImportance2(List<Employee> employees, int queryid) { emap = new HashMap(); for (Employee e: employees) emap.put(e.id, e); return dfs(queryid); } public static int dfs(int eid) { Employee employee = emap.get(eid); int ans = employee.importance; for (Integer subid: employee.subordinates) ans += dfs(subid); return ans }
70. Climbing Stairs You 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? Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
DP n: 3 dp: [0,1,2,3]
181. [SQL] Employees Earning More Than Their Managers The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id. +----+-------+--------+-----------+ | Id | Name | Salary | ManagerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | NULL | | 4 | Max | 90000 | NULL | +----+-------+--------+-----------+ Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager. +----------+ | Employee | +----------+ | Joe | +----------+
SELECT a.Name AS 'Employee' FROM Employee AS a, Employee AS b WHERE a.ManagerId = b.Id AND a.Salary > b.Salary;
938. Range Sum of BST Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high]. Example 1: 10 / \ 5 15 / \ \ 3 7 18 Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 Output: 32 Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
int sol=0; public int rangeSumBST(TreeNode root,int L,int R) { dfs(root,L,R); return sol; } //Doing a DFS preorder traversal recursively public void dfs(TreeNode root, int L,intR) { if(root !=null){ if(L<=root.val &&root.val <=R){ sol +=root.val; } if(root.val >L ) { dfs(root.left,L,R); } if(root.val <R){ dfs(root.right,L,R); } }
595.[SQL] Big Countries There is a table World +-----------------+------------+------------+--------------+---------------+ | name | continent | area | population | gdp | +-----------------+------------+------------+--------------+---------------+ | Afghanistan | Asia | 652230 | 25500100 | 20343000 | | Albania | Europe | 28748 | 2831741 | 12960000 | | Algeria | Africa | 2381741 | 37100000 | 188681000 | | Andorra | Europe | 468 | 78115 | 3712000 | | Angola | Africa | 1246700 | 20609294 | 100990000 | +-----------------+------------+------------+--------------+---------------+ A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million. Write a SQL solution to output big countries' name, population and area. For example, according to the above table, we should output: +--------------+-------------+--------------+ | name | population | area | +--------------+-------------+--------------+ | Afghanistan | 25500100 | 652230 | | Algeria | 37100000 | 2381741 | +--------------+-------------+--------------+
select name, population, area from World where population > 25000000 OR area > 3000000;