Leetcode

Ace your homework & exams now with Quizwiz!

Consecutive Numbers in an array

1. Convert the array to a set 2. iterate over each and if it's the first in a consecutive streak, keep adding until not consecutive 3. repeat until done iterating.

Letter Combinations of a Phone number Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

1. Create a dictionary of digit to possible letters. 2. Create a list of lists containing all possible chars for each digit in input. 3. Call dfs on the first list of lists with parameters starting list and temp word being '' 4. if the len of word is len of digits add to ans and return 5. if not, run a for loop on all the next possible list to add to. 6. call dfs(start +1(next array), word + letter from this current array

Pairs of Songs with Total Durations Divisible by 60 Given a list of times, find the number of pairs that is divisible by 60. (time[i]+time[j]) % 60 == 0

1. Initialize a dictionary 2. Initialize ans to 0 3. Parse through each time and store the remainder of time divided by 60 with accumulating count. 4. Whenever you find it add to answer. This prevents repetition. Time: O(N) Space: O(N)

Product of Array Except Self Give an array find the product of each value multiplied by every value in the array except itself

Accumulate multiply from the left starting on the second index left to right. Accumulate multiply from right starting second to last right to left. Multiply at the same index left[i] * right[i] should be the answer for each index.

Contains Duplicate Give an array of integers, find if the array contains any duplicates.

Check if the set contains a different number of values than the original. Also use hashmap to keep count of each value

Rank of an element in a stream Imagine you are reading in a stream of integers. You wish to look up the rank of a number x. Implement the method track(int x) which is called whenever a number of values less than or equal to x(not including x itself) 1. Create add() and getRank() 2. whats the tradeoff between add() and getRank() 3. How can we make the time complexity of getRank() to become O(1)

Initialize a graph where we keep track of data, smaller data to our left, bigger to our right. Each node will have a value leftSize that contains how many are in the left. 2 Inserting a new node, if data<= root.data: root.left = insert(root.left, data) root.leftSize +=1 Else, root.right = insert(root.right, data) 3. getRank(root, x): if root.data == x: return root.leftSize, if x < root.data, getRank(root.left, x) else if it's bigger call getRank(root.right, x) until it returns the leftSize. To make getRank() become O(1) , we need add() to calculate the rank on each insertion so that we can just grab it off of a dictionary value {value: count}

insertion sort

Inserts elements from an unsorted array into a sorted subsection of the array, one item at a time. O(n^2) average and worst O(n) best O(1) space

quicksort

Recursively divide the input into two smaller arrays around pivot. One half has smaller than pivot other has larger than pivot. Do it over each element. O(n log n) average and best O(n^2) worst O(logn) space

Selection Sort

Select the next smallest element and move it to front. O(N^2) average, worst, best no space

Concatenated Words Given an array of strings words(without duplicates), return all the concatenated words in the given list of words.

for each word run a dfs for each word break it up into two subtexts, prefix and suffix if both are in list, return True if prefix is in list but not suffix run dfs on suffix else run dfs on prefix for every word that's true, add to list. Can also use a Trie and run DFS thru DP method: 1. initialize original list into a set of valid words with len > 0 2. for each word if word_break is true, add to ans 3. word break loops takes word, list(words), start(int), and dp{} 4. if start is in dp return true 5. if start != 0 and word[start:] in words: return true 6. loop through word with a pointer to determine start of suffix and break up into prefix if prefix is in words and suffix is in words return ture

Heap sort

similar to selection sort, choose the largest and move it to end of array O(n log n) average and worst O(n) best O(1) space

Critical Connections in a Network Given servers numbered 0 to n-1 connected by undirected server to server connections, find the connection that if removed will make some server unable to reach some other server.

1. A critical connection is a connection that is not in a cycle. 2. Search for servers in a cycle and remove them 3. Define rank of a node, it will be the depth of the node during a DFS. Starting node is rank 0 4. Increment rank by 1 until an anomaly occurs which would mean you've come across a cycle. 5. DFS would go through every node and return the minimal rank. 6. If dfs(v) returns something smaller than or equal to rank(u) then u knows its neighbor v helped it to find a cycle back to u. So u knows it should discard the edge (u,v) which is in a cycle. 7. Remaining edges are critical connections. 8. Create a map of lists containing direct connections per node 9. Go through each connection node and update its rank. 10. If a rank anomaly comes up remove the node and its neighbor. 11. return the remaining connections. dfs function: if rank has been assigned, return it. assign rank[node] = depth initialize min_back_depth = number of nodes for each node connection, check if it has been assigned rank, if it has, remove the tuple(connection) from connections. Do this for all nodes and return connections.

Search in rotated sorted array given an array that is sorted in ascending order but also rotated, find the target value and return its index if it exists, else return -1. [4,5,6,7,0,1,2] target = 0 => 4

1. Any search is usually binary search. 2. Set left to 0 and right to last index. 3. while left is less than or equal to right, keep doing binary search. 4. middle is left + right-left//2 5. if nums[middle] is the target, return middle index. 6. if nums[middle] >= nums[left], check if target >= nums[left] and target < nums[middle] then right should become middle and recalc middle. 7. else, left becomes middle and middle is recalculated. 8. if nums[middle] is less than nums[left] check if target is greater than middle and less than right, then left should become middle, else right becomes middle. 9. Basically keep cutting what to search in half until you find it.

Closes K points to origin faster without using built in sort

1. Create a list of distance per points 2. Create a sorting function that will pick a random point and partition to sort from a pivot where smaller goes to left and bigger goes to right. 3. Create a partition function that will switch points from the pivot until left pointer and right pointer are equal or left pointer greater than right pointer. 4. return that right pointer to use as the right pointer for another sort(sort of recursively sorting/reusing) 5. return the first K values in list

Partition Labels Given a string, find a way to partition the strings into as many parts as possible so that a letter can only occur in one partition.

1. Create a map of character to index 2. Create 2 pointers, one fast one slow. 3. Set fast pointer to always be the max index of a character. 4. So when i == j, it means that we should not see this char ever again so we can append the len of the word with confidence we'll never see it again. 5. set anchor to be i+1 6. return ans after iterating through

Number Of Islands: matrix of 1s and 0s find number of islands

1. DFS solution 2. When you find a 1, change the value to 0. 3. For each neighbor that is part of the island, change it to 0 and continue until the entire island is converted to 0. 4. that's 1 island, keep count of number of islands 5. return number of islands Time: O(N x M) - has to parse through each value in matrix space: O(N x M) - the grid

Check if we can make a valid word from a list of lists containing chars and given a word input: BABY { A, B } {B, A} {B, X} (Y, C}Output: True

1. Initialize a dp array with boolean false initialized len(list) times this represents the index of options as used 2. start dfs of word at index 0 with all the options 3. in dfs, if index is greater or equal to the length of word, return true 4. initialize result to true to use later 5. for each array of chars, if we check if the index has been used, skip if it has. 6. If it hasn't if the char is equal to the char at index, set the dp[index] to be True 7. run dfs for the next index 8. do this for all options, and return true if it works else false time complexity: O(M X N) m = len of word and n = options * number of possibilities per array

Number of Provinces Given an nxn matrix isConected where isConnected[i][j] = 1 if the ith and the jth city are directly connected, else 0. Things can be indirectly connected and still be 1 province. Return number of provinces

1. Parse list of list for value 1, if found, enter dfs function. Add one to answer. 2. dfs function will set the isConnected[i][j] to 0. And go through each index in isConnected[j] and if there is a connection, run DFS on that city as well. 3. Return ans.

Decode String Given encoded string, return decoded string. input: s = "3[a]2[bc]" out: "aaabcbc"

1. Parse the string. 2. If the character is a number, keep track of multiplier 3. if the char is '[', push into stack the string and the multiplier 4. if the char is just a non digit char , non special character, keep track of it as current_string. 5. if the char is ']', take out the multiplier and previous string and add previous string to multiplier * current string. 6. return decoded word

Variation of a basic calculator Given an expression, validate whether the expression. ex) (10+5) - { [ 5 * 1 * ( 3 + 3 ) ] - 2 }

1. Remove whitespace from string 2. Check if it starts with a negative number 3. if it does, add a 0 to the beginning 4. Loop through each character in reverse and check: 5. if it is a digit, add and keep track for continuous digits as it can be multiple digits 6. if there is a valid number, we want to add to stack and reset n, operand to 0 7. check if '(' then we want to evaluate what is on the stack. 8. stack.pop() to remove ')' 9. at the end of teh loop, check if there is a valid number if there is add to stack and evaluate 10. return ans.

Sort points in close K region We have a list of points on the plane. Find the K closest points to the origin (0,0).

1. Sorting Sort list by each lists' distance value return 0 to k subarray 2. Divide and conquer Partially sort A[i:j+1] so that the first K elements are the smallest K elements. 3. Put random elements as A[i] this is the pivot. 4. Partition by pivot A[i] returning an index mid such taht a[i] <= a[mid] <= A[j] for i < mid < j. 5. Compare distances in this partition and reorganize array. 6. return j 7. at the end return subarry 0 to k

Contiguous Array Given a binary array, find the maximum length of a contiguous subarray with equal numbers of 0 and 1.

1. There are only two choices(binary) 1 or 0, we want to have equal number of 1s and 0s which means that essentially we want the sum of 1s and 0s to be 0 if we were to give 1 the value of 1 and 0 the value of -1. 2. Keep a count adding 1 or subtracting 1 depending on nums[i]. 3. If the aggregate is 0 then we want to calculate max of current max or i+1 4. If we check the map for the new value of counter, and it exists, recalc new map with current max and i - index where it last occurred 5. add to hashmap index of counter value.

Robot bounded in circle On an infinite plane, a robot stands at (0,0) and faces north. The robot can receive three instructions: go 1 forward, turn left, turn right Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.

1. This is basically asking if robot is at the same position at the end of the instructions OR if the robot is not facing north. 2. Create a way to evaluate directions 3. Execute all the instructions and the robot should either be at (0,0) or facing north.

Trapping Rain Water

1. Track what the max height is for each index from left to right 2. Track what the max height is for each index from right to left 3. take the minimum max height from each index and subtract height at index. 4. Accumulate into answer

Length of longest substring without repeating characters

1. Update map of character to index +1 2. ans = max of ans or index - anchor + 1 3. When we come across a repetition, update the anchor to be max of map of s[i] or anchor. 4. return ans

Reorder Data in a log file You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier. Reorder so that the letter-logs come before all digit-logs. The letter-logs are sorted lexicographically by their contents. The digit logs maintain their relative ordering

1. Use the sorted() function to go through each log. 2. Split the log into 2, to (identifier, [rest of words]) 3. sort by rest of words, if it is alpha, should return before the digits.

Word break Given a non-tempty string and dictionary with words, determine if the string can be segmented into a space-separated sequence of one or more dictionary words.

1. Use two pointers 2. For each letter, upto the letter from the start, check if that word is in the dictionary. 3. For each index i(slow pointer), keep track of whether we can word break up to this point i. 4. At point i where i = len(s)+1, if word break was possible for the word made by j, and the word j to i is in the list, then set word break at i to be true. 5. Return the boolean at len(s) at the end.

Best Time to Sell stock You are given an array of stocks where price[i] is the price of teh stock on the ith day. You want to maximize profits, must buy before selling.

1. Use two pointers, if the fast pointer is less than the slow pointer, move the slow pointer to the fast pointer 2. Keep iterating through and find the max of fast-slow or max. 3. return max

Best Time to Buy and Sell Stock in two transactions

1. Use two variables to track cost and profit 2. Track minimum of price and min tracker for transaction 1 3. track max of t1_profit and price- t1_cost 4. t2_cost will be min of t2_cost or price-t1_profit 5. t2_profit will be max of t2_profit and price - t2_cost t2_cost will always be maximize for the min between profit of first transaction or whatever it is

Find the top - N question pairs Write a class that subscribes to a log of Alexa utterances, where each message contains line with the following fields(time, sessionID, location, questionText) - represents a question asked by a customer to Alexa at time T, write an algorithm to find the top-N question pairs.

1. What is the upper limit for how many top questions? 2. Define a data structure to use to store questions for example, map 3. Describe how to use the structure key = date, s#, XX, and value is the question 4. Fill the structure with values and save questions in a list. 5. Go through the list to find the most often asked question.

Analyze User Website Visit Pattern We are given some website visits: username[i] visited website[i] at timestamp[i] Find the 3-sequence visited by the largest number of users. If there is more than one solution, return the lexicongraphically smallest such 3-sequence. input: username['joe','joe','james], timestamp=[1,2,3], website:['home', 'about', 'career'] output: ['home', 'about', 'career']

1. consolidate three inputs into one using zip() 2. sort the tuple and parse through to create map of user to website visited as an array. This maintains order of website visit time 3. Go through each 3 sequence and count each occurrence. 4. return the most frequence 3sequence after sorting to get the lexicongraphically small value.

longest common subsequence text1 = 'abcde' text2 = 'ace' output: 3 ==> 'ace'

1. create a 2d matrix with len(text1)+1 X len(text2)+1 as the grid boundaries 2. reverse both starting at the bottom right, 3. if they are the same add 1 to dp[row+1][col+1] 4. else take the max of one row above or column above 5. repeat until it's fully filled and return dp[0][0]

Validate a BST

1. empty trees are valid BST 2. if the current node is not between low and high, return False, 3. Left and right subtrees must also be valid so recursively loop through left and right. For right, the low becomes the head val, for left, the high becomes head value. O(N)/O(N) Inorder traversal 1. if root is null return true 2. call function for root.left 3. if root.val is less than or equal to self.prev, return false 4.self.prev = current val 5. return recursive function for root.right 6. initialize self.prev as min poss number 7. return the recursive function with root input.

Min number of meeting rooms

1. initialize meeting rooms to be number of meetings 2. create two arrays one of start time sorted by start time and the second sorted by end time 3. whenever the startTime is greater than or equal to a meeting endTime subtract a meeting room and increment endtime pointer. 4. return rooms

Decode Ways '1123' decode how many ways that can be

1. intialize dp array with len(s) + 1 2. set first value as 0 3. set second value as 0 if the first char is '0' else 1 4. loop through range 2, len(dp) 5. if s[i-1] != '0': dp[i] = dp[i-1] 6. check if s[i-2:i] if two digits, if so, dp[i] += dp[i-2] return the last value in dp.

3 SUM Given an array of numbers find 3 numbers that sum to 0 May not contain duplicate triplets.

1. sort the array 2. We should be starting with negative numbers 3. As long as the number is negative and as long as it's not the same as its next neighbor, calculate two sum 4. Initialize a set 5. j = i+1, check of if there's a complement to -nums[i] - nums[j] 6. if the complement is in the set, add [nums[i],nums[j], complement) to answer. 7. Iterate j +=1 until you see a repetition or if it exceeds the length of nums. 8. Add nums[j] to the set. 9. iterate j+=1 10. repeating this for every value in nums will give 3 sum.

Consecutive Numbers Sum Given a number N, find how many ways we can write it as a sum of consecutive integers

1. sum of natural numbers theory N = kx + k(k+1)/2 iterate through 1 to and see if the theory cna go thru with 0 remainder. Add one to answer

LRU Cache Design a data structure for a least recently used cache. Should have functions: constructor(capacity), int get(int key), void put(int key, int value), add_node(self, node) remove_node(self, node) pop_tail(self) move_to_head(self, node)

1.A least recently used cache can only keep N values where N is the capacity. 2. Create a double linked list class that can go .next() and .prev() 3. Initialize with capacity, cache, size, and 2 double linked lists. 4. Replicate a ordered dictionary by using double linked lists. 5. Double linked list will have functions add_node, remove_node, move_to_head and pop_tail 6. add_node will set the new node after the head, set head.next.prev to new node and connect it inbetween. 7. remove_node will remove node, handle both prev and next 8. move_to_head will remove the node and add node. 9. pop_tail will remove the tail aka least recently used and return it 10. the LRU class itself has two functions get and put. 11. get() will return the value from cache if it exists, then move that node to head. 12. put will add the node to the cache and also create a new node for the key,value and add node to linked list. if it already exists, just update the value and move to head. add_node: newNode.next = self.head.next newNode.prev = self.head self.head.next.prev = newNode self.head.next = newNode remove_node(self, node): prev = node.prev new = node.next prev.next = next new.prev = prev pop_tail(self): prev = self.tail.prev self.remove_node(prev) move_to_head(self, node): self.remove_node(node) self.add_node(node)

Find minimum in rotated sorted array Suppose an array of length n sorted in ascneding order is rotated between 1 and n times. [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2] if rotated 4 times [0,1,2,4,5,6,7] if rotated 7 times.

Create a buffer so that you can keep checking to the i-1 for if nums[i-1] is greater than nums[i] then nums[i] is the minimum. Faster do a binary search, check if middle value is greater than left, if so, go right to find a value greater than middle. Else go left to find a value less than middle.

Integer to English

Create a functions that take in a number and depending on the mapping of 1-9: to english 10:-19: teens 2-9: twenty-thirty base of tens return the english define a function that evaluates whether num < 10, num < 20, else if it's 2 digits define a function that evaluates on 3 digit number the hundreds then call twodigit function for remaining handle case for billion, million, thousand and the remaining.

Minimum Difficulty of a Job Schedule You want to schedule a list of jobs in d days. Jobs are dependent. To work on the i-th job, you have to finish all jobs j where 0 <= j < i. You have to finish at least one task every day. The difficulty of a job schedule is the max difficulties of each day of d days. Given an array of integers jobDifficulty and an integer d. The difficulty of the i-th job is jobDifficulty[i] Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.

If the length job difficulty array is less than number of days, it cannot be done. Create a matrix m x n where m = number of job difficulties n = number of days set dp[m][0] = max(job difficulties the day before, job difficulty of today) dp[m][n] = dp[m-1][n-1] + job difficulty return the very last job difficulty in dp by dp[-1][-1]

Merge Sort

Split the array in half, sort each half and then merge the halves together O( nlogn) on average, best, and worst O(n) space

Find the longest substring with equal number of alphabets and numbers given an input containing alphanumeric string.

This is done by adding 1 if letter and -1 if number, repeat this and keep track of largest contiguous string that has 0 as the total counter.

Amazon pickup location has series of lockers for packages to be dropped off and picked up. Packages can come in different sizes, lockers are also of varying sizes. Model the lockers, packages and pickup location and implement an algorithm for efficiency. Finding the best possible empty locker for a given package.

class package: id size status - preparing, shipped, arrived, received, returned lockerid slotid locker code methods: update status updatelocker info class locker: id size expiration date packageid methods: put- put a package in get - get a package out class pickuplocation id location availLockers numTotalLockers numUsedLockers etc Check through all the available lockers and sort by size. Find the minimum that fits the package and return O(n log n) If already sorted, binary search for the locker O(log n)

Reverse a linked list

def reverse(node): if not node or node.next: return node newNode = reverse(node.next) node.next.next = node node.next = None return newNode

Array of numbers could be either in increasing order or decreasing order or increasing then decreasing order or vice-versa.print the type of array based on this order. If array = [1,2,3,4,3,2,1] output should be "increasing-decreasing" with time complexity O(1)

if len(arr) < 2: return -1 if arr[0] == arr[-1] and arr[0]< arr[1]: return "increasing-decreasing elif arr[0] == arr[-1] and arr[0]>arr[1]: return "decreasing-increasing elif arr[0]<arr[1]: return "increasing" else: return "decreasing"

Best time to buy and sell stock in K transactions

initialize the first cost and profit to be as if you can only do 1 transaction. then do cost[ith transaction] = min(price, profit[i-1] profit[i] = max(profit[i], price - cost[i]) return the k-1th profit.


Related study sets

Final Test Organizational Behavior Questions

View Set

Chapter 60-Cardiovascular System

View Set

BUS 211 - Management Information Systems Exam 1

View Set

Supply Chain Management Chapter 7: Demand Forecasting in a Supply Chain

View Set

Geography Chapter 5, Geography Chapter 6

View Set

D104 Intermediate Accounting II Units 4-6

View Set

Why did the USSR collapse in the 1990's?

View Set