BLIND 75

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

152. Maximum Product Subarray Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array.

Keep 2 running products l: begginging to end r: end to beginning Keep a res which is max(res, max(l,r)) at each iteration if l or r == 0 reset it's product to 1

54. Spiral Matrix Given an m x n matrix, return all elements of the matrix in spiral order.

Keep track of top, bottom, left, and right bounds Loop while l<=r and t<=b add to an ans vector Change direction when you meet a bound move the bound return ans vector

206. Reverse Linked List Given the head of a singly linked list, reverse the list, and return the reversed list.

Approach 1: Iterative need to keep track of current node, previous, and next start previous as nullptr start current as head start next as head->next loop: current->next = prev prev = current current = next next = next->next continue until next is null return prev Approach 3: Recursive 2: keep track of head->next set head->next to NULL return recursiveHelper(temp, head) recursiveHelper(curr, prev) if cur is null return null temp = curr->next curr->next = prev if temp = null return cur return recursiveHelper(temp, cur)

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)."

Approach 1: Recursion if node is null return null if node is p or q pass itself up call func on left and right if both are null return null if one is not null return the not null if both are not null pass itself up, it's the ancestor

49. Group Anagrams Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Create a map (string : vector<string>) Loop through strs sort each string push unsorted string to map[sortedString] Loop through map Build out answer

70. Climbing Stairs You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Create a parallel vector, dp dp[0] = 0 dp[1] = 1 dp[2] = 2 dp[i] = dp[i-1] + dp[i-2] return dp[n] Can also solve only keeping track of prev 2

15. 3Sum Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.

Sort the array hold 1 constant use left and right pointers left is right after the const right is at the end while (left < right) if > 0 decrement the right if < 0 increment the left if const + left + right = 0 add to the ans move left and right until the last of their duplicates return the ans Time: O(nlogn) + O(n*n) = O(n*n) Space: O(1)

20. Valid Parentheses Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order.

Use Stack Push open parentheses to the stack pop when closed parentheses appear and complement top check if stack ends up empty

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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Use dp max at house i = max(house[i-1], house[i-2] + house[i]) can optimize by only remembering the past 2 houses

11. Container With Most Water You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container.

Use l and r pointer (at ends) Calculate rect area (diff of indices * lower height) move in the lower bound keep track of max

213. House Robber II You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

[0,1,2,...,n-1,n] Case 1: 0 to n-1 Case 2: 1 to n Do normal House Robber on these cases return max

102. Binary Tree Level Order Traversal Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

check for empty input make vector<vector<int>> res make queue of nodes push root to queue set count to 1 loop while q is not empty loop for the count add root to temp vector push children to queue count how many have been pushed push vector to answer

572. Subtree of Another Tree Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.

compare root and subroot if no match recursively compare root->left and subroot recursively compare root->right and subroot if you reach the leaves, return false

100. Same Tree Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

if the trees are the same, their subtrees are the same Perform dfs if both p and q exist return true if only one exist return false if they are not equal return false return dfs(left, left) && dfs(right, right)

55. Jump Game You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise.

keep minJump = num of jumps needed to get to a spot from which we can get to the end Start with the last element (minJump = 0) iterate backwards at each back-step, increase minJump by 1 if nums[i]>=minJump we can make it to the end reset minJump to 0 return true if minJump of element 0 is 0

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.

left and right pointers keep track of maxLeft, maxRight Loop if left lower than right (update max OR add to total) THEN move l if right lower than left (update max OR add to total) THEN move r continue until l and r meet

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].

longest increasing subsequence = LIS Last element is an increasing subsequence LIS[i] = LIS[index of next greater value] + 1

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. A subarray is a contiguous part of an array.

loop through each num keep a running sum sum = max(sum+num, num) res = max(res, sum) return res

104. Maximum Depth of Binary Tree Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

maxDepth(root) = max(maxDepth(left), maxDepth(right)) + 1 Base Cases: if the root is null depth is 0

200. Number of Islands Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Loop through grid DFS at each island and turn visited to 0s keep a count

79. Word Search Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Loop through the grid if you find the beggining letter dfs for the rest of the word mark visited as '0' along the way change letter back for other searches

5. Longest Palindromic Substring Given a string s, return the longest palindromic substring in s.

Loop through the string at each character / pair of identical characters (pal of len 2) expand until max pal. is reached store the longest pal Expand func I: String, left, right O: String (biggest expanded pal. substr) if the left and right chars are not the same return "" while left and right remain inbounds +- 1 keep expanding while the next left and right are the same return substr(l, r-l+1) Time: O(n) + O(n) = O(n) Space: O(1)

143. Reorder List You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → ... → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → ... You may not modify the values in the list's nodes. Only nodes themselves may be changed.

Make a stack of ListNode pointers push all the nodes to the stack build list from the stack OR reverse half the list and do it that way

62. Unique Paths There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109.

Make m x n vector of 1s starting from vec[1][1], value = above + left return bottom right value

647. Palindromic Substrings Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.

Case 1: Odd length Using each char in s as a starting palindrome expand w that as the center as long as still a valid palindrome Case 2: Even length do the same but for pairs of identical, adjacent pairs

347. Top K Frequent Elements Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

hashmap: element->frequency maxHeap of k elements (compare based on frequency) Make vector out of heap

268. Missing Number Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

total = nums.size() * [nums.size()+1] / 2 Add up the nums subtract total-sum

125. Valid Palindrome A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.

Check left and right if alpha make lower compare

3. Longest Substring Without Repeating Characters Given a string s, find the length of the longest substring without repeating characters.

Create Hash Table (char : index) create maxSize int to return Sliding Window l and r pointer if s[r] not in map add to the map move r if s[r] in the map update maxSize move l to map[l] remove chars along the way

207. 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.

BFS uses the indegrees of each node. We will first try to find a node with 0 indegree. If we fail to do so, there must be a cycle in the graph and we return false. Otherwise we set its indegree to be -1 to prevent from visiting it again and reduce the indegrees of its neighbors by 1. This process will be repeated for n (number of nodes) times. For DFS, in each visit, we start from a node and keep visiting its neighbors, if at a time we return to a visited node, there is a cycle. Otherwise, start again from another unvisited node and repeat this process. We use todo and done for nodes to visit and visited nodes.

226. Invert Binary Tree Given the root of a binary tree, invert the tree, and return its root.

Base Case: if root is null return null call invertTree on left call invertTee on right swap left and right return the root

105. Construct Binary Tree from Preorder and Inorder Traversal Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Beginning of the Preorder is the root Everything to the left of the root in Inorder is to the left in the tree Same goes for right Keep track of (global) preorderIndex (where the current tree we're building is rooted) Make helper(preorder, inorder, start, end) Create a new root val = preorder[preorderIndex] increment preorderIndex Find where this root->val appears in inorder for root->left apply helper to everything in inorder to the left of the root->val for root->right apply helper to right section of root->val return the root

33. Search in Rotated Sorted Array There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.

Binary Search Cut in half search through sorted section

153. Find Minimum in Rotated Sorted Array Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in O(log n) time.

Binary Search Check if left bound > right bound if so, you have the rotated section

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.

Bottom-up DP utilizes a matrix m where we track LCS sizes for each combination of i and j. If text1[i] == text2[j], LCS for i and j would be 1 plus LCS till the i-1 and j-1 indexes. Otherwise, we will take the largest LCS if we skip a charracter from one of the string (max(m[i - 1][j], m[i][j - 1]).

57. Insert Interval You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion.

Create a vector<vector<int>> res Keep counter i and size n Case 1: No Overlap: intervals[i][1] < newInterval[0] add intervals[i] to res increment i Case 2: Overlap: newInterval[1] >= intervals[i][0] adjust new interval bounds newInterval[0] = min(newInterval[0], intervals[i][0]); newInterval[1] = max(newInterval[1], intervals[i][1]); increment i Case 3: No more overlap add the rest of the intervals to res

21. Merge Two Sorted Lists You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.

Create dummy head as new ListNode() Create cur node = dummy Loop while a list is not done compare head of list1 to head of list2 attach lesser to the returning list continue until both run out

19. Remove Nth Node From End of List Given the head of a linked list, remove the nth node from the end of the list and return its head.

Create head clone (temp) move it n spaces ahead if (temp==NULL) return head->next Create new head copy (del: will end right before the node to be deleted) while temp->next exists increment both temp and del del->next = del->next->next

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.

Create parallel array of booleans Go through the dict for all matches, mark the end position of the word true move starting point to the next true position in the dp array repeat if last position in the array is true return true

39. Combination Sum Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Create vector<vector<vector<int>>> dp (target+1) dp[i] represents the combos that add up to i Make first element {{}} Loop through candidates loop from the candidate to target Loop through all of the vectors in dp[j-i], i is the loop var (these are all the ways to make up a sum=j-i from candidates) add i to the vector dp[j-i] push this to dp[j] return dp[target]

417. Pacific Atlantic Water Flow There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c). The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.

Find cells that will reach Pacific (dfs from pacific) Find cells that will reach Atlantic (dfs from atlantic) Find what cells are in both

73. Set Matrix Zeroes Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix. You must do it in place.

Loop through all of grid if you find a 0, mark that col's top and row's start with 0 keep track of firstRow and fistCol as separate bools Go through and fill out 0s

230. Kth Smallest Element in a BST Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Inorder Traverse (iteratively) until kth value Create a stack Infinite Loop While the root is not null push to the stack keep going left until NULL root = top of stack pop stack decrement k if k == 0, its the kth smallest return else root = root->right loop again

133. Clone Graph Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; }

Keep a global map to keep track of nodes (int : Node*) recursiveHelper(Node*) if node->val is in the map return that node pointer from map Create new node with node->val Add it to the map Loop through all of the neighbors new_node->neighbors.push_back(rec(neighbor)); return the new node

1. Two Sum Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Keep a hashmap {num : index} Loop through array look for complement in hash table complement = target - num if found, return indices if not add num and index to hash table

121. Best Time to Buy and Sell Stock You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Keep track of res and minSeen Loop through prices if price < minSeen update minSeen if price > minSeen update res = max(res, price-minSeen)

128. Longest Consecutive Sequence Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

Put nums into a set Loop through nums if n-1 is not in set, it's the start of a sequence determine the size keep track of longest return longest

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.

Recursive function I: TreeNode* root, TreeNode* left, TreeNode* right O: bool At every node pass down itself as a left or right bound left bound if going right right bound if going left call the recursive function on it's children keep passing down the bounds narrow the bounds until leaves reached or break bounds

424. Longest Repeating Character Replacement You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations.

Sliding Window find longest consecutive substring with <=k other characters Keep track of left and right bounds hashmap of char:int maxRepeating in the substring MaxLen of substring Loop through string increment char's val in map Update maxRepeating=max(itself, char's new map val) if windowSize - maxRepeating > k Move left bound update count of left bound char in map Maxlen = max(itself, curSize)

217. Contains Duplicate Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Sort and loop thorugh

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.

Sort the intervals by start Add the first interval to the ans Iterate through intervals if the current start > the last end push my current interval else the current start <= the lase end the last end is the max of the last end and the current interval's end return ans Time: O(nlogn) + O(n) Space: O(1)

48. Rotate Image You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Transpose along main diag reverse each row

141. Linked List Cycle Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false.

Two pointers, fast and slow Move fast 2 times Move slow 1 time Wait for intersection or null

242. Valid Anagram Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Use Hashmap to count

91. Decode Ways A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. The test cases are generated so that the answer fits in a 32-bit integer.

numDecodings(s[p:]) = numDecodings(s[p+1:]) + numDecodings(s[p+2]) However the second part only applies if the 1<s[p:p+2]<26 Use parallel array dp(n+1) dp[n]=1 Iterate Backwards add up the next, and the next's next if valid return dp[0] Can also make const space if you keep track of only next 2

238. Product of Array Except Self Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.

use dp[3][nums.size()] first row is product of everything to the left of dp[0][i] second is products of everything to the right third row you mutliply the first 2 Optimization: Use a single variable for left product Create right product array Loop from left to right and update left product and array


संबंधित स्टडी सेट्स

NCLEX Style Practice Questions: Nitroglycerin Management

View Set

Lesson 4: Configuring IP Networks

View Set

Hardware Security Modules for Government

View Set

Methodology in Cognitive Neuroscience

View Set

MD Life License Chapter 2: Life Insurance Basics

View Set