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
Simplest Greedy Python Solution | O(1) Space | O(n*k) Time
maximum-number-of-non-overlapping-palindrome-substrings
0
1
# Intuition\nIf there is a substring of size k + 2 which is a palindrome, then for sure there is a substring of size k which is a palindrome. Similarly, if there is a substring of size k + 3 which is a palindrome, then there is a substring of size k + 1 which is a palindrome.\n\n# Approach\nSo we can **greedily** start...
2
You are given a string `s` and a **positive** integer `k`. Select a set of **non-overlapping** substrings from the string `s` that satisfy the following conditions: * The **length** of each substring is **at least** `k`. * Each substring is a **palindrome**. Return _the **maximum** number of substrings in an opt...
null
Easy Brute Force solution | Python | TC = O(n^3)
number-of-unequal-triplets-in-array
0
1
```\nclass Solution:\n def unequalTriplets(self, nums: List[int]) -> int:\n c = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n for k in range(j+1, len(nums)):\n if nums[i]!=nums[j] and nums[i]!=nums[k] and nums[j] != nums[k]:\n ...
3
You are given a **0-indexed** array of positive integers `nums`. Find the number of triplets `(i, j, k)` that meet the following conditions: * `0 <= i < j < k < nums.length` * `nums[i]`, `nums[j]`, and `nums[k]` are **pairwise distinct**. * In other words, `nums[i] != nums[j]`, `nums[i] != nums[k]`, and `num...
null
Python Hashmap O(n) with diagrams
number-of-unequal-triplets-in-array
0
1
You can refer to this [video solution](https://youtu.be/d_CHEvI9gQU).\n\n\nLet\'s first try to understand the properties of the triplets.\n\n\n\n# Connected\n![image](https://assets.leetcode.com/users/images/22faf1fa-bfbb-4fd1-9754-0a80be13acfd_1668971330.2726495.png)\n\n\n\nIf we have these 3 numbers with multiple num...
31
You are given a **0-indexed** array of positive integers `nums`. Find the number of triplets `(i, j, k)` that meet the following conditions: * `0 <= i < j < k < nums.length` * `nums[i]`, `nums[j]`, and `nums[k]` are **pairwise distinct**. * In other words, `nums[i] != nums[j]`, `nums[i] != nums[k]`, and `num...
null
✅ [Python/C++/JavaScript] O(n) beats 100%
number-of-unequal-triplets-in-array
0
1
# Intuition\nCalculate the `sum of prev freq & next freq and sum them`.\n\n# Approach\n1. Iterate over frequencies.\n2. Track the sum of previous frequencies.\n3. Track the sum of next frequences.\n4. Sum them all.\n#### Example\nLet `nums = [1, 3, 1, 2, 4]`\nFrequiencies: `1: 2, 3: 1, 2: 1, 4: 1`\n```\n prev ...
16
You are given a **0-indexed** array of positive integers `nums`. Find the number of triplets `(i, j, k)` that meet the following conditions: * `0 <= i < j < k < nums.length` * `nums[i]`, `nums[j]`, and `nums[k]` are **pairwise distinct**. * In other words, `nums[i] != nums[j]`, `nums[i] != nums[k]`, and `num...
null
[ Python ] ✅✅ Simple Python Solution Using Brute Force🥳✌👍
number-of-unequal-triplets-in-array
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 1995 ms, faster than 33.33% of Python3 online submissions for Number of Unequal Triplets in Array.\n# Memory Usage: 14 MB, less than 33.33% of Python3 online submissions for Number of Unequal Triplets in Array.\n...
3
You are given a **0-indexed** array of positive integers `nums`. Find the number of triplets `(i, j, k)` that meet the following conditions: * `0 <= i < j < k < nums.length` * `nums[i]`, `nums[j]`, and `nums[k]` are **pairwise distinct**. * In other words, `nums[i] != nums[j]`, `nums[i] != nums[k]`, and `num...
null
Python easy to read and well commented
number-of-unequal-triplets-in-array
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
You are given a **0-indexed** array of positive integers `nums`. Find the number of triplets `(i, j, k)` that meet the following conditions: * `0 <= i < j < k < nums.length` * `nums[i]`, `nums[j]`, and `nums[k]` are **pairwise distinct**. * In other words, `nums[i] != nums[j]`, `nums[i] != nums[k]`, and `num...
null
Python SortedList
closest-nodes-queries-in-a-binary-search-tree
0
1
# Intuition\nSadly, the tree is unbalanced. Can\'t do bineary search directly.\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nfrom sortedcontainers import ...
1
You are given the `root` of a **binary search tree** and an array `queries` of size `n` consisting of positive integers. Find a **2D** array `answer` of size `n` where `answer[i] = [mini, maxi]`: * `mini` is the **largest** value in the tree that is smaller than or equal to `queries[i]`. If a such value does not ex...
null
Easy Solution | Python Code
closest-nodes-queries-in-a-binary-search-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGiven a BST.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use Inorder traversal to get the node values as Sorted array.\n2. Create a set of the Array.\n3. Create ans array to store result of each query.\n4. I...
1
You are given the `root` of a **binary search tree** and an array `queries` of size `n` consisting of positive integers. Find a **2D** array `answer` of size `n` where `answer[i] = [mini, maxi]`: * `mini` is the **largest** value in the tree that is smaller than or equal to `queries[i]`. If a such value does not ex...
null
My weird binary search solution
closest-nodes-queries-in-a-binary-search-tree
0
1
# Overview\nappending an inorder traversal node values to an array from a BST tree will give you a sorted list in ascending order which you can use for a binary search.\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = ...
1
You are given the `root` of a **binary search tree** and an array `queries` of size `n` consisting of positive integers. Find a **2D** array `answer` of size `n` where `answer[i] = [mini, maxi]`: * `mini` is the **largest** value in the tree that is smaller than or equal to `queries[i]`. If a such value does not ex...
null
Python | runtime beats 100% python soln
closest-nodes-queries-in-a-binary-search-tree
0
1
# Approach\n- We can first store all the node values in an array to make searching part easy that will take O(n) time we can use inorder traversal so we don\'t have to sort the array.\n- Now for each query we can use binary search for closest smaller element and closest greater element that will take O(logn) time.\n\n#...
2
You are given the `root` of a **binary search tree** and an array `queries` of size `n` consisting of positive integers. Find a **2D** array `answer` of size `n` where `answer[i] = [mini, maxi]`: * `mini` is the **largest** value in the tree that is smaller than or equal to `queries[i]`. If a such value does not ex...
null
Python3 | DFS + Binary Search Slow solution
closest-nodes-queries-in-a-binary-search-tree
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 log n + q log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space comple...
2
You are given the `root` of a **binary search tree** and an array `queries` of size `n` consisting of positive integers. Find a **2D** array `answer` of size `n` where `answer[i] = [mini, maxi]`: * `mini` is the **largest** value in the tree that is smaller than or equal to `queries[i]`. If a such value does not ex...
null
Python Solution (beats-98%, iterative inorder, bisect)
closest-nodes-queries-in-a-binary-search-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given tree is a BST so traversing it in inorder will give sorted list of node values. and then searching for result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Traverse tree in inorder and store values ...
1
You are given the `root` of a **binary search tree** and an array `queries` of size `n` consisting of positive integers. Find a **2D** array `answer` of size `n` where `answer[i] = [mini, maxi]`: * `mini` is the **largest** value in the tree that is smaller than or equal to `queries[i]`. If a such value does not ex...
null
📌📌Python3 || ⚡1895 ms, faster than 94.70% of Python3
minimum-fuel-cost-to-report-to-the-capital
0
1
![image](https://assets.leetcode.com/users/images/db6c1909-bb3b-4f52-aef0-79f4d6b937e0_1676220621.272411.png)\n\n```\ndef minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n adjacency_list = defaultdict(list)\n for a, b in roads:\n adjacency_list[a].append(b)\n adjace...
2
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
✔️ Python Optimized Solution | Explained in Detail 🔥
minimum-fuel-cost-to-report-to-the-capital
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\n**For Detailed Explaination Read this Blog:**\nhttps://www.python-techs.com/2023/02/minimum-fuel-cost-to-report-to-capital.html\n\n**Solution:**\n```\nfrom collections import defaultdict\n\nclass Solution:\n def minimumFuelCost(self, roads:...
2
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
[Python] Concise Solution || DFS
minimum-fuel-cost-to-report-to-the-capital
0
1
\n# Code\n```\nclass Solution:\n def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n def dfs(u):\n seen.add(u)\n nRep = 1 + sum(dfs(v) for v in tree[u] if v not in seen)\n ans[0] += ceil(nRep / seats) if u else 0\n return nRep\n tree, seen...
1
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
Python optimal dfs solution
minimum-fuel-cost-to-report-to-the-capital
0
1
# Complexity\n- Time complexity of dfs:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n+e) => O(n+n-1) => O(n)\n\n- Space complexity of adjacency dictionary:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(e) => O(n-1) => O(n)\n\n# Code\n```\nclass Solution:\n def minimumFuelCo...
1
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
[PYTHON] Simple Tree DFS O(N) solution
minimum-fuel-cost-to-report-to-the-capital
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\nFirst, Make tree.\nand calculate the number of representatives (In fact, this is the number of nodes)\nThe minimum number of liters of fuel for Node $n$ ($F_n$) can ...
1
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
Python, DFS
minimum-fuel-cost-to-report-to-the-capital
0
1
```\nclass Solution:\n def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n def dfs(node, parent): \n people = 1\n for child in adj[node]:\n if child != parent:\n people += dfs(child, node)\n \n ...
1
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
Python | Clean DFS
minimum-fuel-cost-to-report-to-the-capital
0
1
# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n G = defaultdict(list)\n for v, w in roads:\n G[v].append(w)\n G[w].append(v)\n ans = 0\n visited = set()\n def dfs(v):...
1
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
BFS PYTHON WELL COMMENTED CODE
minimum-fuel-cost-to-report-to-the-capital
0
1
```\nclass Solution:\n #author : @PUDDINJK\n def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n \n #graph container\n graph = defaultdict(list)\n \n #to filter out leaf nodes on the graph\n degree = [0]* (len(roads)+1)\n \n #to count nu...
1
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
Clean Codes🔥🔥|| Full Explanation✅|| DFS✅|| C++|| Java|| Python3
minimum-fuel-cost-to-report-to-the-capital
1
1
# Intuition :\n- Here we have to find the minimum fuel cost to transport people from a city (represented by node 0) to all other cities (represented by other nodes) in a road network.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach :\n- So we are using a depth-first search (DFS) algor...
138
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
[C++, Java, Python3] Simple DFS O(n)
minimum-fuel-cost-to-report-to-the-capital
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to track the number of people that reach each node and divide that by the number of seats per car, this will tell us the number of cars required to take us to the node that is closer to node`0`\n\n# Approach\nDFS\n* Imagine you ar...
171
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
Python short and clean. DFS. Functional Programming.
minimum-fuel-cost-to-report-to-the-capital
0
1
# Approach\n1. Define a function `min_cost` that given a subtree rooted at `node` computes the number of people in the subtree, say `total_people`, and the minimum fuel cost to gather them all at `node`, say `total_cost`.\n\n2. To compute the `(total_cost, total_people)` from `node`, recursively call `min_cost` on each...
2
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
Python solution
minimum-fuel-cost-to-report-to-the-capital
0
1
\n\n# Code\n```\nclass Solution:\n def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n graph=defaultdict(list)\n \n for i,j in roads:\n graph[i].append(j)\n graph[j].append(i)\n\n print(graph)\n \n \n def dfs(node,parent):\n ...
1
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
Python || Depth-First Search || Easy To Understand 🔥
minimum-fuel-cost-to-report-to-the-capital
0
1
# Code\n```\nclass Solution: \n def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n def dfs(i, prev, people = 1):\n for x in graph[i]:\n if x == prev:\n continue\n people += dfs(x, i)\n if i:\n self.an...
1
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of `n` cities numbered from `0` to `n - 1` and exactly `n - 1` roads. The capital city is city `0`. You are given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional r...
null
[C++, Python] Short DP explained
number-of-beautiful-partitions
0
1
# Intuition\nWe will have to use dynamic programming because there are overlapping subproblems. n^3 dp will fail due to time constraints. To use n^2 dp we will keep a flag `at_start` which means that the substring starts at this point and as per the question the start should be prime.\n\n# Approach\nDP\n* The DP state ...
67
You are given a string `s` that consists of the digits `'1'` to `'9'` and two integers `k` and `minLength`. A partition of `s` is called **beautiful** if: * `s` is partitioned into `k` non-intersecting substrings. * Each substring has a length of **at least** `minLength`. * Each substring starts with a **prime*...
null
[Python] Top down DP - Clean & Concise - O(N * K)
number-of-beautiful-partitions
0
1
# Intuition\nFor each position, we have 2 options:\n- Do not split on that position.\n- Split on that position if we can (`s[i]` is prime, and `s[i - 1]` is non-prime).\nNote that, after the split, we need to advance `i` by `minLength`.\n\n# Complexity\n- Time complexity: `O(N * K)`, where `N <= 1000` is length of stri...
32
You are given a string `s` that consists of the digits `'1'` to `'9'` and two integers `k` and `minLength`. A partition of `s` is called **beautiful** if: * `s` is partitioned into `k` non-intersecting substrings. * Each substring has a length of **at least** `minLength`. * Each substring starts with a **prime*...
null
Python simple DP with optimization
number-of-beautiful-partitions
0
1
\n```\nclass Solution:\n def beautifulPartitions(self, s: str, k: int, minLength: int) -> int:\n n = len(s)\n primes = [\'2\', \'3\', \'5\', \'7\']\n \n # pruning\n if k * minLength > n or s[0] not in primes or s[-1] in primes:\n return 0\n \n # posible sta...
8
You are given a string `s` that consists of the digits `'1'` to `'9'` and two integers `k` and `minLength`. A partition of `s` is called **beautiful** if: * `s` is partitioned into `k` non-intersecting substrings. * Each substring has a length of **at least** `minLength`. * Each substring starts with a **prime*...
null
Java, Python 3, C++ || Iterative 1D DP || Easy to Understand || Runtime 22ms Beats 100%
number-of-beautiful-partitions
1
1
First, we need to verify 3 special cases:\n```\nif (!isprime(s.charAt(0)) || isprime(s.charAt(s.length()-1))){return 0;}\nif (s.length()<minLength){return 0;}\nif (k==1){return 1;}\n```\nNext, we find all the indexes which can be starts of partitions (excluding 0 as 0 is a fixed one):\n```\n/* array of indexes which ca...
2
You are given a string `s` that consists of the digits `'1'` to `'9'` and two integers `k` and `minLength`. A partition of `s` is called **beautiful** if: * `s` is partitioned into `k` non-intersecting substrings. * Each substring has a length of **at least** `minLength`. * Each substring starts with a **prime*...
null
DP Approach | Commented and Explained with Example Walkthrough
number-of-beautiful-partitions
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConsider the first example provided \nInput: s = "23542185131", k = 3, minLength = 2\nOutput: 3\nExplanation: There exists three ways to create a beautiful partition:\n"2354 | 218 | 5131"\n"2354 | 21851 | 31"\n"2354218 | 51 | 31"\n\nNot v...
0
You are given a string `s` that consists of the digits `'1'` to `'9'` and two integers `k` and `minLength`. A partition of `s` is called **beautiful** if: * `s` is partitioned into `k` non-intersecting substrings. * Each substring has a length of **at least** `minLength`. * Each substring starts with a **prime*...
null
Efficient Python Solution
minimum-cuts-to-divide-a-circle
0
1
# Approach\nThe code efficiently handles the special case where n is equal to 1 and provides a concise solution for determining the number of cuts needed based on whether n is even or odd. Both time and space complexities are constant, making the algorithm efficient for any input size.\n\n# Code\n```\nclass Solution:\n...
3
A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are sho...
null
Simple Python Solution
minimum-cuts-to-divide-a-circle
0
1
```\nclass Solution(object):\n def numberOfCuts(self, n):\n if n == 1: return 0\n return n // 2 if n % 2 == 0 else n\n```\n**UpVote** Coders! Which motivates me **:)**
3
A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are sho...
null
Easy Python Solution
minimum-cuts-to-divide-a-circle
0
1
# Code\n```\nclass Solution:\n def numberOfCuts(self, n: int) -> int:\n if n==1: return 0\n return n//2 if n%2==0 else n\n```
2
A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are sho...
null
[C++|Java|Python3] parity
minimum-cuts-to-divide-a-circle
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/679b6a406693e67fb9637bbd1c8449f2372e76c5) for solutions of biweekly 92. \n\n**Intuition**\nThis is a test of parity. If it is required to have odd number of equal cuts, one has to cut it n time; otherwise, one has to cut n//2 times. \nAn edge case ...
2
A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are sho...
null
Python || 1 Line Solution || 100% Faster || Explained
minimum-cuts-to-divide-a-circle
0
1
1)if n=1 we do not need to cut the circle so, answer will be 0.\n2)if n is even then no. of valid cuts will be equal to n/2.\n3)if n is odd then no. of vaild cuts will be equal to n.\n```\nclass Solution:\n def numberOfCuts(self, n: int) -> int:\n return n if n%2 and n!=1 else n//2\n```\n\n**An upvote will be...
1
A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are sho...
null
Shortest solution in C++ and Python. Check it out!
minimum-cuts-to-divide-a-circle
0
1
\n\n# C++\n```cpp\nclass Solution {\npublic:\n int numberOfCuts(int n) {\n if(n == 1) return 0;\n return n & 1 ? n : n/2;\n }\n};\n```\n\n# Python\n```py\nclass Solution:\n def numberOfCuts(self, n: int) -> int:\n if(n == 1): return 0\n return n if n & 1 else n//2\n```
1
A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are sho...
null
Python one-liner
minimum-cuts-to-divide-a-circle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to divide n by 2 if n==1 or n is even.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1...
1
A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are sho...
null
Python || C++ || o(1) || beats 100%
minimum-cuts-to-divide-a-circle
0
1
# Complexity\n- Time complexity: $$O(1)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# C++\n```\nclass Solution {\npublic:\n int numberOfCuts(int n) {\n return (n%2 == 0 ? n/2 : n!=1 ? n : 0) ;\n \n ...
1
A **valid cut** in a circle can be: * A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or * A cut that is represented by a straight line that touches one point on the edge of the circle and its center. Some valid and invalid cuts are sho...
null
【Video】Give me 5 minutes - How we think about a solution
difference-between-ones-and-zeros-in-row-and-column
1
1
# Intuition\nCalcuate sum of 1 in each row and column at first.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/swafoNFu99o\n\n\n\u25A0 Timeline of the video\n\n`0:06` Create number of 1 in each row and column\n`1:16` How to calculate numbers at each position \n`4:03` Coding\n`6:32` Time Complexity and Space Complexity\...
50
You are given a **0-indexed** `m x n` binary matrix `grid`. A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: * Let the number of ones in the `ith` row be `onesRowi`. * Let the number of ones in the `jth` column be `onesColj`. * Let the number of zeros in the `ith` row be...
null
💯Faster✅💯🔥🔥EASY SOLUTION FOR BEGINNER FRIENDLY🔥🔥
difference-between-ones-and-zeros-in-row-and-column
1
1
# Approach\n\n1. Iterate through each element in the input grid.\n2. Calculate the sum of ones and zeros in each row and column.\n3. Create a new jagged array and populate it with the differences between the counts of ones and zeros in each corresponding row and column.\n\n# Complexity\n\n- **Time complexity:** O(n * m...
13
You are given a **0-indexed** `m x n` binary matrix `grid`. A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: * Let the number of ones in the `ith` row be `onesRowi`. * Let the number of ones in the `jth` column be `onesColj`. * Let the number of zeros in the `ith` row be...
null
Lets learn Python 🐍🐍
difference-between-ones-and-zeros-in-row-and-column
0
1
\n`diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj`\n\n# Complexity\n- Time complexity: O (MN)\n\n\n``` Python []\nclass Solution:\n def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:\n def summation(nums) : \n return 2 * sum(nums) - len(nums)\n m, n = len(grid), le...
25
You are given a **0-indexed** `m x n` binary matrix `grid`. A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: * Let the number of ones in the `ith` row be `onesRowi`. * Let the number of ones in the `jth` column be `onesColj`. * Let the number of zeros in the `ith` row be...
null
Easy data preprocessing optimized solution!
difference-between-ones-and-zeros-in-row-and-column
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* To keep track of how many 1s are in each row and column, use arrays: one array for each row and another array for each column. \n* Now, we can quickly determine how ...
3
You are given a **0-indexed** `m x n` binary matrix `grid`. A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: * Let the number of ones in the `ith` row be `onesRowi`. * Let the number of ones in the `jth` column be `onesColj`. * Let the number of zeros in the `ith` row be...
null
✅☑[C++/Java/Python/JavaScript] || Easy Approach || EXPLAINED🔥
difference-between-ones-and-zeros-in-row-and-column
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n(***For more optimized code use dynamic memory allocation***)\n\n1. **Variable Declarations:**\n\n - `row` and `col`: Store the number of rows and columns in the grid.\n - `diff`: A matrix initialized with the size of `row`...
7
You are given a **0-indexed** `m x n` binary matrix `grid`. A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: * Let the number of ones in the `ith` row be `onesRowi`. * Let the number of ones in the `jth` column be `onesColj`. * Let the number of zeros in the `ith` row be...
null
EASIEST SOLUTION WITH TLE OPTIMIZATION
difference-between-ones-and-zeros-in-row-and-column
0
1
# Intuition\n To optimize the solution and avoid Time Limit Exceeded (TLE), you can precompute the sums for rows and columns separately before calculating the difference matrix. This way, you avoid recalculating the sums for each element in the grid.\n\n\n\n# Code\n```\nclass Solution:\n def onesMinusZeros(self, gri...
1
You are given a **0-indexed** `m x n` binary matrix `grid`. A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: * Let the number of ones in the `ith` row be `onesRowi`. * Let the number of ones in the `jth` column be `onesColj`. * Let the number of zeros in the `ith` row be...
null
Solving from a brute force base case to an efficient solution
difference-between-ones-and-zeros-in-row-and-column
0
1
# Intuition\n\nBase case- for a given cell we need the row and we need the column. \n\nSecond look- For each row in the data we will need the column computed many times, so let\'s pre-compute all of the rows. \n\nThird look- We are returning a matrix identical to the input matrix and we aren\'t re-iterating over cells ...
1
You are given a **0-indexed** `m x n` binary matrix `grid`. A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: * Let the number of ones in the `ith` row be `onesRowi`. * Let the number of ones in the `jth` column be `onesColj`. * Let the number of zeros in the `ith` row be...
null
✔Beats 100% || 🔥Mind Blowing Technique || 🔥With Picture || Detail explanations
minimum-penalty-for-a-shop
1
1
![image.png](https://assets.leetcode.com/users/images/a39896fb-646d-4011-be64-f8c865a1bad9_1693274817.5841289.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n> For every hour when the shop is open and no customers come, the penalty increases by 1.\nFor every hour when the shop ...
7
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 a...
null
【Video】Time : O(n) Space: O(1) with Python, JavaScript, Java and C++
minimum-penalty-for-a-shop
1
1
# Intuition\nThe main point of this code is to determine the best closing time for a shop based on customer visit records. It calculates the optimal time to close the shop such that if there are any customers inside, the shop closes at the next hour. The code iterates through the customer records, maintaining a counter...
21
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 a...
null
✅ 99.70% 2-Approach Single Pass & Prefix Sum
minimum-penalty-for-a-shop
1
1
# Interview Guide: Minimum Penalty for a Shop\n\n## Problem Understanding\n\n**Description**: \nSo, you\'re ramping up for coding interviews or just looking to sharpen your algorithmic skills, right? Well, the "Minimum Penalty for a Shop" problem is a perfect starting point. Imagine owning a shop and you need to decid...
132
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 a...
null
Python Solution using prefix sum and dictionary
minimum-penalty-for-a-shop
0
1
\n# Code\n```\nclass Solution:\n def bestClosingTime(self, customers: str) -> int:\n\n d = {i : 1e9 for i in range(len(customers)+1)}\n yp = [0 for i in range(len(customers))]\n np = [0 for i in range(len(customers))]\n\n for i in range(len(customers)) :\n if customers[i] == "Y...
1
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 a...
null
Dynamic Customer Status Analysis for Optimal Closing Time
minimum-penalty-for-a-shop
0
1
# Intuition\nThe initial thoughts for solving this problem involve keeping track of the customers\' statuses (whether they are leaving or staying) and determining the optimal closing time based on the changes in these statuses.\n\n# Approach\nThe approach to solving the problem involves iterating through the customers\...
1
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 a...
null
Simple solution with using Stack DS, beats 87%/92%
minimum-penalty-for-a-shop
0
1
# Intuition\nThe task description wants from us to find **the earliest hour**, that\'ll incur **a minimum penalty**.\n\n---\n\n\nLet\'s dive and obtain some facts:\n1. `Y` and `N` can be convert to bool `1` and `0`, respectively, if at `i`- th hour there\'re at least **1 customer** or not\n2. at each hour we want to ca...
1
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 a...
null
[C++, Java, Python3] Counting Prefixes and Suffixes
count-palindromic-subsequences
1
1
# Intuition\nTo create a 5 digit palindrome we do not need to care about the middle element. We just need to find subsequence of pattern XY_YX. Calculate number of subsequences of type XY and subsequences of type YX around any given point `i` and multiply them to find number of subsequences of type XY_YX. Since string ...
148
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
[C++|Java|Python3] short DP
count-palindromic-subsequences
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/679b6a406693e67fb9637bbd1c8449f2372e76c5) for solutions of biweekly 92. \n\n**Intuition**\nIf a size 5 palindromic subsequence is given, we can check how many of it appears in s in O(N) via DP. In total, there are 100 (not 1000) relevant subsequenc...
48
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
[Python3] Counting
count-palindromic-subsequences
0
1
**Biweekly Contest 92 Submission**\n\n**Counting**\n\n**Intuition**\n\nSince 5 is an odd length each *palindromic subsequences* must have a single middle element (\'3\' in the case of "10301"). Each *palindromic subsequences* must also have an ordered pair prior to a middle element with a mirrored ordered pair after ("...
7
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
Python3 Solution with dp
count-palindromic-subsequences
0
1
\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPalindromes(self, s: str) -> int:\n res=0\n for i in range(10):\n for ...
1
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
Python
count-palindromic-subsequences
0
1
# Intuition\nGo through each bigram "ab", where a and b are digits. For bigram "ab" and for each position in string s, count how many subsequences of form "ab" there are to the left of position and how many subsequences of form "ba" there are to the right. Multiplying them will give the number of palindromes of form "a...
0
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
Counter - O(N)
count-palindromic-subsequences
0
1
# Intuition\nFor every index `i` we find `(a, b)` in `A[:i]` and `(b, a)` in `A[i + 1:]` for all `(a, b)` in `{10} X {10}`, adding `count(a, b) * count(b, a)` to the total `R`.\n\nMore formally:\n$\\sum_{i=0}^{n - 1} \\space\\space|\\{(a, b) \\in A_{[0..i - 1]}\\}| * |\\{(b, c) \\in A_{[i + 1..n - 1]}\\}| \\space\\spac...
0
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
O(10N) 99.5%
count-palindromic-subsequences
0
1
# Intuition\nWe can treat each digit in s as the middle and find the number of xy (middle) yx pairs that exist - then sum the total.\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<...
0
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
Very naive O(n) solution.
count-palindromic-subsequences
0
1
# Intuition\nThe intuition: we keep open a set of machines which look hungrily for letters. Starting out the machines have no state and will accept any letter, once they accept one letter char they take on a partial state (0, char), and will accept any letter. The next time they encounter a letter char\' they transitio...
0
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
Faster than 100%. Python implementation using numpy.
count-palindromic-subsequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe implement the prefix/suffix solution in numpy.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nWe build a running "bag" of characters:\n- `bag.singles` -- `bag.singles[n]` is the number of times n appears in t...
0
Given a string of digits `s`, return _the number of **palindromic subsequences** of_ `s` _having length_ `5`. Since the answer may be very large, return it **modulo** `109 + 7`. **Note:** * A string is **palindromic** if it reads the same forward and backward. * A **subsequence** is a string that can be derived f...
null
🔥🔥PYTHON🔥🔥 Very Easy 4 liner
find-the-pivot-integer
0
1
\n# Code\n```\nclass Solution:\n def pivotInteger(self, n: int) -> int:\n s1 = 0\n s2 = 0\n for i in range(1,n+1):\n s1 = sum(range(1, i+1))\n s2 = sum(range(i, n+1))\n if(s1==s2):\n return i\n return -1\n\n```
3
Given a positive integer `n`, find the **pivot integer** `x` such that: * The sum of all elements between `1` and `x` inclusively equals the sum of all elements between `x` and `n` inclusively. Return _the pivot integer_ `x`. If no such integer exists, return `-1`. It is guaranteed that there will be at most one pi...
null
Solution of find the pivot integer problem
find-the-pivot-integer
0
1
# Approach\n### Solved using algebraic progression\n- The sum of the members of a finite arithmetic progression is called an arithmetic series.\n- This sum can be found quickly by taking the number n of terms being added, multiplying by the sum of the first and last number in the progressio and dividing by 2\n- In this...
1
Given a positive integer `n`, find the **pivot integer** `x` such that: * The sum of all elements between `1` and `x` inclusively equals the sum of all elements between `x` and `n` inclusively. Return _the pivot integer_ `x`. If no such integer exists, return `-1`. It is guaranteed that there will be at most one pi...
null
[C++|Java|Python3] pointer
append-characters-to-string-to-make-subsequence
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/e728a9f475e5742bea7cf67ac2d1a98ab99fb206) for solutions of weekly 321. \n\n**Intuition**\nHere, we can simply check if the characters of t are sequentially present in s. If not, the length of remaining characters in t is the answer. \n**Implementat...
1
You are given two strings `s` and `t` consisting of only lowercase English letters. Return _the minimum number of characters that need to be appended to the end of_ `s` _so that_ `t` _becomes a **subsequence** of_ `s`. A **subsequence** is a string that can be derived from another string by deleting some or no charac...
null
Easy solution in python
append-characters-to-string-to-make-subsequence
0
1
class Solution:\n def appendCharacters(self, s: str, t: str) -> int:\n t=list(t)\n for i in s:\n if len(t)==0:\n return 0\n if(i==t[0]):\n t.pop(0)\n return len(t)\n```
2
You are given two strings `s` and `t` consisting of only lowercase English letters. Return _the minimum number of characters that need to be appended to the end of_ `s` _so that_ `t` _becomes a **subsequence** of_ `s`. A **subsequence** is a string that can be derived from another string by deleting some or no charac...
null
Python | Clean Code | O(n) Time and O(1) Space |
append-characters-to-string-to-make-subsequence
0
1
# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def appendCharacters(self, s: str, t: str) -> int:\n count = 0\n j = 0\n for i in s:\n if j == len(t):\n return 0\n if i == t[j]:\n j +=...
1
You are given two strings `s` and `t` consisting of only lowercase English letters. Return _the minimum number of characters that need to be appended to the end of_ `s` _so that_ `t` _becomes a **subsequence** of_ `s`. A **subsequence** is a string that can be derived from another string by deleting some or no charac...
null
[Python3] Greedy Five Lines
append-characters-to-string-to-make-subsequence
0
1
**Weekly Contest 321 Submission**\n\n**Greedy Five Lines**\n\n**Algorithm**\n1. Find the largest *subsequence* initial fragment of `t` from `s`. This can be done greedily by consistently popping the front character of `t` when iterating `s` if `c` == `t[0]`.\n2. If all characters of `t` are popped during the iteration ...
1
You are given two strings `s` and `t` consisting of only lowercase English letters. Return _the minimum number of characters that need to be appended to the end of_ `s` _so that_ `t` _becomes a **subsequence** of_ `s`. A **subsequence** is a string that can be derived from another string by deleting some or no charac...
null
[Java/Python 3] Two pointers O(n) codes w/ brief explanation and analysis.
append-characters-to-string-to-make-subsequence
1
1
\n1. Traverse `s`, if current char is same as current char of `t`, increase by 1 the pointer for `t`, `idx`.\n2. Deducting the size of `t` by `idx` is the answer.\n\n```java\n public int appendCharacters(String s, String t) {\n int idx = 0;\n for (int i = 0; i < s.length(); ++i) {\n if (idx ...
8
You are given two strings `s` and `t` consisting of only lowercase English letters. Return _the minimum number of characters that need to be appended to the end of_ `s` _so that_ `t` _becomes a **subsequence** of_ `s`. A **subsequence** is a string that can be derived from another string by deleting some or no charac...
null
Simple , compact and Recursive.
remove-nodes-from-linked-list
0
1
# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n def removeNode (head):\n if (head == No...
2
You are given the `head` of a linked list. Remove every node which has a node with a **strictly greater** value anywhere to the right side of it. Return _the_ `head` _of the modified linked list._ **Example 1:** **Input:** head = \[5,2,13,3,8\] **Output:** \[13,8\] **Explanation:** The nodes that should be removed ...
null
[Java/Python 3] 3 codes: Recursive, Iterative space O(n) and extra space O(1).
remove-nodes-from-linked-list
1
1
**Method 1: Recursive**\n\nDuring recursion to the end of the list, check if the value of current node less than that of the next one; If yes, return next node and ignore current one.\n\n```java\n public ListNode removeNodes(ListNode head) {\n if (head != null) {\n head.next = removeNodes(head.next...
26
You are given the `head` of a linked list. Remove every node which has a node with a **strictly greater** value anywhere to the right side of it. Return _the_ `head` _of the modified linked list._ **Example 1:** **Input:** head = \[5,2,13,3,8\] **Output:** \[13,8\] **Explanation:** The nodes that should be removed ...
null
Python || Recursive Code || Beats 90% Time Complexity 🔥
remove-nodes-from-linked-list
0
1
# Code\n```\nclass Solution:\n def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head is None:\n return None\n head.next = self.removeNodes(head.next)\n if head.next and head.val < head.next.val:\n return head.next\n return head\n```
1
You are given the `head` of a linked list. Remove every node which has a node with a **strictly greater** value anywhere to the right side of it. Return _the_ `head` _of the modified linked list._ **Example 1:** **Input:** head = \[5,2,13,3,8\] **Output:** \[13,8\] **Explanation:** The nodes that should be removed ...
null
Python | Easy Solution | Linked List | Arrays
remove-nodes-from-linked-list
0
1
# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n arr = []\n currMax = -99999\n while ...
1
You are given the `head` of a linked list. Remove every node which has a node with a **strictly greater** value anywhere to the right side of it. Return _the_ `head` _of the modified linked list._ **Example 1:** **Input:** head = \[5,2,13,3,8\] **Output:** \[13,8\] **Explanation:** The nodes that should be removed ...
null
Simple. Reverse the list. Tack local max.
remove-nodes-from-linked-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate in the reversed order. Track local maximum value.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Reverse the list.\n2. Iterate through the list tracking max value;\n a. If a current value less that the l...
1
You are given the `head` of a linked list. Remove every node which has a node with a **strictly greater** value anywhere to the right side of it. Return _the_ `head` _of the modified linked list._ **Example 1:** **Input:** head = \[5,2,13,3,8\] **Output:** \[13,8\] **Explanation:** The nodes that should be removed ...
null
Python || prefix sum || O(n)
count-subarrays-with-median-k
0
1
First we transform `nums` into an array of -1, 0, 1: \nn < k to -1, n == k to 0, n > k to 1.\nFor example, `nums` = [5,1,3,4,2], k = 4 -> arr = [1,-1,-1,0,-1]\n\nFor a subarray with sum equals to 0, number of {n: n < k} = number of {n: n > k}.\nFor a subarray with sum equals to 1, number of {n: n < k} = number of {n: n...
3
You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an array is the **middle** element after sorting the array in **ascending**...
null
[Python3] freq table
count-subarrays-with-median-k
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/e728a9f475e5742bea7cf67ac2d1a98ab99fb206) for solutions of weekly 321. \n\n**Intuition**\nThe subarray whose median is `k` has to include `k` itself. So we construct our subarrays starting from where `k` is located. \nWe find the index of `k` (say ...
7
You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an array is the **middle** element after sorting the array in **ascending**...
null
✅ [Python] Multiply diff counts around median | O(n) Solution w/ Explanation
count-subarrays-with-median-k
0
1
# Intuition\n**Brute Force - O(n^3)**\nYou should always start by coming up with the brute force solution. In this case, we can check every possible subarray, count the number of elements above/below the median, and check that the median exists in the subarray. As long as there are the same number of elements above/bel...
3
You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an array is the **middle** element after sorting the array in **ascending**...
null
[Java/Python 3/C++] 1 pass O(n) codes: Count the prefix sum of the balance of (greater - samller).
count-subarrays-with-median-k
1
1
**Key observation:** Within any subarray, the # of elements greater than median - the # of those less than median `= 0` or `1`.\n\nIn order to guarantee the median `k` to present in subarrays, we ONLY save into HashMap/dict the frequencies of the running balances BEFORE finding the median `k`. e.g., \n\n`nums = [7, 1, ...
49
You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an array is the **middle** element after sorting the array in **ascending**...
null
2 Sum || Prefix & Suffix || O(N)
count-subarrays-with-median-k
0
1
# Intuition\nWe can reduce this problem to a 2Sum after pre-processing \n\n# Approach\n\nlet idx be the index of k in nums\n1. find the prefix array where pre[i]= # of element > k - # of element < k in num[i:idx]\n2. find the suffix array where suf[i]= # of element > k - # of element < k in num[idx:i]\n\nif pre[i] + su...
3
You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an array is the **middle** element after sorting the array in **ascending**...
null
[Python3] Counting O(N) With Explanations
count-subarrays-with-median-k
0
1
**Hint1:** We record 1 if `num > k`; -1 if `num < k`, and 0 if `num == k`.\n\n**Hint2:** Let `pos` denote the index of `k` in `nums`, where `k` is the median. Then the problem is equivalent to:\n1. `pos` is in the indices of the subarray;\n2. the sum of the subarray is either `0` or `1`.\n\n**Hint3:** Let `c_i` be the ...
2
You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an array is the **middle** element after sorting the array in **ascending**...
null
[Python] O(n) Picture / Video Solution
count-subarrays-with-median-k
0
1
You can watch the [video](https://youtu.be/oLEKpPXUgm4) solution.\n\n# Conditions for valid subarray\n\n\n![image](https://assets.leetcode.com/users/images/86862115-3d3c-4073-8f26-12605859ce3e_1669914345.9148488.png)\n\nThe condition for a valid subarray:\n* Must include `K`\n* Difference in counts:\n\t* For **Odd leng...
4
You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an array is the **middle** element after sorting the array in **ascending**...
null
Python3 Solution With Freq Table
count-subarrays-with-median-k
0
1
\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countSubarrays(self, nums: List[int], k: int) -> int:\n idx,freq,prefix = nums.index(k), Coun...
1
You are given an array `nums` of size `n` consisting of **distinct** integers from `1` to `n` and a positive integer `k`. Return _the number of non-empty subarrays in_ `nums` _that have a **median** equal to_ `k`. **Note**: * The median of an array is the **middle** element after sorting the array in **ascending**...
null
[C++|Java|Python3] split sentence into words
circular-sentence
0
1
**C++**\n```\nclass Solution {\npublic:\n bool isCircularSentence(string sentence) {\n vector<string> words; \n istringstream iss(sentence); \n string buff; \n while (iss >> buff) words.push_back(buff); \n for (int i = 0, n = words.size(); i < n; ++i) \n if (words[i].bac...
2
A **sentence** is a list of words that are separated by a **single** space with no leading or trailing spaces. * For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Uppercase and lowercase English letters are c...
null
Python - Two Approaches
circular-sentence
0
1
Without **Split** Space `O(1`)\n```\nclass Solution:\n def isCircularSentence(self, sentence: str) -> bool:\n for i in range(len(sentence)):\n if sentence[i] == " ":\n if sentence[i-1] != sentence[i+1]:\n return False\n return sentence[0] == sentence[-1]\n``...
2
A **sentence** is a list of words that are separated by a **single** space with no leading or trailing spaces. * For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Uppercase and lowercase English letters are c...
null
Simple and Easy to Understand | Two Solutions | Python
circular-sentence
0
1
##### Solution 1:\n* *Time Complexity :* **O(N)**\n* *Space Complexity:* **O(1)**\n```\nclass Solution(object):\n def isCircularSentence(self, s):\n if s[0] != s[-1]: return False\n flag = 1\n for ch in s:\n if flag:\n if ch != \' \': last = ch\n else: fl...
9
A **sentence** is a list of words that are separated by a **single** space with no leading or trailing spaces. * For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Uppercase and lowercase English letters are c...
null
Python | Easy Solution✅
circular-sentence
0
1
# Code\u2705\n```\nclass Solution:\n def isCircularSentence(self, sentence: str) -> bool: #// sentence = "leetcode exercises sound delightful"\n sentence_list = list(sentence.split(" ")) #// sentence_list = [\'leetcode\', \'exercises\', \'sound\', \'delightful\'] \n cur...
5
A **sentence** is a list of words that are separated by a **single** space with no leading or trailing spaces. * For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Uppercase and lowercase English letters are c...
null
Python solution with split and zip
circular-sentence
0
1
\n# Code\n```python\nclass Solution:\n def isCircularSentence(self, sentence: str) -> bool:\n words = sentence.split()\n \n for prev, curr in zip(words, words[1:]):\n if prev[-1] != curr[0]:\n return False\n return words[0][0] == words[-1][-1]\n```
1
A **sentence** is a list of words that are separated by a **single** space with no leading or trailing spaces. * For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Uppercase and lowercase English letters are c...
null
Java and Python Solution
circular-sentence
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)$$ -->\no(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n...
1
A **sentence** is a list of words that are separated by a **single** space with no leading or trailing spaces. * For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Uppercase and lowercase English letters are c...
null
Python mod division to wrap around
circular-sentence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor a sentence of n words, it requires evaluation of adjacent characters $$n$$ times. \n\nSince the iteration is circular, using mod division is helpful in handling wrap around. \n\n# Approach\n<!-- Describe your approach to solving the p...
1
A **sentence** is a list of words that are separated by a **single** space with no leading or trailing spaces. * For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Uppercase and lowercase English letters are c...
null
Simple Python solution using sorting
divide-players-into-teams-of-equal-skill
0
1
\n\n# Code\n```\nclass Solution:\n def dividePlayers(self, A: List[int]) -> int:\n A.sort()\n n = len(A)\n a = [A[i]+A[n-i-1] for i in range(n//2)]\n if len(set(a)) != 1: return -1\n return sum(A[i]*A[n-i-1] for i in range(n//2)) \n```
1
You are given a positive integer array `skill` of **even** length `n` where `skill[i]` denotes the skill of the `ith` player. Divide the players into `n / 2` teams of size `2` such that the total skill of each team is **equal**. The **chemistry** of a team is equal to the **product** of the skills of the players on th...
null
simple python solution || brute force method
divide-players-into-teams-of-equal-skill
0
1
**upvote if u like the solution**\n```\n dum=0\n k=sum(skill)\n if len(skill)==2:\n return skill[0]*skill[1]\n elif len(skill)%2==0 and sum(skill)%(len(skill)/2)==0:\n ratio=k/(len(skill)/2)\n else:\n return -1\n skill.sort()\n for i in ...
1
You are given a positive integer array `skill` of **even** length `n` where `skill[i]` denotes the skill of the `ith` player. Divide the players into `n / 2` teams of size `2` such that the total skill of each team is **equal**. The **chemistry** of a team is equal to the **product** of the skills of the players on th...
null
[C++|Java|Python3] freq table
divide-players-into-teams-of-equal-skill
0
1
**C++**\n```\nclass Solution {\npublic:\n long long dividePlayers(vector<int>& skill) {\n int val = 2*accumulate(skill.begin(), skill.end(), 0) / skill.size(); \n long long ans = 0; \n unordered_map<int, int> freq; \n for (auto& x : skill) ++freq[x]; \n for (auto& [k, v] : freq) {\...
1
You are given a positive integer array `skill` of **even** length `n` where `skill[i]` denotes the skill of the `ith` player. Divide the players into `n / 2` teams of size `2` such that the total skill of each team is **equal**. The **chemistry** of a team is equal to the **product** of the skills of the players on th...
null
Simple O(N) Solution | No sorting (Two Sum Technique)
divide-players-into-teams-of-equal-skill
0
1
## Time Complexity = O(N)\n## Space Complexity = O(N)\n\n```python\nclass Solution:\n def dividePlayers(self, skill: List[int]) -> int:\n \n n = len(skill)\n t = n//2 # how many pairs will be created\n s = sum(skill) // t # what will be sum of each pair\n \n c = Counter(...
1
You are given a positive integer array `skill` of **even** length `n` where `skill[i]` denotes the skill of the `ith` player. Divide the players into `n / 2` teams of size `2` such that the total skill of each team is **equal**. The **chemistry** of a team is equal to the **product** of the skills of the players on th...
null
Python3 O(nlogn) Sorting | Easy to understand
divide-players-into-teams-of-equal-skill
0
1
# Code\n```\nclass Solution:\n def dividePlayers(self, skill: List[int]) -> int:\n n = len(skill)\n skill.sort()\n res = 0\n for i in range(0, n//2):\n if skill[i] + skill[n-i-1] != skill[0] + skill[-1]:\n return -1\n res += (skill[i] * skill[n-i-1])\n...
1
You are given a positive integer array `skill` of **even** length `n` where `skill[i]` denotes the skill of the `ith` player. Divide the players into `n / 2` teams of size `2` such that the total skill of each team is **equal**. The **chemistry** of a team is equal to the **product** of the skills of the players on th...
null
divide-players-into-teams-of-equal-skill
divide-players-into-teams-of-equal-skill
0
1
\n# Code\n```\nclass Solution:\n def dividePlayers(self, s: List[int]) -> int:\n s.sort()\n l = 0\n r = len(s)-1\n p = []\n f = []\n while l< len(s)/2:\n p.append(s[l] * s[r])\n f.append(s[l] + s[r])\n l+=1\n r-=1\n if len(s...
1
You are given a positive integer array `skill` of **even** length `n` where `skill[i]` denotes the skill of the `ith` player. Divide the players into `n / 2` teams of size `2` such that the total skill of each team is **equal**. The **chemistry** of a team is equal to the **product** of the skills of the players on th...
null
Solution using dsu beats 100% space and 100% runtime.
minimum-score-of-a-path-between-two-cities
0
1
# Intuition\nThe ans will be the minimum weight edge in component containing 1 and n.\n\n# Approach\nsimply add minimum array(let it be m) to dsu class.Where m[i] will denote minimum weight of the component i if i is parent, when we add a new edge [a,b,weight] and take i (it may be a or b decide by size) as parent node...
3
You are given a positive integer `n` representing `n` cities numbered from `1` to `n`. You are also given a **2D** array `roads` where `roads[i] = [ai, bi, distancei]` indicates that there is a **bidirectional** road between cities `ai` and `bi` with a distance equal to `distancei`. The cities graph is not necessarily ...
null
Python3 👍||⚡99/96 T/M faster beats🔥|| clean solution || simple explain ||
minimum-score-of-a-path-between-two-cities
0
1
![image.png](https://assets.leetcode.com/users/images/242a2589-17c6-4341-a8dd-8641e5a14b6c_1679467685.8966243.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nImportant tips for you : As there is at least one path between 1 and n , just find out all the edges that can be reached...
2
You are given a positive integer `n` representing `n` cities numbered from `1` to `n`. You are also given a **2D** array `roads` where `roads[i] = [ai, bi, distancei]` indicates that there is a **bidirectional** road between cities `ai` and `bi` with a distance equal to `distancei`. The cities graph is not necessarily ...
null
[C++|Python3] dfs + bfs
divide-nodes-into-the-maximum-number-of-groups
0
1
\n**Intuition**\n1) If there is a odd-length cycle, it is impossible to divide the nodes, which is checked by the DFS part; \n2) If it is possible, then we can enumerate all nodes via BFS to check for the largest number of division along each connected component, which is computed by the BFS part. \n\n**Implementation*...
16
You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`. You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is a **bidirectional** edge between nodes `ai` and `bi`. **Notice** that the given gra...
null
[Python3] BFS
divide-nodes-into-the-maximum-number-of-groups
0
1
**Implementation**\nStep 1: Find all connected components of the graph, this can be achieved by using BFS.\nStep 2: Find the maxinum number of groups in each connected component by using BFS and starting from each node of the component, or `-1` if not valid.\nStep 3: If any of the output from Step 2 is `-1`, then retur...
16
You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`. You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is a **bidirectional** edge between nodes `ai` and `bi`. **Notice** that the given gra...
null
[Python3] Memory Efficient Solution with Detailed Explanation (Easy to Understand)
divide-nodes-into-the-maximum-number-of-groups
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe graph must be bipartite in order to seperate like this. The proof is not too hard:\n\n1. No cycle: we can separate the graph and it is by definition bipartite.\n2. Cycle with odd length: (suppose we label them 1,2,...,m and start assi...
2
You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`. You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is a **bidirectional** edge between nodes `ai` and `bi`. **Notice** that the given gra...
null
Very short just BFS
divide-nodes-into-the-maximum-number-of-groups
0
1
# Intuition\nSimilar to other solutions, but just one pass of bfs on each node is sufficient (no odd cycle checking or dsu for finding components).\n\n# Code\n```\nclass Solution:\n def magnificentSets(self, n: int, edges: List[List[int]]) -> int:\n g = defaultdict(set)\n for u,v in edges:\n ...
0
You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`. You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is a **bidirectional** edge between nodes `ai` and `bi`. **Notice** that the given gra...
null
Python solution | DFS + BFS (beats 100 % of the users)
divide-nodes-into-the-maximum-number-of-groups
0
1
# Code\n```\nfrom collections import deque\n\nclass Solution:\n def magnificentSets(self, n: int, edges: List[List[int]]) -> int:\n graph = [[] for _ in range(n)]\n for u, v in edges:\n graph[u - 1].append(v - 1)\n graph[v - 1].append(u - 1)\n\n seen = [0] * n\n grou...
0
You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`. You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is a **bidirectional** edge between nodes `ai` and `bi`. **Notice** that the given gra...
null