title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
[0ms][1LINER][100%][Fastest Solution Explained] O(n)time complexity O(n)space complexity
range-sum-query-immutable
1
1
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, ***please upvote*** this post.)\n***Take care brother, peace, love!***\n\n```\n```\n\nThe best result for the code below is ***0ms / 38.2MB*** (beats 92.04% / 24.00%).\n* *** Java ***\n\n```\n\n/**\n * Using ...
9
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * ...
null
Beats 99.93% of the python users
range-sum-query-immutable
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can use a prefix sum array for this problem.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity of building the prefix_array is $$O(n)$$ but you\'ll get your answer for sumRange(...
4
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * ...
null
Easiest PYTHON solution
range-sum-query-immutable
0
1
\n```\nclass NumArray:\n\n def __init__(self, nums: List[int]):\n self.nums = nums\n\n def sumRange(self, left: int, right: int) -> int:\n return sum(self.nums[left:right+1])\n\n\n# Your NumArray object will be instantiated and called as such:\n# obj = NumArray(nums)\n# param_1 = obj.sumRange(left,r...
8
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * ...
null
presum list python3
range-sum-query-immutable
0
1
Construct the instance takes O(N), but the sumRange is O(1), given that sumRange would be called multiple times, it is worth it to pre-calculated the presum list. The first element is zero becuase the sum before the 0 index num is zero,\n```\nclass NumArray:\n\n def __init__(self, nums: List[int]):\n accu_sum...
2
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * ...
null
efficient python3
range-sum-query-2d-immutable
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initial...
null
Python Easy with explanation ✅
range-sum-query-2d-immutable
0
1
For this, we first need to calculate the **prefix sum array** for the matrix.\n\nSomething like this :\n\n**Prefix Sum of matrix with each cell=1**\n\n<img src="https://assets.leetcode.com/users/images/14109f49-e7ae-4e53-bc53-148e5f60877c_1654215908.2260733.png" width=200/>\n\n\nNow, let\'s say we want to find the sum ...
78
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initial...
null
prefix sum: from array to matrix
range-sum-query-2d-immutable
0
1
# Intuition\nIt\'s derived from the same method of prefix sum in arrays: adding up [0]~[i-1], save the result in preSum[i]\n\n# Approach\nIn a matrix, the additional dimension makes it more complex to define or calculate the prefix sum than working on an array.\nLet\'s start with this intuitive definition:\nSay, $$preS...
1
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initial...
null
304: Solution with step by step explanation
range-sum-query-2d-immutable
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThis problem can be solved using dynamic programming by precomputing the sum of all elements in a submatrix with the top left corner at (0, 0) and the bottom right corner at (i, j). Then, to calculate the sum of a submatrix with the top...
4
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initial...
null
✔️ PYTHON || ✔️ EXPLAINED || ; ]
range-sum-query-2d-immutable
0
1
Instead of traversing an array everytime to find the sum on O ( N ) , we use prefix sum.\n\n**PREFIX SUM**\nIn a single traversal of array we apply the operation :\n**a [ i ] += a [ i - 1 ]**\nSo whenever the sum between index **i** and **j** is to be found, we just find **a [ i ] - a [ j ]** ( i<j ) HENCE **O ( 1 )**\...
23
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initial...
null
O(1) time | O(1) space | solution explained
range-sum-query-2d-immutable
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe sum of the elements in a rectangular matrix is an overlap of four other rectangular matrices that originate at the matrix[0][0]\n\n**rectangle sum = whole sum - top rectangle sum - left rectangle sum + top-left rectangle sum**\nsum(r1...
1
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initial...
null
306: Time 95%, Solution with step by step explanation
additive-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis solution works by checking all possible combinations of the first two numbers, and then iterating through the rest of the string to check if it forms a valid additive sequence. We start by iterating over all possible po...
9
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
Backtracking
additive-number
0
1
```\nclass Solution:\n def isAdditiveNumber(self, num: str) -> bool:\n self.ans = False\n\n def get_number(num_str):\n return int(num_str)\n\n def fun(num_list, num_index_list, valid_so_far, index):\n #print(f\'num_list={num_list}, num_index_list={num_index_list}, index={in...
0
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
Very Simple Solution -Back Tracking(O(2**n))
additive-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
Python Recursive Solution
additive-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
Please help me understand my code
additive-number
0
1
I don\'t know how this works\n\n# Code\n```\nclass Solution:\n def isAdditiveNumber(self, num: str) -> bool:\n def is_valid(start_point, a, b):\n # print("recurs",start_point,"previous",a,b)\n if start_point==len(num):\n # print("done!")\n return True\n ...
0
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
Python (Simple Backtracking)
additive-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
python: backtracking
additive-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
Solution
additive-number
1
1
```C++ []\nclass Solution {\npublic:\n bool isAdditiveNumber(string num) {\n for (int i = 1; i < num.length(); ++i) {\n for (int j = i + 1; j < num.length(); ++j) {\n string s1 = num.substr(0, i), s2 = num.substr(i, j - i);\n if ((s1.length() > 1 && s1[0] == \'0\') ||\...
0
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
Clear Python Solution with Comments
additive-number
0
1
# Code\n```\nclass Solution:\n def isAdditiveNumber(self, num: str) -> bool:\n # remaining - string; pre_sum - int; pre_num - int\n def validate(remaining, pre_sum, pre_num):\n if len(remaining) == 0:\n return True\n if not remaining.startswith(str(pre_sum)):\n ...
0
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true...
null
Using Segmented tree with explanation easy to understand
range-sum-query-mutable
0
1
```\n# Segment tree node\nclass Node(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.total = 0\n self.left = None\n self.right = None\n\n\nclass NumArray(object):\n\n def __init__(self, nums):\n # helper function to create the tree ...
18
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initi...
null
307: Space 98.30%, Solution with step by step explanation
range-sum-query-mutable
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n- The NumArray class is initialized with the input array nums. In the __init__ method, we initialize a binary tree (segment tree) to store the range sum queries for the array.\n- The buildTree method is used to build the b...
5
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initi...
null
Python Elegant & Short | log(n) for sum | Binary Indexed/Fenwick Tree
range-sum-query-mutable
0
1
```\nclass BITTree:\n """\n Implementation of Binary Indexed Tree/Fenwick Tree\n\n Memory:\n creation - O(n)\n update - O(1)\n get_sum - O(1)\n\n Time:\n creation - O(n*log(n))\n update - O(log(n))\n get_sum - O(log(n))\n """\n\n def __init__(self, nums:...
7
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initi...
null
[Python] Binary Indexed Tree Solution || Documented
range-sum-query-mutable
0
1
Binary Indexed Tree is basically dividing the Prefix Sum algo by 2 and call recursively.\n```\n# Binary Indexed Tree implementation\nclass BIT:\n def __init__(self, size):\n self.nums = [0] * (size+1)\n def update(self, ind, val):\n while ind < len(self.nums):\n self.nums[ind] += val\n ...
1
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initi...
null
Python Easy and Best Solution | Segment Tree | Faster than 95%
range-sum-query-mutable
0
1
\tclass stree:\n\t\tdef __init__(self, arr):\n\t\t\tself.arr = [0 for i in range((len(arr))*4)]\n\t\t\tself.org = arr[:]\n\t\tdef create(self, l,r,idx):\n\t\t\tmid = (l+r)//2\n\t\t\tif l == r:\n\t\t\t\tself.arr[idx] = self.org[l]\n\t\t\t\treturn\n\t\t\tself.create(l, mid, 2*idx+1)\n\t\t\tself.create(mid+1, r, 2*idx+2)\...
1
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initi...
null
Python Solution using fenwick Tree
range-sum-query-mutable
0
1
Basic idea is to create a fenwick tree\n1. create a fenwick tree\n2. to update the value find the difference between the old and new value increment the index by 1\nrun the loop while index is less then equal to length of the nums array update the value of index as \nindex += (index & -index)\n3. to search the sum keep...
1
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initi...
null
MOST OPTIMIZED PYTHON SOLUTION
best-time-to-buy-and-sell-stock-with-cooldown
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O((N+2)*2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O((N+2)*2)$$\n<!-- Add your space com...
1
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, yo...
null
Python/Go/Java/JS/C++ O(n) by DP and state machine. [w/ Visualization]
best-time-to-buy-and-sell-stock-with-cooldown
1
1
O(n) by DP and state machine\n\n---\n\n**State Diagram**:\n\n![image](https://assets.leetcode.com/users/images/e43caa0d-25b6-4dad-904a-71a3916ac243_1596022953.885539.png)\n\n---\n\n**cool_down** denotes the max profit of current Day_i, with either do nothing, or just sell out on previous day and enter cooling on Day_i\...
121
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, yo...
null
Simple DP
best-time-to-buy-and-sell-stock-with-cooldown
0
1
No state machine, only simple DP\n\n`b[i]` is the max profit until i while last action is BUY\n`s[i]` is the max profit until i while last action is SELL\n\n# Code\n```py\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n n = len(prices)\n if n == 1: return 0\n b = [-10 ** 9] * ...
25
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, yo...
null
Python || 95.30% Faster || DP || Memoization+Tabulation
best-time-to-buy-and-sell-stock-with-cooldown
0
1
```\n#Recursion \n#Time Complexity: O(2^n)\n#Space Complexity: O(n)\nclass Solution1:\n def maxProfit(self, prices: List[int]) -> int:\n def solve(ind,buy):\n if ind>=n:\n return 0\n profit=0\n if buy==0: #buy a stock\n take=-prices[ind]+solve(ind...
5
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, yo...
null
Python 3 || 4 lines, w/ example || T/M: 94 % / 98%
best-time-to-buy-and-sell-stock-with-cooldown
0
1
```\nclass Solution:\n def maxProfit(self, prices: list[int]) -> int: # Example: prices = [1,2,3,0,2]\n #\n nostock, stock, cool = 0,-prices[0],0 # p nostock stock cool \n ...
7
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, yo...
null
Python easy Solution | Best Approch ✅
best-time-to-buy-and-sell-stock-with-cooldown
0
1
# Recursive & Memoisation\n```\nclass Solution:\n def f(self,ind,buy,n,price,dp):\n if ind>=n:\n return 0\n if dp[ind][buy]!=-1:\n return dp[ind][buy]\n \n if (buy==1):\n dp[ind][buy]=max(-price[ind]+self.f(ind+1,0,n,price,dp),0+self.f(ind+1,1,n,price,dp))...
4
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, yo...
null
True DP Solution Python O(n) 5 Lines With Explanation Full Thought Process
best-time-to-buy-and-sell-stock-with-cooldown
0
1
### I\'m going go over my complete thought process for this problem. \n\n# **Problem Requirements:**\n1. If you sell on a particular day, you must **cooldown and can\'t buy for the next day.**\n2. You can\'t sell the stock if you haven\'t bought the stock yet. \n3. You can only keep one stock.\n\n# The Drawing\n\nWe ha...
11
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, yo...
null
Python O(n) by leave node removal [w/ Visualization]
minimum-height-trees
0
1
**Hint**:\n\nUse leaves node removal procedure to find **central nodes** of graph.\n\nThose trees which are rooted in **central nodes** have minimum tree height.\n\n---\n\n**Illustration and Visualization**:\n\nIn a tree, the degree of leaf node must be 1.\n\nFor example, in this graph, **leaves nodes** are **node 1**,...
59
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edg...
How many MHTs can a graph have at most?
310: Time 96.8%, Solution with step by step explanation
minimum-height-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe can solve this problem using a BFS approach. We start by building an adjacency list of the input edges, which is a mapping between each node and its neighboring nodes. We can then perform a breadth-first search starting f...
10
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edg...
How many MHTs can a graph have at most?
Python easy to read and understand | reverse topological sort
minimum-height-trees
0
1
```\nclass Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n == 1:\n return [0]\n graph = {i:[] for i in range(n)}\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n \n leaves = []\n f...
9
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edg...
How many MHTs can a graph have at most?
Python3, O(n) with explanation
minimum-height-trees
0
1
Note the following: if the height of a tree with root x is h, then the height of the same tree with the leaves removed and with root x is h - 1.\n\nTherefore, any vertex that minimizes the height of the tree also minimizes the height of the tree minus its leaves. \n\nIn other words, if we remove all the leaves, we do ...
16
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edg...
How many MHTs can a graph have at most?
Python DFS (naive) and BFS (topological) solutions comparison [SOLVED]
minimum-height-trees
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n### Solution 1: DFS (Naive Approach)\n\nThis solution is relatively straightforward. A representation of the tree/graph is created using a hashmap. Iterating through ALL nodes, a dfs recursive search is performed on EACH node. This means each node wil...
2
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edg...
How many MHTs can a graph have at most?
✅[Python] Simple and Clean, beats 99.89%✅
minimum-height-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGiven a tree with n nodes and n-1 edges, we can select any node as the root and calculate the height of the tree with respect to that root. We want to find the root(s) that correspond to the minimum height. One way to approach this proble...
2
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edg...
How many MHTs can a graph have at most?
Python, topological sort
minimum-height-trees
0
1
```\nclass Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n <= 2:\n return [i for i in range(n)]\n \n adj = defaultdict(list)\n edge_count = defaultdict(int)\n for a, b in edges:\n adj[a].append(b)\n adj[...
1
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edg...
How many MHTs can a graph have at most?
Just Code
minimum-height-trees
1
1
```java []\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\nimport java.util.Set;\n\npublic class Solution {\n public List<Integer> findMinHeightTrees(int n, int[][] edges) {\n if (n == 1) {\n return List.of(0);\...
0
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edg...
How many MHTs can a graph have at most?
Beats 99.99% Python. Dynamic Programming, Memoization. Simple code
burst-balloons
0
1
# Intuition\nThere is a hard requirement to return the maximum possible value, and the result is path dependent. \n\nImagine the easiest test case to solve by hand, then imagine adding one element to that input.\n\nIf the last element added should be popped last, eg: $$1*1*1$$, the final result is the answer to the eas...
1
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
null
Python || 90.12% Faster || DP || Recursive->Tabulation
burst-balloons
0
1
```\n#Recursion \n#Time Complexity: O(Exponential)\n#Space Complexity: O(n)\nclass Solution1:\n def maxCoins(self, nums: List[int]) -> int:\n def solve(i,j):\n if i>j:\n return 0\n maxi=-maxsize\n for k in range(i,j+1):\n coins=nums[i-1]*nums[k]*n...
5
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
null
312: Time 90.16%, Solution with step by step explanation
burst-balloons
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe idea is to use dynamic programming to solve the problem. We define dp[i][j] as the maximum coins we can get by bursting all balloons between index i and j (exclusive). We want to compute dp[0][n-1] as the result of the o...
7
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
null
Python Solution with Explanation (both DFS and DP)
burst-balloons
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can use dfs + memorization (caching) to solve this problem. Define a function dfs(nums), which return the maximum points we can get from nums. For each element in the input array, we calculate the points of bursting it first by: `nums[...
2
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
null
PYTHON BEGINNER | Brute force recursion -> Brute-Better Memoization -> DP
burst-balloons
0
1
* dp[left][right] = coins obtained from bursting all the balloons between left and right (not including left or right)\n* dp[left][right] = max(nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right]) for i in (left+1,right)\n\n* If i is the index of the last balloon burst in (left, right), the coins that burs...
17
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
null
Dynamic Programming Solution for Bursting Balloons Problem
burst-balloons
0
1
# Intuition\nThe Burst Balloons problem involves finding the maximum coins collected by bursting balloons. My initial thought is that a dynamic programming approach could be useful here, as we need to consider the optimal strategy for bursting balloons in order to maximize the collected coins.\n\n# Approach\nTo solve t...
1
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
null
Simple Solution Using C++ , Python-3 & Java With Two Different Approaches
burst-balloons
1
1
# Approach 1\n<!-- Describe your approach to solving the problem. -->\n Top-Down\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n^3)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n^2)\n# Code\n```C++ []\nclass Solution {\n public:\n ...
2
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ...
null
313: Space 96.61%, Solution with step by step explanation
super-ugly-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nThe idea of this problem is similar to the Ugly Number II problem. We start with the smallest super ugly number, which is 1. Then, we generate each subsequent super ugly number by multiplying each prime number in the array...
5
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, ...
null
Python3 l Faster than 99.35 % | using heapq
super-ugly-number
0
1
Instead of checking the numbers one by one, here we are generating the numbers from the already available ugly numbers and keeping a count.\nFor example: primes = [2,3,5] and n = 16\nHere catch is there are multiple additions to heap like 6 = 2\\*3 and also 6 = 3\\*2\nso what we do is :\nfor 2, we find multiples of 2 l...
29
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, ...
null
heapq did the job
super-ugly-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:n\n<!-- Add your space complexity here, e.g. $$O(n)$$ ...
7
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, ...
null
python my solution
super-ugly-number
0
1
\n\n# Code\n```\nclass Solution:\n def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:\n l=[1]\n a=[0 for _ in range(len(primes))]\n for i in range(n-1):\n t=[primes[i]*l[a[i]] for i in range(len(primes))]\n m=min(t)\n for j in range(len(t)):\n ...
1
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, ...
null
Just code
super-ugly-number
1
1
```java []\nimport java.util.HashSet;\nimport java.util.PriorityQueue;\nimport java.util.Set;\n\npublic class Solution {\n public int nthSuperUglyNumber(int n, int[] primes) {\n if (n == 1) {\n return 1;\n }\n\n PriorityQueue<Long> heap = new PriorityQueue<>();\n Set<Long> seen...
0
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, ...
null
Python solution
super-ugly-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, ...
null
python: dynamic programming, 7 lines, beats 75%, clean code, easy to understand.
super-ugly-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. we created a key, value pair which the key is the primes numbers, and the value is the current quantity of the prime to try.\n2. the min value for dp[v]*k is the cu...
0
A **super ugly number** is a positive integer whose prime factors are in the array `primes`. Given an integer `n` and an array of integers `primes`, return _the_ `nth` _**super ugly number**_. The `nth` **super ugly number** is **guaranteed** to fit in a **32-bit** signed integer. **Example 1:** **Input:** n = 12, ...
null
315: Solution with step by step explanation
count-of-smaller-numbers-after-self
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 the...
null
Solution
count-of-smaller-numbers-after-self
1
1
```C++ []\nclass Solution {\n int bit[BIT_SIZE] = {0};\n \n inline void bitUpdate(int index) {\n while (index < BIT_SIZE) {\n bit[index]++;\n index += index & -index;\n }\n }\n inline int bitAns(int index) {\n int result = 0;\n while (index > 0) {\n ...
28
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 the...
null
Python3. || binSearch 6 lines, w/ explanation || T/M: 97%/84%
count-of-smaller-numbers-after-self
0
1
```\nclass Solution: # Here\'s the plan:\n # 1) Make arr, a sorted copy of the list nums.\n # 2) iterate through nums. For each element num in nums:\n # 2a) use a binary search to determine the count of elements\n # in the...
40
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 the...
null
Two solutions based on MergeSort EXPLAINED
count-of-smaller-numbers-after-self
0
1
**IDEA**: the reason that we can use merge sort to solve this problem is that merge sort always sort the array by comparing the left numbers to the right numbers. By counting how many numbers have been moved from the right half to the left half prior of the current left half number, we will know the count answer for th...
65
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 the...
null
Python || ez Binary Search (with explanation)
count-of-smaller-numbers-after-self
0
1
# Explaination\nIterate nums from index n-1 ~ 0, use bisect_left to find the insert index, and the index will be the number of the elements that smaller than the current number. \n\n# Complexity\n- Time complexity : $$O(nlog(n))$$\n- Space complexity : $$O(n)$$\n\n# Python\n```\nfrom bisect import bisect_left\nclass So...
2
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 the...
null
Merge sort solution
count-of-smaller-numbers-after-self
0
1
This method is based on the way we sort an array __descendingly__ with the merge sort method. The difference is: when we merge two descendingly sorted arrays, for the element in the left array, if it\'s larger than the first number in the right array, it means this left-array element is larger than the every element of...
18
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 the...
null
Python Solution Short Concise
count-of-smaller-numbers-after-self
0
1
```\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n arr, answer = sorted(nums), [] \n for num in nums:\n i = bisect_left(arr,num)\n answer.append(i) \n del arr[i] \n return answer \n```
2
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 the...
null
Simplest Python solution (5 lines)
count-of-smaller-numbers-after-self
0
1
\n# Code\n```\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n res = []\n for i in range(len(nums)-1,-1,-1):\n bisect.insort(res, nums[i])\n nums[i] = bisect_left(res, nums[i])\n return nums\n \n```
3
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 the...
null
POTD With 100% optimisation with 100% Runtime and Memory Acceptance
remove-duplicate-letters
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to remove duplicate letters from the input string while ensuring that the result is in lexicographically smallest order. To achieve this, we can use a stack to maintain characters and their order. We need to keep track of t...
4
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
📈Beats🧭 99.73% ✅ | 🔥Clean & Concise Code | Easy Understanding🔥
remove-duplicate-letters
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInitialize a stack (st) to store characters, two vectors (last_occurrence and used) to keep track of the last occurrence of each character and whether a character is already in the result, respectively.\n---\n\n# Approach\n<!-- Describe y...
2
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
easy solution
remove-duplicate-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
Python3 Solution
remove-duplicate-letters
0
1
\n```\nclass Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n n=len(s)\n lookup={}\n for i in range(n):\n lookup[s[i]]=i\n ans=[]\n for i in range(n):\n if s[i] not in ans:\n while ans and ans[-1]>s[i] and lookup[ans[-1]]>i:\n ...
1
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
✅ 98.53% Stack and Greedy
remove-duplicate-letters
1
1
# Interview Guide: "Remove Duplicate Letters" Problem\n\n## Problem Understanding\n\nThe "Remove Duplicate Letters" problem tasks you with removing duplicate letters from a string such that every letter appears only once. The challenge is to make sure the result is the smallest in lexicographical order among all possib...
77
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
【Video】How we think about a solution with Stack - Python, JavaScript, Java, C++
remove-duplicate-letters
1
1
Welcome to my article! This artcle starts with "How we think about a solution". In other words, that is my thought process to solve the question. This article explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope this aricle is helpful for someone.\n\n# Intuition\n\n...
41
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
Remove the Duplicate Letters Solution in Python3
remove-duplicate-letters
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s a breakdown of how the code works:\n\n1. Three data structures are initialized:\n- stack: It represents a stack data structure, which will be used to keep track of the letters in the desired order.\n- last_occurrence: It\'s a dictionary t...
1
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
Python Solution Beats 100% Users --Greedy Algorithm(Easy to Understand).
remove-duplicate-letters
0
1
# Intuition\n The goal is to remove duplicate letters from the input string while preserving their lexicographical order. This can be achieved using a systematic approach that iterates through the string, ensuring that the characters are added to the result string in the correct order.\n\n# Approach\n- Initialize an em...
5
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
316: Space 98.37%, Solution with step by step explanation
remove-duplicate-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- We create a stack to keep track of the characters that we are going to keep in the result.\n- We also create a dictionary last_occurrence to keep track of the last occurrence of each character in the string.\n- We iterate ...
10
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
Full explanation Python efficient code
remove-duplicate-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe initialize an empty stack to store characters, a dictionary last_occurrence to store the last occurrence index of each character in the string, and a set visited to keep track of characters already visited.\nWe populate the last_occurr...
2
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
[Python] Simple solution with stack
remove-duplicate-letters
0
1
```\nclass Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n ## RC ##\n\t\t## APPROACH : STACK ##\n\t\t## 100% Same Problem Leetcode 1081. Smallest Subsequence of Distinct Characters ##\n\t\t## LOGIC ##\n\t\t#\t1. We add element to the stack\n\t\t#\t2. IF we get bigger element, we just push on to...
23
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "a...
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
Python easy to understand
maximum-product-of-word-lengths
0
1
\n# Code\n```\nclass Solution:\n def maxProduct(self, words: List[str]) -> int:\n total=0\n words=list(set(words))\n for i in range(len(words)):\n for j in range(i+1,len(words)):\n ans=0\n for k in words[i]:\n if k not in words[j]:ans=l...
4
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two ...
null
318: Solution with step by step explanation
maximum-product-of-word-lengths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe solution starts by defining a nested function getMask(word: str) -> int that takes a string and returns an integer bit mask. The bit mask is computed by looping over each character in the string and setting the correspon...
4
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two ...
null
✅ Python | | Easy 3 Approaches explained
maximum-product-of-word-lengths
0
1
1. ##### **Hashset**\nThe approach is quite straightforward. We do the following:\n1. **Compute** the unique **char_set** in one iteration.\n2. **Find** all the **pairs** and **compute** the **max product** only if there are no common characters between two **char_sets**. In python, you can use `&` operator which serve...
62
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two ...
null
Python Solution || Max Product
maximum-product-of-word-lengths
0
1
\n# Complexity\n- Time complexity:\nO(n^2)\n\n\n# Code\n```\nclass Solution:\n def maxProduct(self, words: List[str]) -> int:\n mp = 0\n char_set = []\n \n for i in range(len(words)):\n char_set.append(set(words[i]))\n \n...
2
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two ...
null
What about a trie?
maximum-product-of-word-lengths
0
1
What if instead of a bit-mask, we\'ll use a trie to store all the words? But! ...before adding a new word to a trie, let\'s extract only the **unique** letters from the word (since we don\'t actually care about the count for each letter) and **sort** them alphabetically. Reason \u2013 make the trie as small as possible...
5
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two ...
null
Python Simple Solution || Brute force to Optimized code
maximum-product-of-word-lengths
0
1
**Brute force code**\n```\nclass Solution:\n def maxProduct(self, words: List[str]) -> int:\n l = []\n for i in words:\n for j in words:\n\t\t\t # creating a string with common letters\n com_str = \'\'.join(set(i).intersection(j)) \n\t\t\t\t\n\t\t\t\t# if there are no common l...
6
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two ...
null
Python, brute force O(N^2) using sets and bitmasks
maximum-product-of-word-lengths
0
1
```\nclass Solution:\n def maxProduct(self, words: List[str]) -> int:\n result = 0\n words_set = [set(word) for word in words]\n for i in range(len(words)-1):\n for j in range(i + 1, len(words)):\n if (len(words[i]) * len(words[j]) > result and\n not ...
1
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two ...
null
Easy Python Masking Solution
maximum-product-of-word-lengths
0
1
##### Amortized Analysis\n---\nTime Complexity: O(n^2) [ n is the length of words]\nSpace Complexity: O(n)\n\n---\n##### Code\n---\n\n```python\nclass Solution:\n def maxProduct(self, words: List[str]) -> int:\n words_mask = []\n for word in words:\n mask = 0\n for c in word:\n ...
1
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two ...
null
Python || math || explained
bulb-switcher
0
1
1. For the `m`th bulb, how many times will it be toggled?\nSuppose the prime factorization of `m` is `p_1^m_1 * p_2^m_2 * ... * p_k^m_k`, then the total number of factors of `m` would be `(m_1+1)*(m_2+1)*...*(m_k+1)`.\n2. If there are at least one odd number in `{m_1, ..., m_k}`, the number of factors would be even. A ...
2
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
[ C++ ] [ Python ] [Java ] [ C ] [ JavaScript ] [ One Liner ] [ Maths ]
bulb-switcher
1
1
# Code [ C++ ]\n```\nclass Solution {\npublic:\n int bulbSwitch(int n) {\n return (int)sqrt(n);\n }\n};\n```\n\n# Code [ Python ]\n```\nclass Solution:\n def bulbSwitch(self, n: int) -> int:\n return int(sqrt(n))\n```\n\n# Code [ Java ]\n```\nclass Solution {\n public int bulbSwitch(int n) {\n...
2
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Explanation and Solution
bulb-switcher
0
1
# Code\n```\nclass Solution:\n \'\'\'\n If a number toggles odd number of times it gets off we know this \n if u look at the number of factors of any number there are EVEN.\n except in one case Which is the number being ans PERFECT SQUARE\n lets say 16: 4*4 gives us only one factor thus this effect the\n...
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Simple.py
bulb-switcher
0
1
# Code\n```\nclass Solution:\n def bulbSwitch(self, n: int) -> int:\n return int(math.sqrt(n))\n```
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Python3 easy one liner with explanation || quibler7
bulb-switcher
0
1
# Code\n```\nclass Solution:\n def bulbSwitch(self, n: int) -> int:\n return isqrt(n)\n```\n\n# Approach \n\n- At Start all the bulbs are off. \n- In the first round, all bulbs are turned on. \n- In the second round, every second bulb is toggled ( if its on then turned off and if its off then turned on)\n- In...
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Python3 One Line Solution (also my first post as a newbie)
bulb-switcher
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOnly positions that are a squared number are turned on at the end, i.e. positions 1, 4, 9, 16, 25, etc.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust find the floor of square root of n\n\n# Complexity\n- Tim...
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Python shortest 1-liner. Functional programming.
bulb-switcher
0
1
# Approach\nTL;DR, Similar to [Editorial solution](https://leetcode.com/problems/bulb-switcher/editorial/).\n\n# Complexity\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution: bulbSwitch = isqrt\n```
2
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Image Explanation🏆- [Easiest to Understand - No Clickbait] - C++/Java/Python
bulb-switcher
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Bulb Switcher` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/a3e889bd-7b40-412e-8e55-5335d872acb8_1682559814.8735898.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/1fdf1dd6-5f40-40e1-967f-ca338...
122
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Explanation of factoring through "Fundamental theorem of arithmetic"
bulb-switcher
0
1
# Approach\nonly those bulbs are toggled whose indexes have an odd number of factors.\nAccording to the main theorem of arithmetic, every number can be factored into prime factors in unique way (my favorite theorem).\nExamples:\n18 -> (3,3,2)\n9 -> (3,3)\n5 -> (5)\n\nSo, how many different factors do we have (not only ...
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
SIMPLE CODE IN C LANGUAGE BEGINNER's APPROACH
bulb-switcher
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Beating 89.93% Single line Python Solution
bulb-switcher
0
1
![image.png](https://assets.leetcode.com/users/images/66c1d826-e333-4213-b143-1e0e2a062136_1682585554.847939.png)\n\n\n# Code\n```\nfrom math import floor,sqrt\nclass Solution(object):\n def bulbSwitch(self, n):\n """\n :type n: int\n :rtype: int\n """\n return int(sqrt(n))\n```
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Python Solution || One Linear || Easy to understand || Math || Sqrt
bulb-switcher
0
1
```\nfrom math import floor,sqrt\nclass Solution:\n def bulbSwitch(self, n: int) -> int:\n return floor(sqrt(n))\n```
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
319: Solution with step by step explanation
bulb-switcher
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a variable count to 0 and a variable i to 1.\n2. While i*i is less than or equal to n, increment count by 1 and increment i by 1.\n3. Return the final value of count.\n\nThe idea behind this solution is that a ...
5
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
Mathematical explanation and thought process to arrive at solution
bulb-switcher
0
1
# Approach\n\nLets begin by looking at the $i$<sup>th</sup> bulb (starting from 1). Consider how many times it has been toggled in $n$ rounds. \n\nNote that in rounds $i+1$ and after will no longer affect the $i$<sup>th</sup> bulb. \n\nYou will realise that the number of times the $i$<sup>th</sup> bulb is toggled is eq...
1
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
python3||O(1)
bulb-switcher
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, ...
2
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Retu...
null
321: Space 98.63%, Solution with step by step explanation
create-maximum-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a function called "get_max_subseq" that takes two inputs: a list of integers called "nums" and an integer "k" representing the length of the subsequence we want to extract from the list.\n2. Initialize an empty sta...
4
You are given two integer arrays `nums1` and `nums2` of lengths `m` and `n` respectively. `nums1` and `nums2` represent the digits of two numbers. You are also given an integer `k`. Create the maximum number of length `k <= m + n` from digits of the two numbers. The relative order of the digits from the same array mus...
null
Python Solution | Greedy Search + Dynamic Programming
create-maximum-number
0
1
```\nclass Solution:\n def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: \n def merge(n1, n2):\n res = []\n while (n1 or n2) :\n if n1>n2:\n res.append(n1[0])\n n1 = n1[1:]\n else:\n ...
8
You are given two integer arrays `nums1` and `nums2` of lengths `m` and `n` respectively. `nums1` and `nums2` represent the digits of two numbers. You are also given an integer `k`. Create the maximum number of length `k <= m + n` from digits of the two numbers. The relative order of the digits from the same array mus...
null
Editorial-like Solution
create-maximum-number
0
1
# Approach 1: Stack + Merge\n\n# Intuition\nWithout any good intuition for this problem, I spent some time discarding several incorrect ideas. I want to highlight what I tried and learned before arriving at the solution.\n\n### Greedy\nInitially, I explored a greedy approach using two pointers for `nums1` and `nums2`, ...
0
You are given two integer arrays `nums1` and `nums2` of lengths `m` and `n` respectively. `nums1` and `nums2` represent the digits of two numbers. You are also given an integer `k`. Create the maximum number of length `k <= m + n` from digits of the two numbers. The relative order of the digits from the same array mus...
null
greedy algorithm and merge operation
create-maximum-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. the **everymax fuction** use the greedy algorithm to create the maximum number of length **n** from a given array.\n\n it iterate through the array, maintain a stack to store the maximum number sofar. it campare each element with th...
0
You are given two integer arrays `nums1` and `nums2` of lengths `m` and `n` respectively. `nums1` and `nums2` represent the digits of two numbers. You are also given an integer `k`. Create the maximum number of length `k <= m + n` from digits of the two numbers. The relative order of the digits from the same array mus...
null