Midterm

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

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.

Use Cycle Sort. Iterate over the array. If the current value is not where it's supposed to be, swap it. Otherwise, move to the next number. Iterate over nums again and return the first number that is not where it needs to be. If we complete the loop and have not returned anything, return the the current index which should be the length (n) of the array. O(n) O(1)

Given the head of a singly linked list, return the middle node of the linked list.If there are two middle nodes, return the second middle node.

Use Fast and Slow pointers. Start at the head and move once for slow and twice for fast until the fast or fast.next is null. Then return the slow node. O(n) O(1)

You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.Once you reach a tree with fruit that cannot fit in your baskets, you must stop.Given the integer array fruits, return the maximum number of fruits you can pick.

Use sliding window. This is essentially find the longest continuous subarray length that has two distinct elements. Create a frequency map to hold fruit frequency. When expanding, update and add to the map. Contract when the length of the map is greater than 2. When contracting, update the freq map for the removed fruit. If the fruit count equals 0, remove the item from the map. Check the max against the length of the window. Return the max. O(n) O(1)

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

Use Cycle Sort. Create a results array for output. Iterate over the input array. If the current value is not where it's supposed to be, swap it. Otherwise, move to the next number. Iterate over nums again and push every number that is not where it needs to be. Return the results O(n) O(n) for the results array

Given the head of a singly linked list, reverse the list, and return the reversed list.

Use In place Reversal. 1) Create a prev and current node 2) Iterate the list and reverse the pointers 3) Return the prev pointer O(n) O(1)

Given an integer array nums, find the subarray which has the largest sum and return its sum.

Use Sliding Window. Expand and add to a current sum. Compare max to the current sum and set the new max. Contract when the sum is negative. Return the max O(n) O(1)

Given the head of a linked list, rotate the list to the right by k places.

1) Find the length of the list as well as the last node 2) Connect the last node with the head to make it a circular list 3) Modulo the number of rotations by the length of the list 4) Create a pointer to head for the last node of the rotated list and Iterate from 0 .. Length - rotations - 1, incrementing the pointer 5) Update the head to last nodes next 6) Update the last node's next to null; 7) Return the head O(n) O(1)

You are given two arrays of strings that represent two inclusive events that happened on the same day, event1 and event2, where: event1 = [startTime1, endTime1] and event2 = [startTime2, endTime2]. Event times are valid 24 hours format in the form of HH:MM. A conflict happens when two events have some non-empty intersection (i.e., some moment is common to both events). Return true if there is a conflict between two events. Otherwise, return false.

Return true if we find an overlap ( A overlaps B, B overlaps A) O(1) O(1)

Given a non-empty unsorted array taken from a range of 1 to n. Due to some data error, one of the numbers is duplicated, which results in another number missing. Create a function that returns the corrupt pair (missing, duplicated).

Use Cycle Sort. 1) Iterate over the input array. If the current value is not where it's supposed to beswap it. Otherwise, move to the next number. 2) Iterate over nums again and when a missing number is found, save the number index and value to a pair array and return the results O(n) O(1)

Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.Return the kth positive integer that is missing from this array.

Use Cycle Sort. 1) Iterate over the input array. If the current value is not where it's supposed to be and is less or equal to the input length, swap it. Otherwise, move to the next number. 2) Iterate over nums again and and for every number missing, check if a count is equal to k, also adding each found number to a map. 3) iterate again with the same index counter from 2), while count is less than k,increasing the missing count when a number is not found in the map. When the missing count is equal to k, return the index counter (plus 1). Or for a faster solution, we can use a binary search since the array is already sorted for us 1) Set left to 0 and right to the length - 1. Count the number of missing, which is the actual value and expected value at the last index. (arr[len -1]) - n 2) Iterate while the left is less or equal to the right - Calculate the mid = left + right / 2 - Compute the count missing again but between the actual value at (arr[mid, mid + 1) - Check if the missing count is greater or equal than k, if it is, then set the right to the mid - 1 Otherwise, set the left to mid + 1 (special case if right equals -1, return k) otherwise, return the value of arr[right] + k - the count missing (arr[right, right + 1) O(n) for Cycle Sort, O(logN) for Binary Search O(n) for the map in cycle sort or O(1) for the binary search

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.You must write an algorithm that runs in O(n) time and uses only constant extra space.

Use Cycle Sort. Create a results array for output. Iterate over the input array. If the current value is not where it's supposed to be, swap it. Otherwise, move to the next number. Iterate over the input array again and push every value that is not where it needs to be. Return the results. O(n) O(n) for the results array

Given an unsorted integer array nums, return the smallest missing positive integer.You must implement an algorithm that runs in O(n) time and uses constant extra space.

Use Cycle Sort. Iterate over the array. If the current number is positive and less than or equal to the length of nums and is not where it's supposed to be, swap it. Otherwise, move to the next number. Iterate over nums again and return the first number that is not where it needs to be. If we complete the loop and have not returned anything, return the length of the array plus one. O(n) O(1)

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.There is only one repeated number in nums, return this repeated number.You must solve the problem without modifying the array nums and uses only constant extra space.

Use Cycle Sort. Iterate over the array. If the current value is not where it's supposed to be, swap it. Otherwise, move to the next number. Iterate over nums again and return the first value that is not where it needs to be. O(n) O(1)

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

Use Fast and Slow pointers. 1) Find the middle of the list 2) Reverse from the middle to the end of the list 3) Iterate from the beginning of the start and middle of the list, checking if each pointer's value is the same. Return false if they differ 4) return true if we complete the last loop O(n) O(1)

Write an algorithm to determine if a number n is happy.A happy number is a number defined by the following process:Starting with any positive integer, replace the number by the sum of the squares of its digits.Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.Those numbers for which this process ends in 1 are happy.Return true if n is a happy number, and false if not.

Use Fast and Slow pointers. 1) Create two integers variables for fast and slow. 2) Write a routine to get the squared sum of a number. 3) Iterate until we find a happy number ( either fast or slow ends in 1). For every number, get the square sum once for slow and twice for fast. Ff they are both equal to each other, we've detected a cycle, so return false. Return true if the loop completes O(logN) O(1)

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.

Use Fast and Slow pointers. Iterate over the list and move fast two steps while slow moves one step. If fast and slow meet, then there is a cycle. O(n) O(1)

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.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 (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list.

Use Fast and Slow pointers. Iterate over the list and move fast two steps while slow moves one step. If fast and slow meet, then there is a cycle. Then set a pointer to the beginning of the list and move that pointer and the slow pointer one at a time until they equal each other. The current node will be where the cycle begins. O(n) O(1)

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.

Use Fast and Slow pointers. This can be solved in three steps. 1) Find the middle of the list 2) Save the middle's next and set the middle's next to null(new end of the list), then reverse the list from the middle's next to the end 3) Set a pointer to the beginning of the original list and Iterate starting from the head the reversed list. While the current node of the reversed list is not null, reorder the pointers making use of temporary variables. O(n) O(1)

You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:If nums[i] is positive, move nums[i] steps forward, andIf nums[i] is negative, move nums[i] steps backward.Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.A cycle in the array consists of a sequence of indices seq of length k where:Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...Every nums[seq[j]] is either all positive or all negative.k > 1Return true if there is a cycle in nums, or false otherwise.

Use Fast and Slow pointers. We can start from each index of the array to find the cycle. If a number does not have a cycle we will move forward to the next element. There are a couple of additional things we need to take care of: As mentioned in the problem, the cycle should have more than one element. This means that when we move a pointer forward, if the pointer points to the same element after the move, we have a one-element cycle. Therefore, we can finish our cycle search for the current element. The other requirement mentioned in the problem is that the cycle should not contain both forward and backward movements. We will handle this by remembering the direction of each element while searching for the cycle. If the number is positive, the direction will be forward and if the number is negative, the direction will be backward. So whenever we move a pointer forward, if there is a change in the direction, we will finish our cycle search right there for the current element. When calculating the next index when wrapping, we can use the array length and modulus to help wrap around the array. If the index is negative, we can add the array length to it. O(n^2), but we can optionally cache duplicate cycle calls and reduce to O(n). O(1)

You are given the head of a linked list.The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words,The 1st node is assigned to the first group.The 2nd and the 3rd nodes are assigned to the second group.The 4th, 5th, and 6th nodes are assigned to the third group, and so on.Note that the length of the last group may be less than or equal to 1 + the length of the second to last group.Reverse the nodes in each group with an even length, and return the head of the modified linked list.

Use In Place Reversal. This is asking to reverse nodes between a range for every even group 1) Iterate over the list and count the number of nodes. 2) Create a previous a next pointer as well as a total count, count inside group, and current group size. 3) Iterate the list and keep the counts updated. 4) Calculate the remaining elements left in the list. If the group size is greater than the remaining, check if the remaing amount is even and needs to be reversed. If it's not, then check if the group size is even in order to reverse. 5) When we reach an even group size, reverse the sublist from that point ending when we reversed group size times. To reverse the list, create two pointers to connect the ends of the sublist back to the list. One for the last node of the first part set to the previous node and one for the last node of the sublist set to the current node. Reverse the sublist, incrementing counts as needed. Connect the reversed sublist to the list (previous part next to the previous node and the last node of the sublist next to the current node.) Set the previous to the last node of the sublist 6) If we are not reversing the sublist, then we can iterate up to the group size incrementing the previous and next pointers as well as the group count and total count. 7) Reset the group count to 1 and increment the group size 8) Return the head O(n) O(1)

You are given the head of a linked list, and an integer k.Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

Use In place Reversal. 1) Create a new head pointer with it's next set to head. Also, create two previous pointers. 2) Iterate to K with the first previous pointer. 3) Create a current node at the previous pointer's next and iterate to the end of the list while incrementing the second previous pointer, moving from the start of the list to kth node. The previous nodes are now in the correct position 4) Create a current node for the first previous node and another for the second previous node at their next positions. 5) if both current nodes are equal, then we can return the new head, since there is nothing to swap 6) Swap the nodes using the previous and current pointers and a tmp pointer 7) Return the new head O(n) O(1)

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Use In place Reversal. 1) Create a new head pointing to the current head 2) Create prev and current pointers 3) Iterate indefinitely. 4) Create pointers to connect the ends of the reversed nodes. 5) Iterate from 0 .. 2 (number of nodes to swap) and reverse the nodes 6) Connect the ends to the previous and current nodes 7) Check if we're at the end of the list and break out of the main loop if the current pointer is null 8) Update the previous pointer to the last node of the sublist 9) Return the new head O(n) O(1) *This also has a faster recursive solution

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

Use In place Reversal. 1) Create a new head pointing to the current head 2) Create prev and current pointers 3) Iterate up to the left position 4) Create pointers to connect the ends of the reversed nodes. 5) Iterate from 0 .. to the number of Nodes to swap (from left to right) and reverse sublist 6) Connect the ends to the previous and current nodes 7) Return the new head O(n) O(1)

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. A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].

Use Merge Intervals. Iterate through both the lists together to see if any two intervals overlap. To see if they overlap, we can check if one of the intervals start time lies within the other inteerval. If two intervals overlap, we will insert the overlapped part into a result list and move on to the next interval which is finishing early. (we increment the pointer of the list with the smallest end time). Return the results. O(n) O(n) for the results array

We are given a list schedule of employees, which represents the working time for each employee.Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.(Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.

Use Merge Intervals A) One way to do it is to use Merge Intervals 1) Flatten then Sort the intervals 2) Create a last end pointer to the first interval's end 3) Iterate over schedules from 1.. N Check if the current interval start does not overlap with the previous and if so, add the free interval to the results. 4) Update the lastEnd to the max of the previous and current ends. 5) Return the results B) Another way to do it is to use a heap to take advantage of the fact that the intervals are already sorted for each employee 1) Create a minheap and add all the first intervals for each employee to the heap, along with their employee index, and a starting interval index of zero 2) Create a previous end pointer to the first element end 3) Iterate while the heap is not empty. Remove the next element from the queue and check for a free interval between it and the previous. Push it to the results of there is one. If we find an overlap, update the previous end to the current end Get the current employee and check if there are more intervals for the employee. If there are, add the next one to the queue with the same employee index and incremented interval index 4) Return the results A - O(nlogn) : B - O(nlogk) A - O(n + k) : B - O(k)

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.

Use Merge Intervals. 1) Create a results output array and counter. 2) Iterate over intervals array and add any interval that does not overlap with the new interval( ends before the new interval) 3) Continue iterating (same counter) and merge the intervals that overlap with the new interval. at the end of this loop, push the new merged interval to the results. 4) Continue iterating and add the remaining intervals to the results. 5) Return the results. O(n) O(n)

Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.

Use Merge Intervals. 1) Sort the array and create a prev pointer to the first interval 2) Iterate from 1..N and for each interval, if the current interval overlaps with the previous (It's start is less or equal to previous end), return false. 3) For every iteration, set previous to current. 4) Return true O(nlogn) O(1)

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.

Use Merge Intervals. 1) Sort the array and create a results output array and previous pointer to the first interval in the array. 2) Iterate over the intervals from 1..N and if the current intervals overlaps with the previous( it's start is less or equal to previous end), we can merge the intervals. If they don't overlap, we can add them to the result array of non overlapping intervals and set the current interval to be the new previous. 3) Return the results. O(nlogn) O(n)

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Use Merge Intervals. 1) Sort the intervals 2) Set a previous end pointer to the end time for the first interval and create a counter for removed intervals. 3) Iterate from 1.. N, if we find an overlap, then we "remove" the one that ends last and take the one that ends first (set the previous end to the min of itself and the current end) . Then increment the removed intervals counter. If there is no overlap, we update the previous end to the current end. 4) Return the counter of removed intervals O(nlogn) O(1)

Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.

Use Merge Intervals. 1) Sort the meetings array by the start time 2) Create a min heap to store the active meetings with priority to the smallest end time. Create a max variable that represents the max size of the heap which is the minimum number of rooms 3) Iterate on the intervals, for each iteration, remove all the meetings on the heap that have ended. (their end time is less than the current intervals start time). Push the current interval to the heap. Check if the size of the heap is greater than the current max 4) Return the max (min rooms). O(nlogn) O(n)

You are given an integer n. There are n rooms numbered from 0 to n - 1.You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.Meetings are allocated to rooms in the following manner:Each meeting will take place in the unused room with the lowest number.If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting.When a room becomes unused, meetings that have an earlier original start time should be given the room.Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.A half-closed interval [a, b) is the interval between a and b including a and not including b.

Use Merge Intervals. 1) Sort the meetings by start time 2) Create a minheap for busy rooms sorted by endTime, room number 3) Create a minheap for available rooms sorted by room number 4) Populate the heap/queue of available rooms with an element for every index, empty endTime (0) 5) Create an array to hold the count of meetings that have occurred in each room 6) For every meeting, remove all the meetings from the busy queue that have ended and push them to the available queue. If the available queue is empty, take a room from the busy queue and extend the end time for the delay of the current meetings length. If the available queue is not empty, take a room from the available queue and set the end time to the current meeting's end time. Add the taken room to the busy queue and increment the number of meetings for that room. 7) Iterate over the array of rooms to find the busiest room based on the highest count. Return the busiest room. O(nlogn + m) O(m)

Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm.

Use Reverse Linked Lists In-Place. 1) Create a new head node that points to the current head and sets a previous pointer to this newHead and current pointer to head. 2) Iterate indefinitely and create pointer to link the list around the ends of the reverse group. One pointer for the last node of the previous section pointing to previous and one.pointer for the last node of the group section pointing to the current node. 3) iterate up to K, reversing nodes. 4) Iterate again up to K, but this time, just move prev and current to their next nodes. 5) Connect the sublist to the list. 5) If we reach the end of the list (curr == null), break from the main loop 6) Return the new head. O(n) O(1)

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.You may not alter the values in the list's nodes, only nodes themselves may be changed.

Use Reverse Linked Lists In-Place. 1) Create a new head node that points to the current head and sets a previous pointer to this newHead. 2) Iterate over the list to count the length 3) Create a global counter set to 1. 4) Iterate indefinitely and use the current count to check if we have no more groups to reverse (len - globalcounter < k). If it's less than k, stop processing. 5) Create pointer to link the list around the ends of the reverse group. One pointer for the last node of the previous section pointing to previous and one pointer for the last node of the group section pointing to the current node. 6) start a counter for the group and iterate from 0 to k, reversing the nodes in the list as well as incrementing the count and global counter. 7) Link the group by connecting the ends, making the next pointer for the last node of the previous section to the previous pointer and making the next pointer for the last node of the group section to the current pointer. 8) Break out of the main loop if the current node is now null. 9) Set the previous to the last node of the group section. 10) Return the new head's next O(n) O(1)

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may 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.

Use Sliding Window. 1) Keep track of the list of results, frequency map, and a remaining count set to the length of p. 2) Populate the frequency map for p. 3) When expanding, decrease the remaining count to be found if we've found a character in the map. Contract when the window is greater or equal to the length of p. 4) When contracting, if all characters are found, add the current start index to the results. If we contract past a character in the frequency map, update and increment the remaining count. Ignore negative frequencies and zero when contracting. Ignore negatives only when expanding. Space / Time Complexity O(n + m) O(m + (n for results))

You are given a string s and an array of strings words. All the strings of words are of the same length.A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated.For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", and "efcdab" are all concatenated strings. "acdbef" is not a concatenated substring because it is not the concatenation of any permutation of words.Return the starting indices of all the concatenated substrings in s. You can return the answer in any order.

Use Sliding Window. 1) Create a frequency map for the list of words and populate it from the arr. 2) Iterate over every character in s and create a map to hold the words from starting from the current character. 3) Iterate over the words array and take the substring from the current character to length of a word. If the word is found, update the found map, else break and stop searching the words list. Also stop looking if we found more of the word than needed in the freq map. If we reach the end of the word list, add the index to the results. 4) Return the results O(N∗M∗Len) O(N + M) for results and two word list hashmaps

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.

Use Sliding Window. A slow solution is to keep finding the max of the window while the window is contracting. A faster solution is to use a Deque. When looking at the current number, we remove from the tail of the Deque any value that is less than the current. When expanding, we push the current num to the deque. We contract when the window is greater than k. When the window is contracting, we push the first (head) from the deque to the results and if the left of the window is the same as the head of the deque, we pop the head of the deque. Return the results. Time O(n) using a Deque, O(n*k) when calculating max ourselves Space O(n+k) using a deque. O(n) not using a Deque

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.

Use Sliding Window. Create a frequency map to hold charact frequencies. Keep track of the longest substring length as well as the most frequent max. When expanding, set the mostFrequent to the max of mostFrequent and the current character frequency. Contract the window when the difference between the range and most frequent max is greater than k. Update the frequency map while contracting. Check the max against the current window length. Return the max Space / Time complexity O(n) O(L) for letters in the alphabet, which is O(1)

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

Use Sliding Window. Create a frequency map to hold the character frequencies of t. Keep count of characters remaining. Once all characters are found, check if the length of the window is smaller than the current window length and if it is, save the range (left and right). Return the substring for the left and right indices that were saved for the smallest window found. If not found, the range should have no indices O(n) O(m) where m is the length of t

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.

Use Sliding Window. Iterate over the prices, checking if the difference between the right price and left price. If the difference is negative, move the left to the right index.If it's positive, set a new max if the diff is greater than the max. return the max Space / Time complexity O(n) O(1)

The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.For example, "ACGAATTCCG" is a DNA sequence.When studying DNA, it is useful to identify repeated sequences within the DNA.Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.

Use Sliding Window. Iterate over the sequence pushing character to the window. When we reach the minimum window length, keep adding one and removing a character from the window. Use a set to check for duplicates. When a duplicate is found, add it to the results. Return an array from the results. Space / Time complexity O(n * m) where m is the length of the window O(n)

Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.A subarray is a contiguous subsequence of the array.

Use Sliding Window. Keep track of a total. Iterate over the length of the array. when the current index is odd, use Sliding Window on the whole array and when contracting, add the current sum to the total. If the length of the array is odd, add 1..n to the total. Return the total Space / Time complexity O(n) O(1)

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Use Sliding Window. Set a min value to pos infinity. Keep track of the current sub array length and set to 1. When the currentSum >= target, Keep removing from the start of the window and check if the subarray length is smaller than the min. Also, reduce the subarray length while contracting the window. Return the smallest if not infinity. Space / Time complexity O(n) O(1)

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.

Use Sliding Window. When expanding, increase the one count for ones found. Set the max to the max of current max and the one count plus k. Contract when the number of zeros is greater than k. Decrement the one count if we are removing a one. Return the max if it's less than the length of the array, otherwise return the length of the array. O(n) O(1)

Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.

Use Sliding window. Set current product to 1. When expending, keep multiplying current product and the current. Contract when the product is greater than k and stop when left is at the end of the list. When contracting, dividing the current product by the start index and increment the start. Add the length of the window to the result after contracting. Return the result. O(N) O(1)

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.

Use Tree BFS or DFS For BFS, 1) Create a results array and a deque. 2) Push the root of the tree to the queue and create depth counter 3) Iterate while the queue is not empty. Get the current level size which is the length of queue. Iterate from 0 .. levelSize For every element, dequeue an element .Push the children that are not null to the queue. Increment the depth counter 4) Return the depth O(n) O(n)

Given the root of a complete binary tree, return the number of the nodes in the tree.According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.Design an algorithm that runs in less than O(n) time complexity.

Use Tree BFS or DFS for O(n) DFS: 1) We first process and return the root 2) Base case: node is null, return 0 3) return 1 + node.left + node.right BFS: 1) Create a queue and a node counter 2) Push the root to the queue 3) Iterate while the queue is not empty 4) Iterate from 0 .. level size Pop a node from the queue increase the count Add the left node and right node to the queue if they are not null 5) return the count DFS: O(n) - BFS:O(n) BFS:O(n) - DFS:O(n)

Given a binary treestruct Node {int val;Node *left;Node *right;Node *next;}Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.Initially, all next pointers are set to NULL.

Use Tree BFS. 1) Create a queue. 2) Push the root of the tree to the queue 3) Iterate while the queue is not empty. Get the current level size which is the length of queue. Iterate from 0 .. levelSize For every element, dequeue an element. if it's the last node in the level, point the next to null. If it's not the last, point the next to the next node in the queue. Push the children that are not null to the queue. 4) Return the root O(n) O(n)

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:struct Node {int val;Node *left;Node *right;Node *next;}Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.Initially, all next pointers are set to NULL

Use Tree BFS. 1) Create a queue. 2) Push the root of the tree to the queue 3) Iterate while the queue is not empty. Get the current level size which is the length of queue. Iterate from 0 .. levelSize For every element, dequeue an element. if it's the last node in the level, point the next to null. If it's not the last, point the next to the next node in the queue. Push the children that are not null to the queue. 4) Return the root O(n) O(n)

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.Note: A leaf is a node with no children.

Use Tree BFS. 1) Create a queue. 2) Push the root of the tree to the queue and create min depth counter 3) Iterate while the queue is not empty. Get the current level size which is the length of queue. Iterate from 0 .. levelSize For every element, dequeue an element. If the node is a leaf, return the min depth. Push the children that are not null to the queue. O(n) O(n)

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root)

Use Tree BFS. 1) Create a results array and a deque. 2) Push the root of the tree to the queue 3) Iterate while the deque is not empty. Get the current level size which is the length of deque. Create a level array Iterate from 0 .. levelSize For every element, dequeue an element .Add the value to the level array. Push the children that are not null to the queue. Add the level to the beginning of the results. 4) Return the results O(n) O(n)

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

Use Tree BFS. 1) Create a results array and a deque. 2) Push the root of the tree to the queue and create a flag to know if we are moving left to right. 3) Iterate while the queue is not empty. Get the current level size which is the length of queue. Create an array to hold the values for the level Iterate from 0 .. levelSize For every element, dequeue an element . If we are going left to right, then add the value to the end of the level array. If we are going right to left, then add the value to the start of the level array. Push the children that are not null to the queue. Flip the left to right flag Push the level to the results. 4) Return the results O(n) O(n)

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

Use Tree BFS. 1) Create a results array and a queue. 2) Push the root of the tree to the queue 3) Iterate while the queue is not empty. Get the current level size which is the length of queue. Iterate from 0 .. levelSize For every element, dequeue an element. if it's the last node in the level, add it to the results. Push the children that are not null to the queue. 4) Return the results O(n) O(n)

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted

Use Tree BFS. 1) Create a results array and a queue. 2) Push the root of the tree to the queue 3) Iterate while the queue is not empty. Get the current level size which is the length of queue. Create a sum for the level set to 0 Iterate from 0 .. levelSize For every element, dequeue an element and add the value to the sum. Push the children that are not null to the queue. Calculate the average for the level and push it to the results 4) Return the results O(n) O(n)

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

Use Tree BFS. 1) Create a results array and a queue. 2) Push the root of the tree to the queue. 3) Iterate while the queue is not empty. Get the current level size which is the length of queue. Create an array to hold the values for the level Iterate from 0 .. levelSize For every element, dequeue an element push the value to the level array. Push the children to queue if they are not null Add the level array to the results. 4) Return the results. O(n) O(n)

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

Use Tree DFS 1) We first process the root, target sum, and an empty array that holds the current path. 2) Base case: when the node is null, return 0 3) Add the current node value to the array 4) Create a sum and path counter. Iterate starting from the end of the array, adding each value to a sum, checking each time, if the current sum is equal to the target sum. If it is, increase the path count. 5) Increment the path count by recursing on the left node and then on the right node. 6) Backtrack and pop the last node from the path. 7) Return the path count. O(n^2) if tree is not balanced, O(nlogn) is tree is balanced O(n)

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.

Use Tree DFS A) One way to do it is to use an array to keep track of the paths. 1) Create a total sum set to 0. 2) Recurse starting at root with an empty array to capture the path 3) Base case: when node is null, return 0 4) Add the current value to the path array. 5) if we are at a leaf node, convert the path to a string, then to a number and add that to the total sum, else recurse on the child nodes 6) pop from the path array 7) Return the total sum B) Another way to do it is to calculate the running sum by add the current value to the current sum * 10 1) Recurse starting at root with an initial sum of 0 2) Base case: if the current node is null, return 0 3) Calculate the number for the current node (10 * sum + the value of the node) 4) If we reach a leaf node, return the sum 4) return the result of recursing and adding the child nodes A: O(nlogn) - B: O(n) A: O(nlogn) - B: O(n)

Given the root of a binary tree, return all root-to-leaf paths in any order.A leaf is a node with no children.

Use Tree DFS. 1) Create arrays for the current path and a results output array. 2) We first process the root and an empty array. 3) The base case will be if the root is null, we stop. 4) For every node, we add the node to the current path and check if we reach a leaf node, and if so, add the converted array to string path to the results, otherwise we recurse the child nodes, 5) Pop the last node. 6) Return the results O(nlogn) O(nlogn)

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

Use Tree DFS. 1) Create arrays for the current path and a results output array. 2) We first process the root, target sum and an empty array. 3) The base case will be if the root is null, we stop. 4) For every node, we add the node to the current path and check if we reach a leaf node, and if so, add the path to the results, otherwise we recurse the child nodes, subtracting current value from the target sum. 5) Pop the last node. 6) Return the results O(nlogn) O(nlogn)

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.

Use Tree DFS. 1) Recurse starting on the root. 2) Base case: if root is null, return 0 3) Calculate the left and right heights 4) Calculate the current diameter (left + right diameters) and compare to existing max Update max if the current diameter is greater than the max 5) Return the bigger diameter from left and right and + 1 for the current node 6) Return the max O(n) O(n)

Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.

Use Tree DFS. A) One way to do it is to check every path for a match 1) Recurse starting on the root and an empty path array 2) Base case: if root is null, return false 3) Add the current value to the array 4) Check if we are at a leaf node, if so, check if the sequence is equal to the path. If it is, we can return true, other wise, return false. 5) If we are not at a leaf node, then return and recuse on the child nodes 6) Pop the last element from the array 7) Return found B). Another way to do it is to check along the path. 1) Recurse starting at root, given sequence, index 0. At each level, check if the node is equal to the character at that index. 2) Base case: return false if node is null 3) If we reach an index that goes past the length of the sequence or the value of the node doesnt match the sequence at the index position, return false 4) Return and recurse on the child nodes with an incremented index A: O(nlogn) - B: O(n) A:O(nlogn) - B:O(n)

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.A leaf is a node with no children

Use Tree DFS. Start DFS with the root of the tree. If the current node is not a leaf node, do two things: Subtract the value of the current node from the given number to get a new sum => S = S - node.value Make two recursive calls for both the children of the current node with the new number calculated in the previous step. At every step, see if the current node being visited is a leaf node and if its value is equal to the given number 'S'. If both these conditions are true, we have found the required root-to-leaf path, therefore return true. If the current node is a leaf but its value is not equal to the given number 'S', return false. The other way to do is to use DFS, but start at a 0 sum. Then each search, we check if the current node value + current sum is equal to the target sum. Also, instead of subtracting the root value from the sum, we add it. O(n) O(n)

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.

Use Tree DFS. Since we need to find the overall maximum sum, we should ignore any path which has an overall negative sum. 1) We create a max value at the root.val and first process the root 2) Base case: if node is null, return 0 3) get the max of the left pathsum and 0 4) get the max of the right pathsum and 0 5) Compare the sum of the left, right and current node value to the max. Update the max if needed. 6) Return the max of the left and right with the addition of the current node value (selecting the greater subtree) O(n) O(n)

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.You must solve this problem without using the library's sort function.

Use Two pointer. Really, we're using three pointers here. We set two pointers at the left and right of the list. Our third pointer is at the start. We use the third pointer's value to check whether we need to swap any values. If the third pointer is 0, we swap it to the left and move it's pointer and the left pointer to the right. If it's 2, we swap it to the right and move the right pointer left. If it's 1, then we just move to the third pointer to the right. O(n) O(1)

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Use Two pointers. Create a new "head" pointer that points to the head. Keep track of the previous and current nodes while iterating the list. If we find a duplicate, move current until no duplicate is found. If we don't find a duplicate, then just update previous and current to the next pointers. Return the newHeads next which is now the head of the list. O(n) O(1)

Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.

Use Two pointers. Easiest way is to iterate and create a copy, adding an extra zero for every zero encountered. Then iterate over the original array copying each item from the copy. Another way to do it with O(1) space is to use Two pointers. We do one pass to count the number of zeros. Then we create one pointer starting at the end of the original array and we create another pointer starting at the length of the original array plus the number of zeros. We do a second pass from the back, decrementing the pointers each iteration. If we encounter a zero for the first pointer, we replace the value of the second pointer with the value of the first if the second pointer is within the original array (less than the length). We then decrement the second pointer and replace again. If we don't encounter a zero, we just do a single swap. we continue to the start of the list or until the first pointer is equal to the second pointer (we ran out of zeros). O(n) O(n) for the easy solution or O(1) for the two pointer solution

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.Return k after placing the final result in the first k slots of nums.Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Use Two pointers. It's similar to a fast and slow problem where one pointer moves at a different pace than the other. Iterate over the list and when i and j numbers don't match, do a swap and increment j. They can all start at a repeat length k, which then j-k would be used to compare and we swap before incrementing j. K here would be equal to 2 for the number of repeats allowed. O(n) O(1)

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.Return the shortest such subarray and output its length.

Use Two pointers. Iterate on the list from left and right and move left and right to the edge of the subarray while the list is still in order. Stop if we encounter where both left and right are out of order with the index to the inside. Iterate over this range and store both the min and max of the range. Loop and extend the left pointer back left to include any number bigger then minimum. Loop and extend the right pointer back right to include any number smaller then maximum. Return the range length. O(N) O(1)

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Use Two pointers. One way is to keep three pointers and solve it like an array, cutting off the distinct list by setting the back node's next to null after the swaps are done. An easier way is to iterate over the list and if we find a duplicate with current and next, we replace change the currents next pointer to it's next, next pointer. O(n) O(1)

Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.Return the sum of the three integers.You may assume that each input would have exactly one solution.

Use Two pointers. Similiar to 3sum except we keep track of the closest sum using difference as a min. If we find a match we return that, otherwise we keep looking for the lowest difference O(N∗logN+N^2), which is asymptotically equivalent to O(N^2) O(N) for sorting. Ignoring space for output array

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:0 <= a, b, c, d < na, b, c, and d are distinct.nums[a] + nums[b] + nums[c] + nums[d] == targetYou may return the answer in any order.

Use Two pointers. Similiar to 3sum, but with an extra pointer. Sort the list. Set a start pointer at the start, the second pointer will be at the first pointer plus 1. The third next to the second and the last at the end. O(N∗logN+N^3), which is asymptotically equivalent to O(N^3) O(N) for sorting. Ignoring space for output array

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.

Use Two pointers. Sort the list. Have one pointer at the start and iterate until length - 2; Then use two pointers to solve 2sum. To remove duplicates, after finding a match, loop and check for any matches with the next value for left and right, skipping any that are duplicates. Do the same type of loop outside the two sum block for the start pointer. O(N∗logN+N^2), which is asymptotically equivalent to O(N^2) O(N) for sorting. Ignoring space for output array

Given an array of n integers nums and an integer target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

Use Two pointers. Sort the list. Similar to 3sum, but we can also solve it more efficiently by using the difference between the third and second pointer and add that to the results when we find a sum smaller than the target. Otherwise, we would need to loop from second and third pointers adding each individually. This is because since the left and right pointers lead to a sum smaller than the target, anything between the second on third would also be smaller O(N∗logN+N^2), which is asymptotically equivalent to O(N^2) O(N) for sorting. Ignoring space for output array

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.

Use Two pointers. Sort the list. set a left pointer to beginning of the list and a right pointer at the end of the list. Iterate while left is less than the right. Add the values of the pointers and if it's less than the target, increment the left pointer. If it's greater than the target, decrement the right pointer. If we find a match, find the matching indices in the unsorted array and return that result array. We can also use Binary search to solve it. Sort the list. For every element, calculate it's complement to equal the target and search for that complement. If we find a valid index, then find the original indices and return the result. We can also use a hashmap to solve it by iterating and adding each element as a key to the map and its index as a value. For each iteration, we look for the complement in the map and if found, return the resulting indices. O(nlogn) O(1)

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Use Two pointers. The easy solution is to loop and square each number and then sort. For a faster solution, we can use two pointers. We create a new array the length of the list since modifying the original array would result in miscalculations. We create a left and right pointer. We also create a high index pointer starting at the end of the list so we are moving in non decreasing order. For each iteration, we square left and right values and we set the array at the high index to the square that is greatest. if the right is greatest, we decrement right pointer and if the left is greatest, we increment the left pointer. Then we decrement the high index pointer to move down to the next index. After the end of the loop, we return the result array. O(n) O(n) for the result array

Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.Note that after backspacing an empty text, the text will continue empty.

Use Two pointers. We can solve this easily by using stacks to remove the backspaces from the strings and then compare the strings. We can solve it faster using Two pointers. We start from the back of the strings and iterate while the index1 and index2 indices are greater or equal to 0. For each iteration, we need to calculate the current index of both indices and assign them to temporary indices s1 and s2. To get the index, we iterate while index is greater and equal to zero. We keep track of the backspace skips and increment the skips if we encounter a backspace and then move the index left if it is. If we don't encounter a backspace, but we have some skips we need to make (> 0), we reduce the skip number and move the index left. If neither is true (no skips and no backspace character), then we stop and return the current index. Using those indices for s1 and s2, if they are both negative (empty string), we return true since they are both empty.If only one of them is empty and negative, then return false, since they are not equivalent. If the characters at those indices don't match, return false, since they are not equivalent.decrement index1 and index2 by s1 - 1 and s2 - 1.Return true if we complete the loop O(N) O(1)

Given a string s, find the length of the longest substring without repeating characters.

Use sliding window. Create a freq map. Update the frequency when expanding. Contract when the current map value is greater than 1. When contracting, decrement the starting character frequency and delete it if it reaches zero and increment the start. Check the max against the current map length. Return the max. O(n) O(L) for letters in the alphabet, which is O(1)

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.In other words, return true if one of s1's permutations is the substring of s2.

Use sliding window. create a dictionary to hold the frequency for s1 and populate the map for s1. When expanding the window, if the left letter exists in the frequency map, decrement it by one. if the new value in the map is > 0, decrement total characters remaining. When contracting the window, increment the total count if the character being removed is part of the frequency map and the freq is non negative. Check if there are any character remaining after contracting and return true if total is 0. Return false if the loop ends O(n + m) O(m)


Ensembles d'études connexes

Insurance Pre-licensing : Chapter 1 quiz

View Set

Test 1: Sissejuhatus anatoomiasse ja füsioloogiasse

View Set

Week 3 Quiz "Electricity" Units 26 & 28

View Set