LeetCode

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

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. Example 1: Input: nums = [1,2,3,1] Output: true

USE HASHSET Create a hashset of values seen so far while iterating through if current value is in seen, return true else add value to see if loop finishes, return false

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. Example 1: Input: nums = [3,4,5,1,2] Output: 1 Explanation: The original array was [1,2,3,4,5] rotated 3 times.

DIVIDE AND CONQUER Because we want an O(log n) alg, we have to cut our problem in half recursively, To find min, we need to keep track of the start and end of our subarray if we are comparing 2 or fewer nums, return the smaller or the singular otherwise find the mid of the subarray (use i + (j - i)/2 to avoid integer overflow) if the number in the mid is smaller than both the number to its left and end of the subarray, then you've found the smallest num so return that otherwise, if the num at mid - 1 is bigger than the number at num[end], search from mid+1 to end or search from start to mid-1

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. Example 1: Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

The idea is to check how many palindromes you can make by extending from each character. for example: for string aaa a count++ then check a(a)a (a was already checked so only need to check that i - 1 == i + 1) count++ return 2 from this single a. to implement this: have an outer loop that iterates through each character in the string from each character, have a for loop that has 2 pointers that go out left and right from i (acting as the middle of the palindrome) so naturally, you need one more inner for loop that goes left and right but right starts as i + 1 to keep track of even palindromes in both inner loops, check that left and right are in bounds and the characters at both indices are the same (and thus a palindrome)

Invert Binary Tree Given the root of a binary tree, invert the tree, and return its root. Example 1: Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]

USE DFS recursively search down the right and left nodes of each root and swap them return the root if its null or swap is complete

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. Example 1: Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1

USE DFS OF GRAPH Create a visited 2d array and have all values as false (in python for an MxN array, use [[False]*n for _ in range(m)] to init array) Go through all values of input grid and dfs when you reach an unvisited '1' increment count of islands each time to dfs - mark current node as visited - visited all up, down, left, right neighbors that are also unvisited and '1'

Number of Weak Characters You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei. Return the number of weak characters. Example 1: Input: properties = [[5,5],[6,3],[3,6]] Output: 0 Explanation: No character has strictly greater attack and defense than the other.

USE A SORT sort properties by attack in descending order, and ascending order for defense when they have the same attack for ex: [[6, 4] [6,6] [5,3] [3,2] [3,4]] keep track of the max defense seen so far for each sorted value - if value[i][1] < max_defense, then you have a smaller attack and defense than the previously seen max, so increment num weak chars - update max_def accordingly

Basic Calculator II Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). Example 1: Input: s = "3+2*2" Output: 7

USE A STACK init a stack, a sign variable (as '+' to represent a positive), and a num value as 0 for each character in the string - if the current character is a digit, set num = num * 10 + character - otherwise -- if the last seen sign is +, stack.push(num) -- if the last seen sign is -, stack.push(-num) -- if the last seen sign is *, stack.push(stack.pop() * num) ---> you're multiplying the last seen number (with correct pos/neg) -- if the last seen sign is /, stack.push(stack.pop()/num) -- sign = character, and reset num to 0 now add up everything in the stack in order and return the result

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. Example 1: Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1

USE AN ADJACENCY GRAPH APPROACH make a visited[][] and helper method that recursively visits any node that isn't visited and is part of the island our goal is to visit every connected component of a node and call that an island to do so, iterate through the 2D grid and look for any land mass that has yet to be visited. Once found, call the private helper method to mark every connected component as visited. Now increment count and continue the loop. once the loop is done, every land mass will be visited and each unique island counted.

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. The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations.

USE BACKTRACKING Basic setup: - list of lists that add up to target - sort nums array backtrack: - if remain < 0, return (base case when you've overshot the target) - if remain == 0, add the current list of nums to answer list (base case when sum of current list == target) otherwise, - iterate from current index in nums to end - add nums[new_idx] to current list of nums and backtrack - remove the last entry in current list and repeat return list of lists

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. Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa.

USE CHAR DICT AND SLIDING WINDOW outer loop iterates the right pointer set most used letter to Math.max(most used letter, ++frequency[currChar - 'A']) to find the most commonly used letter so far while loop with sliding window verification to verify sliding window: check if the number of elements in the subarray is still greater than the number of allowed replacements and the most freq letter (basically ur checking if every character in this subarray can be changed into 1 matching character with the allowed replacements) in this loop, we have to decrement freq for each of the letters we remove by incrementing the left pointer at the end of the loop we check if this new valid subarray is the longest one we've seen return the maxLength

Valid Anagram Given two strings s and t, return true if t is an anagram of s, and false otherwise. Input: s = "anagram", t = "nagaram" Output: true

USE COUNT ARRAY Create a count array of size 26 to keep track of how many times each letter in string s is used iterate thru t after populating the array and now decrement the count array for each letter used if each letter is used the same number of times in s as it is in t, then they are valid anagrams and every element of the count array should be 0 if there's some value that is not a 0, then t is not a valid anagram

Sliding Window Maximum You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Example 1: Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7]

USE DEQUE keep a result array, and keep track of its current idx keep a window deque of idxs that could have a max -> will be sorted by idx AND value [from greatest to least] for each value of nums array - while deque is not empty and the first item in the deque is not in i - k + 1 of i, use window.poll() to remove it as it is no longer an idx included in the window - while deque is not empty and the LAST item (like a stack) is less than nums[i], use window.pollLast() to remove it as it can't be the next potential max - add i to window - if i - k + 1 > 0 (first window is populated), result[i -k+1] = nums[window.peek()] (use first seen, largest value in answer) return result

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 non-empty path. Example 1: Input: root = [1,2,3] Output: 6 Explanation: The optimal path is 2 -

USE DFS set a global max variable for ease DFS into sub trees to find largest path so far Options: 1. curr.val 2. pathSum(curr.left) + curr.val 3. pathSum(curr.right) + curr.val 4. left_sum + right_sum + curr.val Base case: curr node is null, return 0 the global max sum can be calculated at each node (which is the case that the current node is basically the end of our path) which is max(global max, all options) to further recurse, however, we return the value that is max(option 1, option 2, or option 3) as we can pick ONLY 1 out of the two possible subtrees to follow as a path

The Maze There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination. The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the

USE DFS (as a graph) create a visited array each recursion call will be to a new position create an array of +- 1 to move in up,down,left,right directions keep a list of possible new positions by going in each direction for each one of these directions: - use position parameter to get curr_position - while canKeepRolling -- increment a new x and y by adding the 2 parts of the direction array -- if new pos x and y are within bounds, unvisited, and the space isn't "1", update curr_position -- else set canKeepRolling to false - if curr_position is the target position, return true - add curr_pos to list of possible new positions add original_position to visited array for each of the new positions in list - if recursion on new position, return True return false

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

USE DIVIDE AND CONQUER array nums is of length n+1 First use dc to find the smallest value: - start i,j at 0 and n and go until i >= j. - update i to be mid + 1 when nums[mid] > nums[j] -- (you know the smallest value must be on the right half of the -- array) - update j to be mid when nums[mid] <= nums[j] rotated to the right = i reset i and j to be 0 and n again - while i <= j - get a true_mid value by doing (mid+rotated)%n - if nums[true_mid] == target then you're done return true_mid - if nums[true_mid] > target, then i = mid + 1 - else, j = mid - 1 if nothing is found by the end, return -1

LRU Cache Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least re

USE DOUBLY LINKEDLIST AND HASHMAP Map: key-> cache_key, value-> Node(cache_key, cache_value) Dummy_head = new Node(-1,-1) Dummy_tail = new Node(-1,-1) global capacity constructor: - dummy_head.next = dummy_tail - dummy_tail.prev = dummy_head add_node_to_start: - new_start.next = old_start - new_start.prev = dummy_head - dummy_head.next = new_start - old_start.prev = new_start delete_node: - prev_copy = delete_this.prev - next_copy = delete_this.next - prev_copy.next = next_copy - next_copy.prev = prev_copy get: - if key isn't in map, return -1 - save node and value from map - delete node.key in map - delete node in DLL - add new node(key, value) to start - put (key, dummy_head.next) in map put: - if key is in map, save node -- remove node.key from map -- remove node from DLL - if map.size() == capacity, -- remove dummy_tail.prev.key from map -- remove dummy_tail.prev from DLL - add new node to start - put (key, dummy_head.next) in map

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.

USE DP The goal is to find the largest size square of 1's and keep track of the squares you've seen so far. Bellman equation: dp[i][j] = 0 if the current value is a 0 or i == 0 or j == 0 otherwise, = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) ^ checks if we're visiting a 1 and if we are, then checks if this is the corner to a bigger square for example: [1, 1] [1, 2] has a 2 in the bottom because the other 1s surrounding it mean it's actually part of a 2x2 and not just a 1x1 by itself! to find solution: loop through all i and js and on each iteration, update dp if visiting a 1. After updating dp[][], add to a counter of # of squares which you can return. at dp[m][n], biggest square seen so far.

Detect Cycle in LinkedList 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. (3,-4) -> 2 -> 0- > -4 -> (cycle back to 2) Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

USE FAST AND SLOW POINTER approach 1: hashset and check if you've visited the node (space complexity O(N) approach 2: replace the value of nodes visited to smth out of range (space complexity O(1) but changes values) *****approach 3: use a fast and slow pointer that eventually meets if there's a cycle set fast and slow to head loop while fast.next and fast.next.next are != null in loop, inc slow by 1 (slow = slow.next) and inc fast by 2 (fast = fast.next.next) if fast == slow at any point, return that there is a cycle at the end of the loop, the fast pointer has reached the end, so return no cycle

Best Time to Buy and Sell Stocks II You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve. Example 1: Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), prof

USE GREEDY Iterate through array len-1 - anytime i < i+1, add difference to profits return sum of all profits

Minimum Window Substring Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string. Example 1: Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.

USE HASHMAP AND SLIDING WINDOW populate the hashmap with characters in t and their frequency iterate through s while keeping track of how many of the letters in t we've found and which ones are left for loop iterates the right pointer while fixing the left if the charAt(r) is in the hashmap, decrement the freq in the map and increase number of letters found while the num of letters found == t.length() then we need to increment the left pointer until we've gotten rid of all the unnecessary chars but first, make sure to check if this window is the smallest valid window seen if any characters we remove happen to be in t, decrement found, increment that character's hashmap, and exit the while loop return the smallest valid window seen

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. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

USE HASHMAP WITH SORTED STRING AS KEY create a HashMap that maps a sorted string to an anagram. iterate through the list of strings convert the string into a char[] which we can sort later by using str.toCharArray() sort char[] and convert it back into a string by using sortedStr = String.valueOf(char []) check if map containsKey(sortedStr) and if it doesn't, make new list add str to list at map.get(sortedStr) return list of lists

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. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].

USE HASHMAPS Create a hashmap that maps the num visited with its index. Iterate through each value in the array while checking if the key = target - nums[i] is in the hashmap. if yes, return an array with map.get(key) and i else, put(nums[i], i)

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. Example 1: Input: nums = [1,2,3,4] Output: [24,12,8,6]

USE PREFIX AND SUFFIX ARRAYS build a prefix array by setting the value of pre[0] to 1 and then the following pre[i] = pre[i-1] * nums[i-1] (this sets the current value to the product of the elements before it and the previous element) to build the suffix array, do the same but set post[end] = 1 and the following post[i] = post[i+1] * nums[i+1] (this sets the current value to the product of the elements after it and the next value) the result array can be built by result[i] = pre[i] * post[i]

Merge k Sorted Lists You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example 1: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6

USE PRIORITY QUEUE (or divide and conquer for better space complexity) For each linked-list, populate a PQ with the nodes (use new PriorityQueue<>((a,b) -> a.val-b.val) as the lambda expression that compares the values of two nodes) If the PQ is empty here, just return null Save a head node as the first poll While PQ isn't empty-> Then poll each node in order and set it as the curr.next, update curr to curr.next If in this while PQ becomes empty, set curr.next to null

Reverse a Linked List Given the head of a singly linked list, reverse the list, and return the reversed list. 1->2->3->4->5 5->4->3->2->1 Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]

USE RECURSION AND RECURRENCE RELATIONS base case: if head == null or head.next == null rec case: create a new listnode that will be the previous node by doing p = reverseList(head.next) assign that nodes .next as the head node (head.next.next = head;) now erase the connection from head to head.next (head.next = null;) return p to give a reversed version of head and head.next

Best Time to Buy or 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. Example 1: Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

USE RUNNING MAX AND MIN while iterating, keep track of the lowest price, the maxProfit check if the current price is less than lowest price if yes, then set lowest price to current price otherwise, if the current price - lowest price is > than maxProfit, set maxProfit to that value return maxProfit after all iterations

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. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.

USE RUNNING SUM AND MAX SUM keep track of the current sum and the max sum by using Math.max to track the current subarray's sum, set sum = Math.max(sum + nums[i], nums[i]) (which sets the sum to the continuous subarray or restarts the subarray based on which value is bigger) to track the current max sum, set max = Math.max(max, sum) (which sets the max to the biggest subarray sum we've seen as the current sum may be smaller than one before it) return the max

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. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]

USE SORT AND SKIP DUPLICATES AND 2 POINTER 1. create the answer list 2. sort the array so duplicates are next to each other and largest values are on the right while the smallest are on the left 3. iterate through the array while in bounds and while the values are negative (otherwise there's no sum that reaches 0) 4. if this is isn't the first iteration, and the value is a repeat of the last one, skip this case 5. otherwise, set j to i + 1 and k to length - 1 (j and k are two pointers) -> if the sum is 0, add this triplet to answer list then skip all repeat values of j and k -> else if the sum > 0, decrease sum by decrementing k (make k a smaller num) -> else sum < 0, increase sum by incrementing j (make j a bigger num) 6. return list of all triplets

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

USE SORTING to sort based on start times use Arrays.sort(intervals, (a,b)->Integer.compare(a[0], b[0])); then create an ArrayList<int[]> to store the merged int arrays. Create and add to that list a newInterval int array that corresponds to intervals[0] now while iterating through all the intervals, compare the end time of that interval with the start time of the new interval -> if this start time is ≤ the end time, set the newInterval's end time to the max of either interval -> otherwise, set newInterval to check against as the current one being visited and add that to the list (so the algo only adds intervals after they have been as merged as possible) return the list as an int[] by doing merged.toArray(new int[merged.size()][])

Longest Valid Parentheses Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring . Example 1: Input: s = "(()" Output: 2 Explanation: The longest valid parentheses substring is "()". Example 2: Input: s = ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()".

USE STACK populate stack with indices of parentheses keep track of longest length so far for each character in the string - if char is '(', push it to the stack - otherwise, pop -- if the stack is now empty, push this idx to the stack -- else, update longest by finding max between itself and idx - stack.pop (i.e. last potential start to a set of parentheses) return longest basically we update the stack with potential starts (i.e. '(' ) and then pop when we encounter a ')' until the only thing in the stack is the earliest start. if its empty then this is the new earliest start.

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. Example 1: Input: s = "()" Output: true

USE THE STACK! create a stack onto which you push the respective closing bracket (i.e. ']', ')', or '}') when encountering the open variant. otherwise, if the current character in the string s is not an open bracket, check if stack is empty or if the popped value is != to the current character (we've encountered the wrong closing bracket) if yes to either, then return false else at the end of the iterations, return true

Course Schedule II 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 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

USE TOPOLOGICAL SORT Create a adjList map (key: course #, value: list of all classes that require this course as a pre-req) Create a list of indegrees of size num_courses for pre-req in pre-reqs - increment in degree for course# pr[0] - add pr[0] to the adjList of pr[1] Create a queue of nodes with 0-indegree while queue isn't empty - pop queue for next course to add to order - for all courses that require the current one, -- remove 1 indegree, and add to queue if new indegree == 0 - count iterations if iterations in while loop < num_courses, return empty array [] otherwise return order visited.

Container with Most Water Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Notice that you may not slant the container. Example 1: Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

USE TWO POINTER while leftPtr < rightPtr keep track of current water contained by doing curr = Math.min(height[l], height[r]) * (right - left) keep track of max water contained by doing max = Math.max(curr, max) we then want to change the pointer that is at the smaller height in hopes of finding something taller after loop, return max

Longest Substring Without Repeating Characters Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.

USE TWO POINTER AND HASHMAP We must create a hashmap (or an ascii char[] of size 256) that maps characters in the string to their index. The outer for loop will iterate through the string incrementing the right pointer. In each iteration, check if (not a while loop) the curr char is already in the hashmap and update the left pointer to be the max of (j, map.get(currChar) + 1 update map.put(currChar, i) update maxlength to (max, right - left + 1) return max after loop finishes

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

USE UPPER AND LOWER BOUNDS We will use tail end recursion to solve this problem. We want to keep track of the lower and upper bounds of each node. When going left, we set the next node's upper value to the node we just visited and keep the lower bound as is. Likewise, while going right, we set the next node's upper bound to what it was previously but update the lower bound to the node we just visited. We then return false if a node falls outside those bounds and return true when we reach a null case;


Ensembles d'études connexes

12.1.14 - Windows System Tools - Practice Questions

View Set

Law Psych and Mental Health Final

View Set

W08: Cloud and Virtualization Security

View Set

FINC exam 2 practice/HW/clicker questions

View Set

Post Lab Questions: Sc. Inquiry & Lab Safety

View Set

N125 Case Study Heart and Neck Muscles

View Set

Migration: Push and Pull Factors

View Set