Meta LeetCode

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

50. Pow(x, n) Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

1. Base Cases: If n is 0, return 1. If n is 1, return x. 2. Check Memoization Table: If the result of pow(x, n) has already been computed and stored in the memoization table, return it. 3. Recursive Binary Exponentiation: If n is even, calculate pow(x, n/2) * pow(x, n/2). If n is odd, calculate x * pow(x, n-1). Store the result in the memoization table. 4. Handle Negative Exponents: If n is negative, calculate 1 / pow(x, -n) since x^-n is equivalent to 1 / x^n.

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.

1. Create Num -> Frequency Map: Iterate through the array and count the frequency of each element using a hash map. 2. Create Frequency -> Num Map: map each frequency to a list of numbers that have that frequency 3. Return Top K Elements: Think, what's the highest possible frequency? The length of the array. Start at this frequency, loops down, and append the elements at each frequency until you reach k

921. Minimum Add to Make Parentheses Valid A parentheses string is valid if and only if: It is the empty string, It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string. For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))". Return the minimum number of moves required to make s valid.

1. Scan the String from Left to Right: Initialize two variables, leftCount and rightCount, to keep track of the number of unmatched opening and closing parentheses, respectively. Iterate through each character in the string from left to right. If the character is '(', increment leftCount. If the character is ')' and there are unmatched opening parentheses (leftCount > 0), decrement leftCount. Otherwise, increment rightCount. 2. Return Total Additions: After scanning the entire string, return the sum of leftCount and rightCount, as these represent the minimum number of additions needed to make the parentheses valid.

31. Next Permutation A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.

1. Find the First Decreasing Element: Start scanning from the end of the array to find the first element that is smaller than its next element. Let this element be at index i. If no such element is found, reverse the entire array. 2. Find the Smallest Element Larger Than the First Decreasing Element: Again, start scanning from the end of the array. Find the smallest element larger than the element at index i. Let this element be at index j. 3. Swap the Two Elements: Swap the elements at indices i and j. 4. Reverse the Rest of the Array: Reverse the sub-array from index i+1 to the end of the array.

88. Merge Sorted Array You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

1. Initialize Pointers: Initialize three pointers: p1 pointing to the last non-zero element in nums1, p2 pointing to the last element in nums2, and p pointing to the last element in the merged array. 2. Merge Arrays: Start from the end of both arrays. Compare the elements pointed by p1 and p2, and place the larger element at position p in nums1. Decrement p and the respective pointer (p1 or p2) for the element that was placed. 3. Handle Remaining Elements: If there are any remaining elements in nums2 after merging, copy them to nums1.

163. Missing Ranges You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are within the inclusive range. A number x is considered missing if x is in the range [lower, upper] and x is not in nums. Return the shortest sorted list of ranges that exactly covers all the missing numbers. That is, no element of nums is included in any of the ranges, and each missing number is covered by one of the ranges.

1. Initialize Variables: Initialize a list to store valid missing ranges. 2. Traverse Sorted Array: Iterate through the sorted integer array nums:For each element num in nums, check if it is equal to lower.If num is equal to lower, increment lower by 1.If num is greater than lower, there is a missing range between lower and num - 1. Add this missing range [lower, num - 1] to the result list.Update lower to num + 1. 3. Check Last Element: After traversing nums, check if lower is less than or equal to upper. If so, there is a missing range from lower to upper. Add this missing range [lower, upper] to the result list. 4. Return Result: Return the list containing all valid missing ranges.

Subarray Sum Equals K Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array.

1. Initialize Variables: Initialize a variable count to keep track of the number of subarrays whose sum equals k. Initialize a variable sum to store the current prefix sum. Initialize a hash map to store the frequency of prefix sums encountered, map 0 to 1. 2. Iterate Through the Array: Iterate through the array nums. At each index i, update the prefix sum sum by adding nums[i] to it. 3. Check for Subarray Sum Equals k: Check if the difference (sum - k) exists in the hash map. If it exists, add the frequency of (sum - k) to the count, as it represents the number of subarrays ending at index i whose sum equals k. 4. Update Hash Map: Increment the frequency of the current prefix sum sum in the hash map. 5. Return Total Count: After iterating through the array, return the total count of subarrays whose sum equals k.

270. Closest Binary Search Tree Value Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.

1. Initialize Variables: Initialize a variable to store the closest value found so far. Initialize a variable to store the minimum difference between the target value and any node value encountered. 2. Traverse the BST: Start from the root of the BST and iterate down the tree. At each node, compare its value with the target value and update the closest value and minimum difference accordingly. Move to the left or right child depending on the comparison with the target value. Go left if the target is smaller than the current node value and right otherwise 3. Return Closest Value: After traversing the entire BST, return the closest value found.

426. Convert Binary Search Tree to Sorted Doubly Linked List Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.

1. Perform In-order Traversal: Use in-order traversal to visit each node of the binary search tree in ascending order. During the traversal, keep track of the previously visited node to establish the connections in the doubly linked list. 2. Update Pointers: As you visit each node during in-order traversal, update the "next" pointer of the previous node and the "previous" pointer of the current node to establish the connections in the doubly linked list. 3. Adjust Head and Tail Pointers: Once the in-order traversal is complete, adjust the head and tail pointers of the doubly linked list to form a circular structure.

71. Simplify Path Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path. In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.

1. Tokenize Path: Split the input path string into tokens using the '/' character as the delimiter. 2. Process Tokens: Create a stack for path elements Iterate through the tokens obtained from the input path. If the token is ".", it represents the current directory, so ignore it. If the token is "..", it represents the parent directory, so pop the top directory from the stack. If the token is not empty or ".", it represents a directory name, so push it onto the stack. 3. Reconstruct Simplified Path: After processing all tokens, reconstruct the simplified path using the directories stored in the stack. Join the directories in the stack using the '/' character as the separator. If the stack is empty, return "/" as the simplified path.

346. Moving Average from Data Stream Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Implement the MovingAverage class: MovingAverage(int size) Initializes the object with the size of the window size. double next(int val) Returns the moving average of the last size values of the stream.

1. Use a Queue to Store Elements: Use a queue to store the elements of the sliding window. As new elements are added to the stream, enqueue them into the queue. 2. Maintain a Rolling Sum: Maintain a rolling sum of the elements currently in the sliding window. As elements are enqueued or dequeued, update the rolling sum accordingly. 3. Calculate Moving Average: To calculate the moving average, divide the rolling sum by the number of elements in the sliding window. Return the moving average whenever requested.

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

Check if current node in range, if so, add to running total if curr node < high, search right if curr node > low, search left return running total

146. 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 recently used key. The functions get and put must each run in O(1) average time complexity.

Approach: Doubly Linked List with Hash Map Initialize Variables: Initialize a doubly linked list to store the keys and values of the cache in the order of their usage. Initialize a hash map to store the mapping from keys to their corresponding nodes in the doubly linked list. Initialize capacity variable to keep track of the maximum capacity of the cache. Set head and tail sentinel nodes so adding and removing nodes is easier 2. Get Operation: If the key exists in the cache, retrieve its value from the hash map and move its corresponding node to the front of the doubly linked list (indicating recent usage). If the key doesn't exist, return -1. 3. Put Operation: If the key already exists in the cache, update its value and move its corresponding node to the front of the doubly linked list. If the key doesn't exist:If the cache is at full capacity, remove the least recently used node (from the end of the doubly linked list) and its corresponding key from the hash map.Add the new key-value pair to the front of the doubly linked list and update the hash map.

987. Vertical Order Traversal of a Binary Tree Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree.

Assign each node a row and col value. Map from row and col to node.val. Save the min col, max col, and max row in this process Iterate through the dictionary, by col and row. If there are multiple values at a given coordinate, sort and append that. If there is only one, append the one value (guess you could sort nonetheless) return the list with all the values

301. Remove Invalid Parentheses Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order.

Basic Jist: Run DFS on string after removing and keeping paren keep track of max length and result set use a recursive function base case is if your current index is too big, then you check if string is greater than max length (reset result and add) or if it is equal to max length (add to result list) Else, check char if char is '(', recurse on string with the paren and without the paren if char is ')' recurse on string without the paren, and only with if the leftcount is greater than rightcount otherwise, recurse on the string with the add char and then remove at end Runtime: O(2^n), for every paren, you might do two recursive calls Spacetime: O(n), process one character at a time

973. K Closest Points to Origin Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

Build a min heap (heapq, heapify) go through the points, calculating the distance and adding to heap loop up to k and pop from heap o(n log k)

129. Sum Root to Leaf Numbers You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children.

Calculate newTotal as (total*10)+node.val if node is leaf, return new total if have left and right, return sum of recursive call on left and right with newTotal otherwise, return recurse on left or right with new tota

708. Insert into a Sorted Circular Linked List Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list. If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted. If the list is empty (i.e., the given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node.

Check if head is empty, if so return node(val) create two pointers, one at head and one at head.next if they are equal, insert after head (only one element) in a while true loop if right is head, means we did a full loop can insert anywhere (3->3->3), break if left <= val <= right, break if left <= val >= right, break if left >= val <= right, break else move the pointers to next insert between left and right

1091. Shortest Path in Binary Matrix Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that: All the visited cells of the path are 0. All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path.

Check if top left and bottom right are zero, otherwise no path return -1 Do bfs in all directions, checking if neighbor value is 0, and save the distance along with the neighbor in queue If you're at the bottom right, return the distance you've saved in the queue

863. All Nodes Distance K in Binary Tree Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order.

Convert the binary tree into a graph run breadth first search from the target, going up to the distance k

766. Toeplitz Matrix Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

Create a helper function to help you know if a given diagonal is toeplitz. Helper takes a row and col. Iterate down and right, checking that everything was equal to the element found at the provided row and col. If it isn't return False. Return True if you make it to the end of the loop Loop through the first column checking toeplitz at every row Then loop through the first row checking toeplitz

Nested List Weight Sum You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. The depth of an integer is the number of lists that it is inside of. For example, the nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth. Return the sum of each integer in nestedList multiplied by its depth.

Go through list while tracking depth and total. If see an integer, add getInteger() * depth. Otherwise, add recurse on list with depth + 1 to total Return total

Kth Largest Element in an Array Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Can you solve it without sorting?

Heap Answer create a min heap (heapq) loop through nums pushing on the heap. When the length of the heap is greater than k, heapq pop return heap[0] QuickSelect Answer Define a quickSelect function that takes arguments nums and k. This function will return the kthk^{th}kth greatest element in nums (the nums and k given to it as input, not the original nums and k). Select a random element as the pivot. Create left, mid, and right as described above. If k <= left.length, return quickSelect(left, k). If left.length + mid.length < k, return quickSelect(right, k - left.length - mid.length). Otherwise, return pivot. Call quickSelect with the original nums and k, and return the answer.

138. Copy List with Random Pointer A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list. None of the pointers in the new list should point to nodes in the original list. Return the head of the copied linked list. The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node. Your code will only be given the head of the original linked list.

Initialize a hash map to store mappings from original nodes to their corresponding copied nodes. Iterate through the linked list, making copies of the nodes and mapping from original node to copy Iterate through the list again, getting each copy and linking the copy's next and random to the mapped next and random Time Complexity: O(n) Space Complexity: O(n)

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

Initialize an empty list that will hold all the right side elements initialize a dictionary that tells you if the current depth has been occupied Recursive traverse curr->right->left for every iteration, check if current level is already occupied, otherwise populate at that depth and append to list

Valid Palindrome II Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Iterate Through the String: Traverse the string from both ends simultaneously. Check for Palindrome: Check if characters at the current positions are equal. If they are, move to the next pair. Remove at Most One Character: If characters don't match, attempt to remove either the left or right character and check if the resulting substring is a palindrome. Continue Checking: Continue this process until you've either confirmed that the string can be made into a palindrome by removing at most one character or determined that it's not possible. Return Result: Return True if it's possible to form a palindrome by removing at most one character, otherwise return False.

827. Making A Large Island You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s.

Iterate through the grid and when you see a 1, run bfs/dfs marking each 1 with an id marker keeping track of how big the island is so far. Return that size and hash it island id -> island size Go through the grid again this time looking for 0. When you see a zero, pull the neighboring unique ids and sum up the sizes. Get the max of that total + 1 (for the zero you flipped) and current max. Check if a max was ever set, it's possible everything is covered in which case return n*n. Otherwise return the max size

398. Random Pick Index Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning.

Iterate through the provided nums map from number to a list containing all the indices where the number is found For pick, get the list of possible indices for the target generate a random number between 0 and the length of the possible indices. Return the value found at the random index

Buildings With an Ocean View There are n buildings in a line. You are given an integer array heights of size n that represents the heights of the buildings in the line. The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height. Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order. MUST ITERATE LEFT TO RIGHT

Keep a stack of indices of the buildings that have an ocean view so far At every iteration, check if the building at the top of the stack is blocked and pop within a loop return that stack

249. Group Shifted Strings We can shift a string by shifting each of its letters to its successive letter. For example, "abc" can be shifted to be "bcd". We can keep shifting the string to form a sequence. For example, we can keep shifting "abc" to form the sequence: "abc" -> "bcd" -> ... -> "xyz". Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in any order.

Key obserservation: you can tell the pattern by comparing the chars in an individual string For a given string, go char by char and see the difference from one char to another (do [ord(char) - ord(char)] % 26 for the 26 characters in the alphabet. Put all the difference together as a string and you now have a key. Map by pattern -> list of strings that follow that pattern. Do this for every string Loop through the keys and collect the values

791. Custom Sort String You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string. Return any permutation of s that satisfies this property.

Make a frequency table for the char in s loop over order, appending to the answer the number of times that character appears in s Loop over the remaining chars in the freq dict that were not in order and append to answer return the answer

670. Maximum Swap You are given an integer num. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get.

Map each digit to the last index it occurs in (left to right) loop through the digits in num. then, loop from 9 down for possible digits. If the possible digit exists in your map and its index is later than the one you're on in num, that's your guy! Do the swap and return that num Runtime: O(n) SpaceTime: O(n)

Dot Product of Two Sparse Vectors Given two sparse vectors, compute their dot product. Implement class SparseVector: SparseVector(nums) Initializes the object with the vector nums dotProduct(vec) Compute the dot product between the instance of SparseVector and vec A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector. Follow up: What if only one of the vectors is sparse?

Map from index to value for a vector loop through those keys, check if they are in the other vector as well, multiply and add to total

1249. Minimum Remove to Make Valid Parentheses Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Method 1. Use a stack Loop through the string. If you see a '(', add index to the stack. If you see a ')', check stack. Nothing in stack means save the remove index. Else, just pop the stack. Add every index in stack in removeList Loop through string again, checking if index is in the remove list Pro: only pass forward, code is simpler Con: added space (using stack) Method 2. No stack Keep leftParenBalance, firstPassString If see '(', increase balance If see ')', check balance if balance > 0, decreaseBalance, add char else, skip return early if the first pass ended with a balance of 0 Do the same thing, but backwards for ')' balance and return the passTwo string

Lowest Common Ancestor of a Binary Tree III Given two nodes of a binary tree p and q, return their lowest common ancestor (LCA). Each node will have a reference to its parent node

Naive Solution Create path from one node to the parent Create path from other node to the parent, check at each step if that node is in the first path O(1) space solution two pointers, each point to the given nodes while they're not the same, move up parents. When one reaches the root, move him to the opposite node (if started on p, start on q and vice versa) Return either pointer (they'll be equal) Runtime: O(n)

162. Find Peak Element A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time.

Need to determine if you're on a rising or falling slope Go to the middle and see what kinda slope you're on based on the right and left If you're rising, (left < mid < right), go right else you're falling, go left

691. Stickers to Spell Word We are given n different types of stickers. Each sticker has a lowercase English word on it. You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker. Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.

Need to watch the leetcode video on this again

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.

Perform DFS searching for p and q curr is true if the current node is equal to p or q left is true if the left subtree has p or q right is true if the right substree has p or q if two of curr, left, or right are true, that's the lca save it in pointer return left || curr || right

Random Pick with Weight You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index. You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).

Preprocess Weights Array: Given an array of positive integers representing the weights, preprocess it to calculate the cumulative sum of weights. Generate Random Number: Generate a random number between 1 and 0, multiply by total weight Binary Search for Interval: Use binary search to find the index of the interval where the random number falls. Return Result: Return the index of the chosen element (left pointer)

1424. Diagonal Traverse II Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.

Remember, not every row is the same length You can do bfs starting from the top left corner. add the current element to the ans. If you're on the first column and not on the last row, add the element to the bottom to the queue If you're not on the last column, add the element to the right You MUST visit neighbors in this order (ensures you do it in the diagonal direction)

314. Binary Tree Vertical Order Traversal Binary Tree Vertical Order Traversal Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right.

Run breadth first search. Append node and x coord to queue. Append node to list found at nodeDict[x coord] If x coord < start, that's the new start if x coord > end, that's the new end loop from start to end, appending the list of nodes found at each x coord Time Complexity: O(n) Space Complexity: O(n)

65. Valid Number A valid number can be split up into these components (in order): A decimal number or an integer. (Optional) An 'e' or 'E', followed by an integer. A decimal number can be split up into these components (in order): (Optional) A sign character (either '+' or '-'). One of the following formats:One or more digits, followed by a dot '.'.One or more digits, followed by a dot '.', followed by one or more digits.A dot '.', followed by one or more digits. An integer can be split up into these components (in order): (Optional) A sign character (either '+' or '-'). One or more digits. Given a string s, return true if s is a valid number.

Save state of seenDigit, seenExponent, seenDot all as False Go through every character if the character is a digit, set seenDigit to flase elif it's a sign, return false if index > 0 and the character before is not an exponent elif char is an exponent, if already seenExponent or haven't seen a digit, return False. Set seenDigit to False and seenExponent to True elif char is '.' if aleady seen dot or seenexponent, return false. Set seenDot to True Else return false Return seendigit, must ensure last thing you've seen is a digit

1004. Max Consecutive Ones III Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.

Sliding window problem (left and right pointer) always move right keep track of the number of zeros in the sliding window if you get to k zeros, move left pointer until you drop the leftmost zero Keep track of the max window length

636. Exclusive Time of Functions On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1. Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp. You are given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively

Solve with a stack keep track of last seen start time Whenever you see start Check stack, if populated add to top of stack function's running total (current timestamp - previous start time) add to stack, update previous start time Else saw an end add to running total (current timestamp - previous start + 1) pop from stack previous start time = end time + 1

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 time Set start and end to the first start and end of the list. Iterate through the sorted list. How do we detect an intersection? If the interval we're looking at is in the range of the current start and end. (curr start <= end and curr end >= start). Set the start to the min start and end to the max end. If you're not in an intersection, save the current start,end pair. Reset start and end to the current interval. Remember to append the last start,end pair when you exit the loop

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

Stack solution Start with current number as 0 and current operation as + As you see digits, create the current number When you see +/-, put the current number in the stack When you see * or /, do the operation between stack top and current number and put it in the stack update the current operation to what you are seeing now, and current number to zero Add everything in the stack together No stack solution keep result, current number, last number, and last sign (start with +) build current number when you see digits If last sign is + or -, add lastNumber to the operation, set lastNumber to +/- the currentNumber if * or /, do the operation between lastNumber and currentNumber Update the sign to what you are seeing now, and currentNumber to 0 Do this if you are at the the last index too Add last number to results return result

1216. Valid Palindrome III Given a string s and an integer k, return true if s is a k-palindrome. A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it.

This is a recursion and memoization problem. Your changing arguments are left, right, and k if (left, right, k) are memoized, return that if k < 0, return False if left >= right, return True if the char's match, recurse on left+1, right-1, same k. Memoize, return result if char do not match, recurse on [left+1, right, k-1] and [left, right-1, k-1]. Memoize result, return or of the two results

498. Diagonal Traverse Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.

This problem is much easier if we make a helper function. Think, how would you collect one diagonal? This helper should take a starter row and col and a flag indicating if we're in reverse or not. Remember the diagonal goes from right to left. Loop through grid, increasing row by 1 and decreasing col by 1 with each iteration, making sure you're still within bounds. flag tells you whether to append to start or end of list First, iterate through the first row, stopping at the last column. With each iteration, call helper func with current row and col, saving the list and flipping the reverse flag Then, go down the last column doing the same thing you did when going through the first row

317. Shortest Distance from All Buildings You are given an m x n grid grid of values 0, 1, or 2, where: each 0 marks an empty land that you can pass by freely, each 1 marks a building that you cannot pass through, and each 2 marks an obstacle that you cannot pass through. You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right. Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1. The total travel distance is the sum of the distances between the houses of the friends and the meeting point.

Trick is to run bfs on building nodes, keep track of a target empty land value, and maintain a separate grid that tracks total distance to all buildings Create a distance grid with the same dimensions as the input grid. Start with empty land value = 0. Every time you see a building (value = 1), run bfs Within BFS, you want to update each corresponding entry in the distance grid with the distance it took to get there from the building, decrement the value (so 0 -> -1), and update the minimum distance seen so far. Don't add building and obstacles to the queue. Return the minimum distance seen within each BFS iteration. After every BFS run, decrement your target empty land value so you only process areas that connect to other buildings. If your minimum distance is -infinity, you can't reach all buildings, return -1 otherwise return the distance

1868. Product of Two Run-Length Encoded Arrays Run-length encoding is a compression algorithm that allows for an integer array nums with many segments of consecutive repeated numbers to be represented by a (generally smaller) 2D array encoded. Each encoded[i] = [vali, freqi] describes the ith segment of repeated numbers in nums where vali is the value that is repeated freqi times. You are given two run-length encoded arrays encoded1 and encoded2 representing full arrays nums1 and nums2 respectively. Both nums1 and nums2 have the same length. Each encoded1[i] = [vali, freqi] describes the ith segment of nums1, and each encoded2[j] = [valj, freqj] describes the jth segment of nums2. Return the product of encoded1 and encoded2.

Two pointer approach with the ans list kinda being a stack One pointer for each encoded, start at beginning for each one If the frequencies are the same, multiply normally, check if the tops of ans has the same value. Adjust top of ans or append new pair. Move both pointers by one if the frequencies differ, multiply normally, set the frequency to be the min frequency, check top of ans if values match ,and move the pointer of the minimum frequency

986. Interval List Intersections You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists.

Two pointers, one for each list your start is the max of the two starts your end is the min of the two ends if start <= end, you have an intersection from start to end add to list If your end was from list1, move ptr1 up else move ptr2 up

Valid Word Abbreviation A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. The lengths should not have leading zeros. Given a string word and an abbreviation abbr, return whether the string matches the given abbreviation. A substring is a contiguous non-empty sequence of characters within a string.

Two pointers, word pointer and abbreviation pointer While the two pointers have the same characters, keep going If there is a discrepancy, make sure it's a digit and not a zero, else return False While you're seeing a digit, keep processing and creating a total number. Add that number to the word pointer. Make sure that both pointers reach the end of their strings

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

recursive function if you're at none, return 0 recurse on left recurse on right the diameter so far is the max of what you have now and left+right return the max of left or right plus one


Ensembles d'études connexes

2024 ATI Proctored Exam Practice

View Set

Introduction to Nuclear Medicine

View Set

Chapter 4 - Theoretical Foundation of Nursing Practice

View Set

Fundamentals pre-assessment quiz

View Set

Life Insurance Policy Provisions, Options and Riders

View Set

Med skills heart attack, stroke, seizures, fainting, diabetes

View Set