Facebook algorithms

Ace your homework & exams now with Quizwiz!

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice.

- Start at both sides of arr with i = 0 and j=len(arr) - 1 - while i < j + sum = arr[i] + arr[j] + if sum < target: i++ + elif sum > target: j-- + else: Return j and i

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. Example 1: Input: [[0, 30],[5, 10],[15, 20]] Output: 2 Example 2: Input: [[7,10],[2,4]] Output: 1

- sort rooms - make heap (h = [ ]) - iterate through rooms + if h is empty: heappush(h, room[1]) + else: while len(h) > 0 and room[0] >= h[0]: heappop(h), then heappush(h, room[1] + max = max(<>) return max

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

- switch both dividend and divisor to positive by setting value to 0-value if less than 0 -multiples = [] - curr = dr - mul = 1 while curr <= dd: multiples.append((mul, curr)) curr = curr + curr mul = mul + mul - output = 0 - sum_curr = 0 output = 0 sum_curr = 0 while len(multiples) > 0: tmp = multiples.pop() if sum_curr + tmp[1] <= dd: sum_curr += tmp[1] output += tmp[0] - if negative: + if output >= (2 ** 31) + 1: return overflow + return 0 - output else: + if output > 2 ** 31: return overflow + return output

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

- Do BFS, keep track of depth, and terminate of first node without children

Given a collection of distinct integers, return all possible permutations.

- return corner cases - self.out = [] - self.arr = nums - self.traverse(1, nums[0] RECURSIVE FUNC - traverse(self, i, rec) - if i >= len(self.arr): out.append(rec): return - else: + for j in range(0, i): + rec_copy = rec + rec_copy.insert(j, self.arr[i]) + self.traverse(i + 1, rec_copy) + rec.append(arr[i]) + self.traverse(i + 1, rec)

Given a file and assume that you can only read the file using a given method read4, implement a method read to read n characters. Your method read may be called multiple times.

- on class __init__ create self.cache = [] - read = 0 - buf4 = [None] * 4 - while read < n: + tmp = read4[buf4] + read += tmp + self.cache.extend(buf4[:tmp]) + if tmp < 4: break - buf.clear() - for i in range(0, n): + if i >= len(self.cache): break + buf.insert(i,self.cache.pop(0)) return i

Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: Input: [1,2,3] 1 / \ 2 3 Output: 6 Example 2: Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42

DFS recursive search - global max - return 0 if None - left = max(self.traverse(n.left), 0) - right = max(self.traverse(n.right), 0) - global max = max(global_max, n.val + left + right) - return max(left, right) + n.val In parent return global max

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. Example 1: Input: 123 Output: "One Hundred Twenty Three" Example 2: Input: 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" Example 4: Input: 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

Split into two parts: Return string values of anything in 999 or less For every 10^3 put this string value plus thousand, million, billion THERE ARE A TON OF CORNER CASES: - zero - 1000000 - 1001 - 1099 - teens - multiple spaces - ending with spaces - etc

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer.

The trick is that if two numbers have the same remainder value, then their difference is divisible by k. Building off the continuous subarray problem, we know the difference between them is the sum of the numbers between them (aka subarray). Use a hashmap and put the modulo of the continuous sum. - do zero check if k == 0 - d = {0:1} - tmp = 0 - for i, n in enumerate(nums): + tmp += n + tmp %= k + if tmp in d: + if (i - d.get(tmp)) >= 2: return True + else: d[i] = tmp - return False

Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.

Would use either python library or regex is real world. But since don't have access to them right now, I would right string checks for rules.

fibonacci

def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fib_rec(0, 1, 0, n) # Write your code here. def fib_rec(prev_1, prev_2, count, n): curr = prev_1 + prev_2 count += 1 if count == n: return(curr) else: return(fib_rec(curr, prev_1, count, n)) Or other way public int CalculateFibonacci(int n) { if(n < 2) return n; return CalculateFibonacci(n-1) + CalculateFibonacci(n- 2); }

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

num1 = num1[::-1] num2 = num2[::-1] mul = 1 out = 0 for c1 in num1: tmp_sum = 0 tmp_mul = 1 for c2 in num2: val = tmp_mul * int(c2) * int(c1) tmp_sum += val tmp_mul *= 10 out += (tmp_sum * mul) mul *= 10 return str(out)

Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets.

recursion, if in map return zero, otherwise append value and call all combos def traverse(self, arr): t = tuple(arr) if t in self.visited: return else: self.visited[t] = 1 self.out.append(arr) if len(arr) <= 1: return for i in range(0, len(arr)): self.traverse(arr[:i] + arr[i+1:])

Roman to Integer

simple solution: go backwards through string - if val[i-1] < val[i]: out += val[i] - val[i-1], i -= 2 - else: out += val[i], i-=1

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n).

Do custom binary search to find pivot then do bin search on both sides of pivot - search = nums[0] - pivot = 0 - lo = 0; hi = len(nums) - while lo < hi: + mid = math.floor((hi + lo) / 2) + if mid == 0: break + if nums[mid] < nums[mid-1]: pivot = mid; break + elif nums[mid] > search: lo = mid + 1 + else: hi = mid - if not bin(search both sides) return -1, else return found

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

carry = 0 head = node = ListNode() while l1 is not None or l2 is not None or carry == 1: if l2: l2_val = l2.val else: l2_val = 0 if l1: l1_val = l1.val else: l1_val = 0 val = l1_val + l2_val + carry carry = 0 if val >= 10: val -= 10 carry = 1 node.next = ListNode(val) node = node.next if l1 is not None: l1 = l1.next if l2 is not None: l2 = l2.next return head.next

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode() node = head while l1 or l2: if not l2: node.next = l1 l1 = l1.next elif not l1: node.next = l2 l2 = l2.next elif l1.val <= l2.val: node.next = l1 l1 = l1.next elif l2.val < l1.val: node.next = l2 l2 = l2.next else: print("ERROR") node = node.next return head.next

Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters. Method read4: The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf. The return value is the number of actual characters read. Note that read4() has its own file pointer, much like FILE *fp in C. Definition of read4: Parameter: char[] buf4 Returns: int Note: buf4[] is destination not source, the results from read4 will be copied to buf4[] Below is a high level example of how read4 works:

def read(self, buf, n): count = 0 tmp_list = [] buf4 = [None] * 4 while count < n: tmp = read4(buf4) count += tmp tmp_list.extend(buf4) if tmp != 4: break buf[:] = tmp_list[:] return min(count, n) NOTE: extend is list method, and return min

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

i = 0 for j in range(1, len(nums)): if nums[j] != nums[i]: i += 1 nums[i] = nums[j] return i + 1

Given two sparse matrices A and B, return the result of AB. You may assume that A's column number is equal to B's row number.

- Go through and put locations with values in dictionaries, then multiply them and expand to full array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Constraints: -10^9 <= nums1[i], nums2[i] <= 10^9 nums1.length == m + n nums2.length == n Accepted

- Go through nums1 and pop the zeros from (m, len(nums1) - i = 0 - while len(nums2 > 0) - val = nums2[0] - if i >= len(num1), append val and pop nums2(0) - elif val < num1[i], num1.insert(i, val) and pop nums2(0) - i++

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

- Instantiate tuple hash map - go through and if encounter island and if it's not in the dict, then recursively put all coords in dict and increment count

Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children.

- call recursion - traverse(self, n, path) - if not n: return - if both children are None: path += str(n.val); append; return - path += str(n.val) + "->" - call traverse(n.left, path) and traverse(n.right, path)

Given a binary tree, flatten it to a linked list in-place.

- can do normal DFS with q, but this problem statement prohibits that - recursive traverse(self, n) - if n is None: return - if n.left is None and n.right is None: return n - left = self.traverse(n.left) - right = self.traverse(n.right) - if left: + if right: left.right = n.right + n.right = n.left + n.left = None - if right: return right - else: return left

Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.

- create OrderedDict - call recursive DFS - return self.d.popitem(last=False)[1] RECURSIVE DFS - make_graph(self, n) - if n.val in self.d: return - new_node = Node(n.val) - self.d[n.val] = new_node - for neighbor in neighbors: + self.make_graph(neighbor) - new_node.neighbors = [] - for neighbor in n.neighbors: + new_node.neighbors.append(self.d.get(neighbor.val))

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. Note: The input string may contain letters other than the parentheses ( and ). Example 1: Input: "()())()" Output: ["()()()", "(())()"] Example 2: Input: "(a)())()" Output: ["(a)()()", "(a())()"] Example 3: Input: ")(" Output: [""]

- create get_removes(s) method that counts through and gets number of ")" <dsr> and "(" <dsl> to remove - call get_removes to get original number to remove - create visited dictionary and results list - call recursion method that takes in (s, dsr, dsl) + if s in self.visited return, otherwise put s in self.visited + if dsl == 0 and dsr == 0, then check if valid with self.get_removes. If valid put in results list + if dsr > 0, for (i, char) in s, if char == "(", call self.recursion(s[without i (string cut)], dsr - 1, dsl + elif do same with dsl NOTE: For string without [i] char: if i < len(s) - 1: self.rec_search(s[:i] + s[i+1:], dsr - 1, dsl) else: self.rec_search(s[:i], dsr - 1, dsl)

Given an array w of positive integers, where w[i] describes the weight of index i(0-indexed), write a function pickIndex which randomly picks an index in proportion to its weight. For example, given an input list of values w = [2, 8], when we pick up a number out of it, the chance is that 8 times out of 10 we should pick the number 1 as the answer since it's the second element of the array (w[1] = 8). Example 1: Input ["Solution","pickIndex"] [[[1]],[]] Output [null,0] Explanation Solution solution = new Solution([1]); solution.pickIndex(); // return 0. Since there is only one single element on the array the only option is to return the first element. Example 2: Input ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] [[[1,3]],[],[],[],[],[]] Output [null,1,1,1,1,0] Explanation Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It's returning the second element (index = 1) that has probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It's returning the first element (index = 0) that has probability of 1/4. Since this is a randomization problem, multiple answers are allowed so the following outputs can be considered correct : [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on.

- create list of vals that are the sum of all the vals prior plus current - get random.random() * self.tot - do binary search to find where the random value lies while lo < hi: mid = math.floor((lo + hi) / 2) if arr[mid] >= x: if mid == 0 or arr[mid -1] <= x: return mid hi = mid else: lo = mid + 1

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example: Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

- create num_map and empty results list - if len(digits) < 1 return [] - Call recursive function def permute(self, num_str, let_str, i): if i >= len(num_str): self.results.append(let_str) return num = int(num_str[i]) chars = self.num_map.get(num) for char in chars: self.permute(num_str, let_str + char, i + 1) - return self.results

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.

- create self.first and self.last, then call recursive DFS traversal + if n == None, return + traverse(n.left) + if self.first is None, self.first = n and self.last = n + else, self.last.right = n; n.left = self.last, self.last = n + traverse(n.right) - Then link first and last together - return first

Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.

- sort intervals by left val - create new list, merged = [ ] - iterate through sorted list + if len(merged) < 1: append val + else: + if merged[-1[1] is between val[0] and val[1]: merged[-1][1] = val[1] + if val[0] > merged[-1[1]: append val return merged

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Example: BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.

- create self.stack - create helper + while(n is not None): self.stack.append(n), n = n.left - for has_next: return false if self.stack is empty - for next return stack.pop(), and call helper on .right of popped node Non-ideal answer Iterate over tree and call append after recursive call to left branch and before recursive call to right branch.

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 1,2,3 → 1,3,23,2,1 → 1,2,31,1,5 → 1,5,1

- find the largest index such that str[i-1] is less than str[i] - reverse arr and Return false if no decrease is found - Find the the highest index to the right (j) such that str[j] is greater than str[i-1] - Swap str[i - 1] with str[j] - Reverse substring [i:]

Given two strings s and t, determine if they are both one edit distance apart. Note: There are 3 possiblities to satisify one edit distance apart: Insert a character into s to get t Delete a character from s to get t Replace a character of s to get t

- if s == t: return - if len(s) == len(t): loop: if (s[:i] + s[i+1:]) == (t[:i] + t[i+1:]): return True - if len(s) - len(t) == 1: loop: if s == (t[:i] + t[i+1:]): return True - if len(s) - len(t) == -1: loop: if (s[:i] + s[i+1:]) == t: return True - else: return False

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. Note: Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. Example 1: Input: "42" Output: 42 Example 2: Input: " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42. Example 3: Input: "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. Example 4: Input: "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed. Example 5: Input: "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.

- in_num = False -loop + if in_num, if numeric append, else break + if " " continue + if "+" or "-" or numeric, append and set in_num = True - len(out) < 0, return 0 - calculate if neg - pop + or - if there is one - convert to string - if not numeric, return 0 - multiply by neg if neg is true - set min and max - return

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets.

- return if len(nums) < 3 - nums.sort() - create dict with the first index of any number value - for start in d.vals() + break if start >= len(nums) - 2 + i = start + 1 + j = len(nums) - 1 + while i < j sum_val = nums[start] + nums[i] + nums[j] if sum_val == 0: self.add_visit(nums[start], nums[i], nums[j]) i += 1 elif sum_val < 0: i += 1 else: j -= 1 NOTE check for duplicates helper def add_visit(self, a,b,c): if (a,b,c) not in self.visited: self.visited[(a,b,c)] = 1 self.visited[(a,c,b)] = 1 self.visited[(b,a,c)] = 1 self.visited[(b,c,a)] = 1 self.visited[(c,a,b)] = 1 self.visited[(c,b,a)] = 1 # print(f"append {a} {b} {c}") self.out.append([a,b,c])

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1] Constraints: 0 <= nums.length <= 10^5 -10^9 <= nums[i] <= 10^9 nums is a non decreasing array. -10^9 <= target <= 10^9

- return invalid if len(arr) < 1 - to get left index get bisect.bisect_left(arr, x). If index == len(arr) or arr[index] != target, return invalid - to get right index get bisect.bisect_right(arr,x) - 1 - Return [left, right] NOTE: need to subtract right index - 1 FOR CODED BINARY SEARCH (mod this): - lo = 0 - hi = len(arr) - while hi > lo + mid = math.floor((hi + lo) / 2) + if arr[mid] == target, return + Mod this to check for left val !=, then mid = hi + if arr[mid] < x, lo = mid + 1 + if arr[mid] > x, mid = hi

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

- return value of recursion - def traverse(self, n, upper=float('inf'), lower=float('inf') - if n is None: return True - if n.val <= lower or n.val >= upper: return False - if not self.traverse(n.left, n.val, lower): return False - if not self.traverse(n.right, upper, n.val): return False - return True

Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" Constraints: Each string consists only of '0' or '1' characters. 1 <= a.length, b.length <= 10^4 Each string is either "0" or doesn't contain any leading zero.

- reverse string - create logic helper (a,b,c) tmp_sum = int(a) + int(b) + c if tmp_sum == 0: return 0, "0" elif tmp_sum == 1: return 0, "1" elif tmp_sum == 2: return 1, "0" elif tmp_sum == 3: return 1, "1" Then do while statement with carry, char = self.get_sum(a[i], b[i], carry), etc. - out.insert(0, char) return string of out

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. The cache is initialized with a positive capacity. Follow up:Could you do both operations in O(1) time complexity?

- use and OrderedDict() - when get is called (pop val and re-append) + if key doesn't exist: return -1 + tmp val = self.d.pop(key) + self.d[key] = tmp_val + return tmp_val - put is called + if key is self.d: self.d.pop(key) + elif len > cap: self.d.popitem(0) + self.d[key] = val NOTE: popitem is OrderedDict method

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.

-loop through end of array to beginning, if 0 is found increment number of pops and pop that index. -go through and append number of pops 0's to array

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.

Create a dict with the number of occurences of each character in s1, then loop through and find the first char that is in the dict. Then go through and keep track of the matches with a dict and a que. If there are too many repetitions of a char, pop the end off the que and subtract from the match dict every pop. Then poppush the actual char. If the len of the que is the len of s2, return True. Also reinstatiate the q and match dict at the beginning of the main loop. - d = mapped to number of repetitions of chars in s1 - j = 0 - while j < len(s2) + match_d = {} + q = deque() + while s[j] not in d: j += 1 + while j < len(s) and s[j] in d: + if s2[j] not in match_d: match_d[s2[j]] = 1 + else: + if match_d[s2[j]] < d[s2[j]]: match_d[s2[j]] += 1 + while q[0] != d[s2[j]]: q.popleft() and decrement or remove match_d[q[0]] + q.append(popleft()) + if len(q) == len(s): return True + j += 1 - return False

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter.

Create a dict with the number of occurences of each character in s1, then loop through and find the first char that is in the dict. Then go through and keep track of the matches with a dict and two pointers. If the number of items in match_d is >= d: loop left pointer decrementing the number in match_d until you find the same char as the right pointer. If (r-l+1 == len(p)): add l to output. - d = dict of number of occurrences of chars - r = 0 - out = [] - while r < len(s): + while r < len(s) and s[l] not in d: r += 1 + l = r + match_d = {} + while r < len(s) and s[r] in d: + if s[r] not in d: put in d + else: + if match_d[s[r]] < d[s[r]]: match_d[s[r]] += 1 + else: + while s[l] != s[r]: + if match_d[s[l]] <= 1: match_d.pop(s[l]) + else: match_d[s[l]] -= 1 + l += 1 + l += 1 + if (r - l + 1) == len(s): out.append(l) + r += 1 - return out

Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

Create a graph with a dict and a mapping from each first email to all following emails, and a mapping of emails to names. Then do a search of the graph to find all linked emails, then sort them and prepend them with the name to one of the email, then put in output list. - graph = {} - emails_to_name = {} - for account in accounts: + for i in range (1: len(account)): + if account[i] in graph: append account[1] + else: graph[account[i]] = [account[1]] + if account[1] in graph: append account[i] + else: graph[account[1]] = [account[i]] + emails_to_name[account[i]] = account[0] SEARCH - result = [] - visited = {} - for email in graph: + if email in visited: continue; else visited[email]=1 + account = [] + q = deque(); q.append(email) + while len(q) > 0: + curr = q.popleft() + if curr in visited: continue; else visited[curr]=1 + account.append(curr) + for next in graph[curr]: q.append(next) + account.sort() + account.insert(0, emails_to_name[email]) + result.append(account) - return result

Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. Example: addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true Note:You may assume that all words are consist of lowercase letters a-z.

Create a trie with node = self.trie for char in word: if char not in node: node[char] = {} node = node[char] node["!"] = True Then traverse the tree: """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. """ node = self.trie self.found = False self.traverse(node, word, 0) return self.found def traverse(self, node, word, i): if not node: return if node == True: return # print(f"node {node}") if i >= len(word): if "!" in node: self.found = True return char = word[i] if char == ".": for item in node: self.traverse(node[item], word, i + 1) elif char in node: self.traverse(node[char], word, i + 1)

Given an array of integers 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. Note:The array size can be very large. Solution that uses too much extra space will not pass the judge. Example: int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(3); // pick(1) should return 0. Since in the array only nums[0] is equal to 1. solution.pick(1);

Create dictionary with arr of indexs of values return math.floor(random.random() * len(arr)) for key if value is len(arr) make it len(arr) - 1

Implement pow(x, n), which calculates x raised to the power n (xn).

Create list of tuples with num of multiples and multiple values. Then go through list and multiply multiple values if the sum of the num of multiples is less than n - n_sign = n ## for inverse powers - n = abs(n) - multiples = [] - curr = x - mul = 1 - while mul <= n: + multiples.append((curr, mul)) + curr *= curr + mul += mul - out = 1 - exp = 0 - while len(multiples) > 0: + tmp = multiples.pop() + if exp + tmp[1] <= n: + out *= tmp[0] + exp += tmp[1] - if n_sign < 0: return 1/out - else: return out

A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (12). Example 2: Input: "226" Output: 3 Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

DP Problem (very similar to fibonacci) - self.m = {} # for memoization - then call recursive dp method - if i = len(s): return 1 # can't do in one step cuz of zeros - if s[i] == "0": return 0 - if i >= len(s) - 1: return 1 - if i in self.m return self.m.get(i) - if s[i] + s[i+1] <= 26: + n = self.dp(i+1) + self.dp(i+2) - else: + n = self.dp(i+1) - self.m[i] = n - return n - then call dp method and return result

Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates). If two nodes have the same position, then the value of the node that is reported first is the value that is smaller. Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.

Do a BFS and keep track of l,r,x,depth. If x is in visited{} created and OrderedDict and append at depth a heap with the value of n.val Then loop through visited{} from l:r+1, and go through each value in the node values and heappop all the values of off.

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, 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.

Do a BFS and keep track of x position. Also keep track of max left and right to iterate through at the end. - if root is None: return [] - visited = {} - l = r = x = 0 - q = deque() - q.append((root, x)) - while len(q) > 0: - tmp = q.popleft() - n = tmp[0] - x = tmp[1] - if x not visited: + visited[x] = [n.val] + l = min(l,x) + r = max(r,x) - else: + visited[x].append(n.val) - if n.left: q.append((n.left, x - 1)) - if n.right: q.append((n.right, x + 1)) - out = [ ] - for i in range(l, r + 1): + out.append(visited[i]) - return out

Given 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. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---

Do a DFS with a dictionary to keep track of nodes that were visited. Do a check of the "level" before calling recursive search and if not in hashmap put in current node value.

A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that nums[-1] = nums[n] = -∞.

Do modified binary search where if slant going up to the right go right, else go left. Be careful of ends - lo = 0 - hi = len(nums) - while lo < hi: + mid = math.floor((hi + lo)/2) + left = max(0, mid - 1) + right = min(mid + 1, len(nums) - 1) + if nums[left] <= nums[mid] and nums[right] <= nums[mid]: return mid + if nums[left] <= nums[mid] and nums[right] >= nums[mid]: lo = mid + 1 + else: hi = mid

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).

Do recursive search, and if there is a * after the current char call recursive function on the text and pattern without star and recursive function on text without first char and pattern. Make sure to check valid compare before calling recursive function on text without first char. PARENT METHOD - self.visited = {} - return self.rec_helper(text, pattern) RECURSIVE HELPER - rec_helper(self, text, pattern) - if len(pattern) < 0: return len(text) < 0 - if (lens tuple in self.visited): return get - curr_match = self.comp_helper(text, pattern) - if len(pattern) > 1 and pattern [1] == "*": + zero_match = self.rec_helper(text, pattern[2:]) + match_rec = curr_match and self.rec_helper(text[1:], pattern) + self.visited[(len(text),len(pattern)] = zero_match and match_rec + return zero_match and match_rec else: + match_rec = curr_match and self.rec_helper(text[1:], patter[1:]) + self.visited[(len(text),len(pattern)] = match_rec + return match_rec HELPER COMPARE def comp_helper(self, text, pattern): if len(text) > 0 and len(pattern) > 0: if pattern[0] == text[0] or pattern[0] == ".": return True return False

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. Note: Please solve it without division and in O(n). Follow up:Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

Find products of multiples to the left and products of multiples to the right. Then loop through and the value is the multiple of the one index to left and the multiple of the one index on the right.

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Find sum of all components up to each square, then the value of a given square is its bottom-right corner minus the area that is not in the upper left corner. You can get this value by (a - b - c + d) NOTE: Account for empty array and out of bounds inputs Get the sums by making a matrix of sums cross then sums down. Then iterate over these two matrices and the values is the sum of both minus the component. - cross = down = self.ref = matrix.copy() for i in range(0, len(matrix)): tmp = 0 for j in range(0, len(matrix[0])): tmp += matrix[i][j] cross[i][j] = tmp for j in range(0, len(matrix[0])): tmp = 0 for i in range(0, len(matrix)): tmp += matrix[i][j] down[i][j] = tmp for i in range(0, len(matrix)): tmp = 0 for j in range(0, len(matrix[0])): self.ref[i][j] = cross[i][j] + down[i][j] - matrix[i][j] Get return value with values in self.ref - a = b = c = 0 d = self.ref[row2][col2] if row1 > 0 and col1 > 0: a = self.ref[row1 - 1][col1 - 1] if row1 > 0: b = self.ref[row1 - 1][col2] if col1 > 0: c = self.ref[row2][col1 - 1] return a - b - c + d

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the 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) where random pointer points to, or null if it does not point to any node.

Go through and add nodes to hash with index as value while node is not None: d[node] = i i += 1 node = node.next Create new copy and populate indexed new_node list nodes = [] new_head = Node(head.val) nodes.append(new_head) prev_node = new_head node = head.next while node is not None: new_node = Node(node.val) nodes.append(new_node) prev_node.next = new_node prev_node = new_node node = node.next Go through and link randoms while node is not None: if node.random: new_node.random = nodes[d.get(node.random)] node = node.next new_node = new_node.next return new_head

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"

Go through every possible center of palindrome and expand out - if len(s) < 1: return "" - self.max_str = s[0] - for i in range(0, len(s) -1): + self.is_pal(s, i) + self.is_pal(s, i, i + 1) - return self.max_str Helper method to find if palindrome - is_pal(self, s, i, r = None) - if r is None: + r = l + 1 + l = l - 1 + length = 1 - else: length = 0 - if l < 0 or r >= len(s) or s[l] != s[r]: return - while l >= 0 and r < len(s) and s[l] == s[r]: + length += 2 + if length > len(self.max_str): self.max_str = s[i:r+1] + r += 1 + l -= 1

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)." Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

Go through tree and return True if found. Then if left and right are true or self and branch are true, set global val to node.

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'.

Go through with double pointers and if not palindrome remove chars from both sides and recheck both combos of the string to see if it is a palindrome.

Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. (Formally, 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 is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].) Example 1: Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]] Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] Note: 0 <= A.length < 1000 0 <= B.length < 1000 0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9

If there is no overlapping in the A and B lists then you can just do: lo = max(A[0], B[0]) hi = min(A[1], B[1]) if lo <= hi: append(lo, hi) If there is overlapping do if else statement for 8 possible outcomes of compare. Then on positive compares call append help to compare right val of section to see if it gets appended to list.

Say you have an array prices for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy ag

Loop through (1, len) and if curr > prev += profit by it

On a single threaded CPU, we execute some functions. Each function has a unique id between 0 and N-1. We store logs in timestamp order that describe when a function is entered or exited. Each log is a string with this format: "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means the function with id 0 started at the beginning of timestamp 3. "1:end:2" means the function with id 1 ended at the end of timestamp 2. A function's exclusive time is the number of units of time spent in this function. Note that this does not include any recursive calls to child functions. The CPU is single threaded which means that only one function is being executed at a given time unit. Return the exclusive time of each function, sorted by their function id.

Keep track of prevtime and starts indexes in stack. Subtract current time minus previous time and add to value for previous index. For starts append to stack, for stops, pop stack. Also make sure to ask about rules for calls, can end happen asynchronously, is it sorted?

Given a singly linked list L: L0→L1→...→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→... You may not modify the values in the list's nodes, only nodes itself may be changed.

LIST METHOD If can have O(N) space - go through and add nodes to list while i < math.floor(len(nodes) / 2): tmp = node.next node.next = nodes[len(nodes) - 1 - i] node.next.next = tmp node = tmp i += 1 node.next = None IN ORDER METHOD 1. go through list while fast and fast.next: slow = slow.next fast = fast.next.next 2. Reverse end of list prev, curr = None, slow while curr: tmp = curr.next curr.next = prev prev = curr curr = tmp 3. Merge lists node_begin = head node_end = prev while node_end and node_end.next: tmp = node_begin.next node_begin.next = node_end node_begin = tmp tmp = node_end.next node_end.next = node_begin node_end = tmp

Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B. The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice.

Loop through every index in the graph and if node isn't in hashmap, do a bfs to verify it is red, black - create switch_colour helper and define RED=0, BLACK=1 - visited = {} - q = deque() - for count in range(0, len(graph)): + if count not in visited: q.append(count, RED) + while len(q) > 0: + i, colour = q.popleft() + n = graph[i] + if n not in visited: n[visited] = colour + else: + if visited[i] != colour: return False + continue + for j in graph[n]: q.append(j, self.switch(colour)) - return True

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Make a q, push -1, then go through string and if ( push i, if ) tmp = pop, then if stack empty put i in, otherwise find max. Max is i minus top of stack. - q = deque() - max_len = 0 - q.append(-1) - for i, c in enumerate(s): + if c == "(": q.append(i) +else: q.pop() + if len(q) < 1: q.append(i) + else: max_len = max(max_len, i - q[-1]) - return max_len

Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter.

OPTIMAL APPROACH - Make hash that maps chars to index - Make tuple key of number of time each char occurs in [0] * 26 list key - If tuple key exists in dict, append to list - else make new list - return d.values() NON-OPTIMAL APPROACH d = {} for s in strs: ss = str(sorted(s)) if ss in d: d[ss].append(s) else: d[ss] = [s] return d.values()

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6

Push k elements on heap, pop heap and if next push next. The trick is to use k elements and this reduces time complexity to Nlog(k)

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.

Recursive solution where you go through and call appending a char, adding, subtracting, or multiplying. You have to keep track of the previous value since multiplication overrides it, and also for appending. - rec(i, prev, curr, val, s) - curr = curr*10 + int(num[i]) - op = str(curr) APPEND - if curr > 0: + rec(i + 1, prev, curr, val, s) ADD - s.append(<operator>) - rec(i + 1, curr, 0, val + curr, s) - s.pops - if len(s) > 0: MULTIPLY + curr_sum = val - prev + (curr * prev) + s.append(<operator>) + rec(i+1, prev * curr, 0, curr_sum, s) + s.pops SUBTRACT + s.append(<operator>) + rec(i+1, -curr, 0, val - curr, s) + s.pops - rec_helper(0,0,0,0,[]) -return out

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n.

Recursively traverse through string and each time move left and right and add all reversible characters NOTE: For this problem we have zero as special case cuz it can't be on ends, but is that the case in the interview? END_NUMS = {1: 1, 6: 9, 8: 8, 9: 6} MID_NUMS = [0, 1, 8] - self.results = [] - init = [None] * n - self.rec(init, 0, n - 1) - return self.results Recursive function - rec(self, arr, l, r) - if l >= math.floor(len(arr) /2): + if len % 2 == 0: + self.results.append("".join(arr)) + else: + for num in MID_NUMS: + arr[l] = str(num) + self.results.append("".join(arr)) - for key in END_NUMS: + arr[l] = str(key) + arr[r] = str(END_NUMS[key]) + self.rec(arr, l + 1, r - 1) - if l > 0: + arr[l] = arr[r] == "0" + self.rec(arr, l + 1, r - 1)

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Note: Given target value is a floating point. You are guaranteed to have only one unique value in the BST that is closest to the target. Example: Input: root = [4,2,5,1,3], target = 3.714286 4 / \ 2 5 / \ 1 3 Output: 4

Traverse tree and keep track of global min_compare node. While traversing, if val is less than node.val go left, otherwise go right

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

STEP 0: put all unique letters in map - for word in words: for c in word: map[c] = [] STEP 1: Find where characters change across words - for i in range(0, len(words) - 1): + for j in range(0, min(word1, word2)): + if c1 != c2: map[c1].append(c2): break + else: if len(word2) < len(word1): return "" (prefix of word1) STEP 2: DFS in map - self.out = [] - self.seen = {} - self.map = map - for n in map: if not self.dfs(n): return False - return "".join(self.out[::-1] DFS SEARCH - dfs(self, n) - if n in self.seen: return self.seen.get(n) - self.seen[n] = False - for next_n in self.map.get(n): + if not self.dfs(next_n): return False - self.seen[n] = True - self.out.append(n) - return True

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Same as permute, but add tuple dict t = tuple(rec) if t in self.visited: return else: self.visited[t] = 1

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false

Simple solution Go through and if char.isalnum(): append(char.lower()) if new_s == [::-1] new_s: return true Also, there is pointer solution for O(1) time complexity

Given a binary tree, you need to compute 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. Example:Given a binary tree 1 / \ 2 3 / \ 4 5 Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. Note: The length of path between two nodes is represented by the number of edges between them.

Simple solution Recursive DFS search tree with depth tracker. Return depth. Current node is left + right + 1 If node is None, return 0 else, return max(left, right) + 1 Globally keep track of Max.

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Simple solution: Reverse string or start from end. Add each value and see if there is carry over, continue. NOTE: to reverse num1 = num1[::-1] num2 = num2[::-1]

Given a string, find the length of the longest substring T that contains at most k distinct characters. Example 1: Input: s = "eceba", k = 2 Output: 3 Explanation: T is "ece" which its length is 3. Example 2: Input: s = "aa", k = 1 Output: 2 Explanation: T is "aa" which its length is 2.

Sliding Window - create l pointer, r pointer, d dict - while r < len(s) + while r < len(s) and len(d) <= k + add or increment s[r] in d, r++ + if len(s) == r and len(d) <= k: max(out, r-l) + else: max(out, r - l - 1) + while len(d) > k and l < r: - pop(s[l]) from d or decrement return out

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

Sliding window - create dict (t_d) and put num of occurrences of each char in t string - create found_d dict and found counter - initialize out and out_s - while r < len(s) - loop right: while r < len(s) and found < len(t): c = s[r] if c in t_d: if c in found_d: found_d[c] += 1 if found_d[c] <= t_d[c]: found += 1 else: found_d[c] = 1 found += 1 r += 1 loop left: while l < r and found >= len(t): c = s[l] if c in found_d: found_d[c] -= 1 if found_d[c] < t_d[c]: found -= 1 if (r - l) < out: out = r - l out_s = s[l:r] l += 1 return out_s

Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Sliding window - d = {} - while i and j < len(s) + if s[j] not in d, then add s[j] to d and increment j + else remove s[i] from d and increment i

A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order. Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1. You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface: BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed). BinaryMatrix.dimensions() returns a list of 2 elements [rows, cols], which means the matrix is rows * cols. Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

Start on upper right corner of matrix Decrement down If is 1 loop to left most 1 and leave index there Return index

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words.

TODO: Make sure solution is optimal

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Constraints: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

The idea behind this approach is as follows: If the cumulative sum(repreesnted by sum[i] for sum upto i^ith index) upto two indices is the same, the sum of the elements lying in between those indices is zero. Extending the same thought further, if the cumulative sum upto two indices, say i and j is at a difference of k i.e. if sum[i]−sum[j]=k, the sum of elements lying between indices ii and j is k. put (0) in hashmap. Go through keep cumulative sum put sum in hashmap or if sum is already in hashmap increment it. If sum - k in hashmap increment count by the value of that key

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note:You may assume k is always valid, 1 ≤ k ≤ array's length.

Trick is to use heap instead of sort in order to reduce time complexity to nlogk class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: out = heapq.nlargest(k, nums) return out[k-1]

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

USE BISECT self.__getitem__ = isBadVersion return bisect.bisect_left(self, True, 1, n) BIN SEARCH lo = 0 hi = n + 1 while lo < hi: mid = math.floor((lo + hi)/ 2) if mid == 0: return 0 val = isBadVersion(mid) val_left = isBadVersion(mid - 1) if val != val_left: return mid elif val: hi = mid else: lo = mid + 1 # return 0

You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where: Each 0 marks an empty land which you can pass by freely. Each 1 marks a building which you cannot pass through. Each 2 marks an obstacle which you cannot pass through.

Verify that a space in the middle of 4 building is travel of 4 and not one. Do a BFS on each 1 square and add to the distance traveled for each 0 square. Then find the min of the 0 square. - count = 0; self.sum_grid = [] - for i in range(0, len(grid)): + self.sum_grid.append([]) + for j in range(0, len(grid[i])): + self.sum_grid[i].append([0,0]) + if grid[i][j] == 1: count += 1 - if count < 1: return -1 - for (i,j): if self.bfs() != count: return -1 - min = float('inf') - for(i,j): + if grid[i][j] == 0 and self.sum_grid[i][j][1] == count: + min = min(min, self.sum_grid[i][j][0] -return min path BFS - bfs(self, grid, i, j) - found = 1 - visited = {} - q = deque() - q.append((i, j, 0)) - hit_land = False - while len(q) > 0: + tmp = q.popleft(); then get i, j, depth from it + if (i,j) in visited: continue; else put in visited + if grid[i][j] == 2: continue + if grid[i][j] == 1 and depth > 0: + found += 1 + continue + if grid[i][j] == 0: + hit_land = True + self.sum_grid[i][j][0] += depth + self.sum_grid[i][j][1] += 1 + call stack on q for all 4 sides - if hit_land: return found - else: return -1

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one.

min_price = prices[0] max_profit = 0 for price in prices: min_price = min(price, min_price) profit = price - min_price max_profit = max(profit, max_profit) return max_profit

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Example: You may serialize the following tree: 1 / \ 2 3 / \ 4 5 as "[1,2,3,null,null,4,5]" Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

serialize: DFS search and put n.val or "n" in search order deserialize: - make list from string Recursive function - if "n", then pop list[0], return None - make node(list.pop(0)) - node.left is (l) - node.right is (l) return node

In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language. Example 1: Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. Example 2: Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. Example 3: Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info). Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 20 order.length == 26 All characters in words[i] and order are English lowercase letters.

simple solution Put chars as keys in hashmap with incremented value. Then compare down words.

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. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or 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. Example 1: Input: s = "lee(t(c)o)de)" Output: "lee(t(c)o)de" Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. Example 2: Input: s = "a)b(c)d" Output: "ab(c)d" Example 3: Input: s = "))((" Output: "" Explanation: An empty string is also valid. Example 4: Input: s = "(a(b(c)d)" Output: "a(b(c)d)"

stack for right and stack for left Go through and append left "(" and put ")" on right stack unless there is something in left stack. Then just pop left stack Then go through append chars to output string. If the is something in left stack and is "(" then don't append, if something in right stack and is ")" don't append, otherwise append char. Return output strick


Related study sets

240 Tutoring EC-6 TEACHING SOCIAL STUDIES INSTRUCTION

View Set

SPC 205 Ch.8 Supporting Your Ideas

View Set

Policy Riders, Amendments, and Options Questions

View Set

Articles of Confederation to Checks and Balances

View Set

ANTH 1150 Pearson Questions Chapter 1

View Set

Economics Chapter 14 Notes Federal Reserve System

View Set

CHAPTER 2 Review (Intro to computers)

View Set