text
stringlengths
37
1.41M
Words = "Why sometimes I have believed as many as six impossible things before breakfast".split() print(Words) '''To generate an a list comprehension, the syntax is [expression(item) for item in iterable] Fore mexample:''' print([len(word) for word in Words]) print([len(word) for word in Words if len(word)>3]) #This...
# HomeWork_3 # Maayan Nadivi - 208207068 # Alice Aidlin - 208448326 def main(): A = [[4, 2, 0], [2, 10, 4], [0, 4, 5]] b = [[2], [6], [5]] choise = int(input('Select the desired iterative method:\n1.Jacobi\n2.Gaus Zaidl\n')) if choise == 1: Jacobi(A, b) main() elif choise == 2: ...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def _init_(self, data): self.head = Node(data) def append(self, data): cur = self.head while cur.next is not None: cur = cur.next cur.next = Node(data) ...
def myfun(): print("welcome to my calc") a = int(input("enter first num:")) b = int(input("enter second num:")) print("1. Sum \n2. Multi \n3. Div \n4. sub") choice = int(input("Select your choice: ")) if choice == 1: print(a + b) elif choice == 2: print(a * b) elif ch...
# binary tree # https://www.interviewbit.com/problems/max-depth-of-binary-tree/ # Time: O(nodes) # Space: O(max-depth) # Find max depth of binary tree # Uses two stacks instead of recursion # http://stackoverflow.com/a/19914505/3542151 def max_depth_nr(root): depth = 0 path, explore = [], [root] ...
# binary tree, recursion # https://www.interviewbit.com/problems/sorted-array-to-balanced-bst/ # Time: O(n) # Space: O(log n) # Construct balanced binary tree form sorted array def btree_from_sorted_array(array, start = 0, end = None): if end is None: end = len(array) if end == start: return None ...
class Solution: def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ solution = [] for i in range(len(numbers)): real_target = target - numbers[i] index = binary_search(numbers, i + 1, ...
''' -Hard- *DP* A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the...
''' -Easy- Given an integer array nums, find three numbers whose product is maximum and return the maximum product. Example 1: Input: nums = [1,2,3] Output: 6 Example 2: Input: nums = [1,2,3,4] Output: 24 Example 3: Input: nums = [-1,-2,-3] Output: -6 Constraints: 3 <= nums.length <= 10^4 -1000 <= nums[i] ...
''' -Medium- Given a binary tree, find the subtree with maximum average. Return the root of the subtree. LintCode will print the subtree which root is your return node. It's guaranteed that there is only one subtree with maximum average. 样例 Example 1 Input: {1,-5,11,1,2,4,-2} Output:11 Explanation: The tree is look...
''' -Medium- *Union Find* *BFS* Given a list of pairs of equivalent words synonyms and a sentence text, Return all possible synonymous sentences sorted lexicographically. Example 1: Input: synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]], text = "I am happy today but was sad yesterday" Output: ["I ...
''' -Medium- *Sweep Line* You are given a 0-indexed array nums and a non-negative integer k. In one operation, you can do the following: Choose an index i that hasn't been chosen before from the range [0, nums.length - 1]. Replace nums[i] with any integer from the range [nums[i] - k, nums[i] + k]. The beauty of the...
''' -Hard- *Monotonic Stack* *Prefix Max* *Suffix Min* You are given an integer array arr. We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return the largest number of chunks we can make to sort the ar...
''' -Hard- *DP* *Memoization* *Memoization with tuple* *Memoization with bitmask* You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts. You ...
''' -Medium- You have a binary tree with a small defect. There is exactly one invalid node where its right child incorrectly points to another node at the same depth but to the invalid node's right. Given the root of the binary tree with this defect, root, return the root of the binary tree after removing this inv...
''' -Medium- You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y': if the ith character is 'Y', it means that customers come at the ith hour whereas 'N' indicates that no customers come at the ith hour. If the shop closes at the jth hou...
''' -Medium- Given a string str, find the longest substring with no fewer than k repetitions and return the length. The substring can have overlapping parts, but cannot completely overlap. 1 <= str.length <= 1000 1 < k < str.length We guarantee that the problem will certainly can be solved 样例 Example 1: Input: st...
''' -Medium- *DP* Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return the numbe...
''' Given an array, rotate the array to the right by k steps, where k is non-negative. Follow up: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,...
''' -Hard- *DP* You are given an array nums consisting of positive integers and an integer k. Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k. Return the number of distinct great...
''' -Easy- Given a list of the scores of different students, items, where items[i] = [IDi, scorei] represents one score from a student with IDi, calculate each student's top five average. Return the answer as an array of pairs result, where result[j] = [IDj, topFiveAveragej] represents the student with IDj and thei...
''' Say you have an array for which the i-th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). Example 1: I...
''' -Easy- 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. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output:...
''' -Medium- Given an undirected tree, return its diameter: the number of edges in a longest path in that tree. The tree is given as an array of edges where edges[i] = [u, v] is a bidirectional edge between nodes u and v. Each node has labels in the set {0, 1, ..., edges.length}. Example 1: Input: edges = ...
''' -Medium- Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the target value. It’s not necessarily the case that t...
''' -Medium- *Sorting* Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order. If a folder[i] is located within another folder[j], it is called a sub-folder of it. The format of a path is one or more concatenated strings of the for...
''' -Medium- *Greedy* We have a two dimensional matrix A where each value is 0 or 1. A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s. After making any number of moves, every row of this matrix is interpreted as a binary number, ...
''' -Medium- *Binary Search* *Sorting* You are given two positive integer arrays nums1 and nums2, both of length n. The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). You can replace at most one element of nums1 with any other element...
''' -Medium- In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflic...
''' -Hard- A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pa...
''' -Medium- You are given an array nums of length n and an integer m. You need to determine if it is possible to split the array into n non-empty arrays by performing a series of steps. In each step, you can select an existing array (which may be the result of previous steps) with a length of at least two and split...
''' -Medium- 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). Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]] Example 2: Input: root = [1] Output: ...
''' -Medium- *Trie* 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") addW...
# -*- coding: utf-8 -*- """ Created on Fri Jun 30 00:24:20 2017 @author: merli -Medium- *Recursion* *DFS* Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1. The adding rule is: given a positive integer depth d, ...
''' Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. Example 1: Input: [[0,30],[5,10],[15,20]] Output: false Example 2: Input: [[7,10],[2,4]] Output: true NOTE: input types have been changed on April 15, 201...
''' -Medium- *BFS* *Bidirectional BFS* Chell is the protagonist of the Portal Video game series developed by Valve Corporation. One day, She fell into a maze. The maze can be thought of as an array of 2D characters of size n x m. It has 4 kinds of rooms. 'S' represents where Chell started(Only one starting point). '...
''' -Hard- The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are giv...
''' -Medium- Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: The height of the tree is height and the number of rows m should be equal to height + 1. The number...
''' -Medium- *DFS* Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to...
''' -Hard- *DP* You are given a string s containing lowercase letters and an integer k. You need to : First, change some characters of s to other lowercase English letters. Then divide s into k non-empty disjoint substrings such that each substring is a palindrome. Return the minimal number of characters that you ne...
''' -Medium- $$$ The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. Given an array find the maximum alternating subarray sum. Example: [-1,2,-1,4,7] Output is 7 Explanation: Subarray [2,-1,4] has sum 2-(-1)+4=7 Subarray [7] ...
''' -Medium- *Binary Search* On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., stations[N-1], where N = stations.length. Now, we add K more gas stations so that D, the maximum distance between adjacent gas stations, is minimized. Return the smallest possible value of D...
''' -Easy- *Rolling Hash* *Rabin Karp* *KMP* Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Subscribe to see which companies asked this question Clarification: What should we return when needle is an empty string? This is a great questio...
''' -Medium- *Monotonic Stack* Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num. Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 w...
''' -Hard- *BFS* 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 ...
''' -Medium- There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix score, where each row represents one student and score[i][j] denotes the score the ith student got in the jth exam. The matrix score contains distinct integers only. You are also given an integer k. Sort the stu...
''' Amazon is running a promotion in which customers receive prizes for purchasing a secret combination of fruits. The combination will change each day, and the team running the promotion wants to use a code list to make it easy to change the combination. The code list contains groups of fruits. Both the order of t...
''' -Medium- *Backtracking* You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1. Fo...
''' -Hard- You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can w...
''' -Easy- *Two Pointers* Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. Example 1: Input: nums = [4,2,5,...
''' -Medium- *Binary Search* Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold. Each result of divis...
''' -Medium- *DP* You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size). The size of the arra...
''' -Medium- An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty ar...
''' -Medium- Given an integer array nums and an integer k, return the number of subarrays of nums where the greatest common divisor of the subarray's elements is k. A subarray is a contiguous non-empty sequence of elements within an array. The greatest common divisor of an array is the largest integer that evenly di...
""" Given an unsorted array of integers, find the length of longest increasing subsequence. For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return t...
''' -Hard- Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region. Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-...
''' -Hard- You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: target should be formed from left to right. To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in wo...
''' -Medium- *Sorting* There are two mice and n different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index i (0-indexed) is: reward1[i] if the first mouse eats it. reward2[i] if the second mouse eats it. You are given a positive integer array reward1, a pos...
''' -Medium- *Math* Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows: Jumbo Burger: 4 tomato slices and 1 cheese slice. Small Burger: 2 Tomato slices and 1 cheese slice. Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and t...
''' -Hard- *DP* You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate. For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z'...
''' Searches for a 2D pattern in a 2D text. Assumes that both the pattern and the text are rectangles of characters. O(Mr * Nr * Nc), where Mr is the pattern row length, Nr is the text row length and Nc is the text column length ''' MOD = 10**9+7 class RabinKarp2D(object): def __init__(self, rad, pattern): ...
''' -Medium- *Prefix Sum* You are given a 2D integer array grid of size m x n, where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is on...
''' Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three. Example 1: Input: nums = [3,6,5,1,8] Output: 18 Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). Example 2: Input: nums = [4] Output: 0 E...
from collections import deque import networkx as nx import pandas as pd import matplotlib.pyplot as plt import matplotlib #matplotlib.use('TkAgg') NIL = 0 INF = float('inf') class BipGraph(object): # To add edge from u to v and v to u def addEdge(self, u, v): #Add u to v’s list. ...
''' -Easy- *Greedy* A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands: -2: turn left 90 degrees, -1: turn right 90 degrees, or 1 <= x <= 9: move forward x units Some of the grid squares are obstacles. The ith obstacle is at grid point ...
''' Given a node from a Circular Linked List which is sorted in ascending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the circular li...
''' -Easy- You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is: If x ...
""" Given an unsorted array of integers, find the length of longest increasing subsequence. For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the ...
''' -Medium- *DP* You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with th...
''' -Medium- *Dijkstra's Algorithm* You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two inte...
''' -Medium- *Sorting* In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. Example 1: Input: barcodes = [1,1,1,2,2,2] Output: [2,1,2,1,2,1] Example 2:...
''' -Hard- You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want: Chose two indices i and j, and swa...
''' -Medium- *DP* There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way. You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 t...
''' -Medium- *Binary Search* You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once. Your solution must run in O(log n) time and O(1) space. Example 1: Input: nums = ...
''' -Hard- *Union Find* You are given an integer array nums, and you can perform the following operation any number of times on nums: Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j]. Return true if...
''' -Hard- *Sliding Window* *Two Pointers* 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). For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC". Note: If there is no such window in S that covers all characters in T, return ...
''' -Hard- *DP* We are given n different types of stickers. Each sticker has a lowercase English word on it. You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have in...
''' -Medium- You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the su...
''' -Medium- *Simulation* There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol). You are also given a 0-in...
# -*- coding: utf-8 -*- """ Created on Thu Jul 06 22:08:37 2017 We are given two arrays ar1[0…m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] – x) is minimum. @author: merli """ import sys class Solution(): def closestPair(self, l1, l2, ...
""" Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note that 1 is typically treated as an ugly number. """ import heapq __author__ = 'Daniel' class...
''' -Medium- A perfectly straight street is represented by a number line. The street has street lamp(s) on it and is represented by a 2D integer array lights. Each lights[i] = [positioni, rangei] indicates that there is a street lamp at position positioni that lights up the area from [positioni - rangei, positioni...
''' -Medium- *Monotonic Stack* You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length. Return the number of steps performed until nums becomes a non-decreasing array. Example 1: Input: nums = [5,3,4,4,7,3,6,11,8,5,11] Output...
''' -Hard- *DP* *Bitmask* You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers. For example, if nums = [1, 2, 3, 4]: [2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectiv...
''' -Medium- Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. Return the two integers in any order. Example 1: Input: num = 8 Output: [3,3] Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are ...
''' -Medium- *DFS* Given a digit string, 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. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Note: Although the above answer...
''' -Medium- Given the root of a binary tree, the depth of each node is the shortest distance to the root. Return the smallest subtree such that it contains all the deepest nodes in the original tree. A node is called the deepest if it has the largest depth possible among any node in the entire tree. The subtree...
''' -Hard- *Priority Queue* 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 al...
''' -Hard- *DP* Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell. From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repe...
''' -Medium- *Difference Array* You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.) Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th t...
''' -Hard- Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system. For example, ["one", "two", "three"] represents the path "/one/two/three". Two folders (not necessarily on the sa...
''' -Medium- Given the root of a binary tree and a leaf node, reroot the tree so that the leaf is the new root. You can reroot the tree with the following steps for each node cur on the path starting from the leaf up to the root​​​ excluding the root: If cur has a left child, then that child becomes cur's right chi...
''' -Medium- You are playing a game that has n levels numbered from 0 to n - 1. You are given a 0-indexed integer array damage where damage[i] is the amount of health you will lose to complete the ith level. You are also given an integer armor. You may use your armor ability at most once during the game on any le...
''' Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". One of the benefits ...
''' -Medium- Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in an ascending order, return compute the researcher's h-index. According to the definition of h-index on Wikipedia: A scientist has an index h if h of th...
''' -Medium- *Binary Search* You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions: The sum of the grades of students in t...
''' -Medium- *Greedy* *DP* You are given a binary string s and a positive integer k. Return the length of the longest subsequence of s that makes up a binary number less than or equal to k. Note: The subsequence can contain leading zeroes. The empty string is considered to be equal to 0. A subsequence is a string ...
''' -Medium- You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1). Return true if there is a path from (0, 0) to (m - 1, n - 1) that visits an equal number of 0's and 1's. Otherwise return false. Example 1: Input: grid = ...
''' -Hard- *Greedy* *DP* You are given two 0-indexed integer arrays nums1 and nums2 of equal length. Every second, for all indices 0 <= i < nums1.length, value of nums1[i] is incremented by nums2[i]. After this is done, you can do the following operation: Choose an index 0 <= i < nums1.length and make nums1[i] = 0. ...
''' -Medium- Yash is a student at MIT and has to do a lot of work. He has finished k homeworks and the deadlines of these homeworks lie between 0 to 𝑘^2 - 1. Help Yash sort these homeworks in non-decreasing order of deadlines with expected time and space complexity O(k). Input: k = 5, homeworks = [13, 24, 1, 17,...