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 |
|---|---|---|---|---|---|---|---|
[C++|Java|Python3] counter | find-consecutive-integers-from-a-data-stream | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7360be4d63ffa8b13518401baa628a6f6800d326) for solutions of weekly 95. \n\n**Intuition**\nHere we can use a counter to count the number of occurrence of `num` as of now. \n**Implementation**\n**C++**\n```\nclass DataStream {\n int value = 0, k = ... | 2 | For a stream of integers, implement a data structure that checks if the last `k` integers parsed in the stream are **equal** to `value`.
Implement the **DataStream** class:
* `DataStream(int value, int k)` Initializes the object with an empty integer stream and the two integers `value` and `k`.
* `boolean consec(... | null |
Beginner friendly Python Code | find-consecutive-integers-from-a-data-stream | 0 | 1 | # Code\n```\nclass DataStream:\n\n def __init__(self, value: int, k: int):\n self.val = value\n self.k = k\n self.i = 0\n \n\n def consec(self, num: int) -> bool:\n if(num == self.val):\n self.i += 1\n if(num != self.val):\n self.i = 0\n if((s... | 0 | For a stream of integers, implement a data structure that checks if the last `k` integers parsed in the stream are **equal** to `value`.
Implement the **DataStream** class:
* `DataStream(int value, int k)` Initializes the object with an empty integer stream and the two integers `value` and `k`.
* `boolean consec(... | null |
Python3 - O(n) | find-xor-beauty-of-array | 0 | 1 | All the numbers will get cancelled out because of XOR, except the numbers themselves.\n\nSo, XOR of the numbers will give the answer\n\n```\nclass Solution:\n def xorBeauty(self, nums: List[int]) -> int:\n\t\n s = 0\n for x in nums:\n s^=x\n return s | 3 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
Python Simple 1-liner | Simplify the Expression | Faster than 100% | find-xor-beauty-of-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTried to simplify the expression\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe key observation is that the triplets ```((nums[i] | nums[j]) & nums[k])``` occurs in pairs except when $$i=j=k$$.\n\nWhen $$i=j=k... | 1 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
[C++|Java|Python3] math | find-xor-beauty-of-array | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7360be4d63ffa8b13518401baa628a6f6800d326) for solutions of weekly 95. \n\n**Intuition**\nMath! The final answer is `(v|v) & v` where `v` is the xor of all numbers. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n int xorBeauty(vec... | 1 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
Python - one line | find-xor-beauty-of-array | 0 | 1 | # Intuition\nWhen you read it, it acutally asks to xor all elements\n\n# Approach\nWhen you read it, it acutally asks to xor all elements\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nfrom functools import reduce\nfrom operator import xor\n\nclass Solution:\n def xorBeauty(se... | 1 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
[python3] Iteration solution for reference. | find-xor-beauty-of-array | 0 | 1 | ```\nclass Solution:\n def xorBeauty(self, nums: List[int]) -> int:\n N = len(nums)\n\n OR = 0 \n for i in range(N):\n OR = OR | nums[i]\n \n for i in range(N):\n nums[i] &= OR\n \n ans = 0 \n \n for i in nums:\n ans ... | 1 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
[Python3] One Liner with Formal Proof | find-xor-beauty-of-array | 0 | 1 | # Intuition\nMany of you may get accepted during contest by guessing the answer (the bitwise XOR of all `num` in `nums`). Here we provide a formal proof.\n\n# Key Observations:\n1. Fully utilize the symmetry between `i, j, k`.\n2. `a ^ a = 0` (the property of bitwise XOR).\n\n# Proof: \n\n1. First, note that by symmetr... | 76 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
Python3 | find-xor-beauty-of-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)$$ --... | 1 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
Python 3 || 1 line, w/ explanation and example || T/M: 350 ms / 27.8 MB | find-xor-beauty-of-array | 0 | 1 | Here\'s the analysis:\n- We start with an identity:\n`A^A^B =B [Proof: `A^A^B = (A^A)^B = (0)^B = B `] \n\nHere\'s an example of how this identity works:\n `1^2^3^2^2^1 = 1^1 ^ 2^2 ^ 2 ^ 3 = 0^0^2^3 = 2^3 = 1`\n\n- In Example 1:\n```\nBeauty = (1|4)&1)^(4|1)&1) ^ (1|4)&4)^(4|1)&4) ^ (1|1)&4) ^ (4|4)&1) ^ (1|1)&1) ... | 5 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
Python | No Magic | find-xor-beauty-of-array | 0 | 1 | # Intuition\n\nI\'ll tell you what to do if you haven\'t noticed symmetries in the formula.\n\n# Approach\n\nFirst of all, contributions of different bits are independent, which is a common pattern in such questions. For each bit and each of the 8 possible combinations of bits in $$x, y, z$$, we can calculate how many ... | 7 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
Python solution beats 100% time and space complexity, it's super easy :-) | find-xor-beauty-of-array | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n* Disclaimer : This question is meduim to understand but super easy to solve. Iterate over the array once doing xor of all elements and simply return it.\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n... | 1 | You are given a **0-indexed** integer array `nums`.
The **effective value** of three indices `i`, `j`, and `k` is defined as `((nums[i] | nums[j]) & nums[k])`.
The **xor-beauty** of the array is the XORing of **the effective values of all the possible triplets** of indices `(i, j, k)` where `0 <= i, j, k < n`.
Retur... | null |
Binary Search | Python | NlogN | maximize-the-minimum-powered-city | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nkey points-\n -optimization problem\n -"at max some k"\n\nSo I thought binary search could work\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBinary search on answer, this solution is weird because we a... | 1 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
[Python3] Binary Search on the Answer and Sliding Window | maximize-the-minimum-powered-city | 0 | 1 | # Approach\nWe perform a binary search on the possible answer space by checking whether the given `target` (maximum possible minimum power) is valid or not. For each given `target`, we utilize a sliding window algorithm to check its validity in linear time.\n\n# Complexity\n- Time complexity: `O(NlogA)`, where `A` is t... | 1 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
[C++|Java|Python3] Binary search | maximize-the-minimum-powered-city | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7360be4d63ffa8b13518401baa628a6f6800d326) for solutions of weekly 95. \n\n**Intuition**\nBinary search for the desired answer. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n long long maxPower(vector<int>& stations, int r, int k... | 3 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
[C++/Python] Binary Search & Sliding Window & Greedy - Clear explanation | maximize-the-minimum-powered-city | 0 | 1 | # Intuition\n- We can see that:\n - If we **increase** the minimum power among cities, then we need **more** additional power stations (Given that we have up to `k` additional power stations).\n - If we **decrease** the minimum power among cities, then we need **less** additional power stations (Given that we have ... | 99 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
[C++||Java||Python3] Binary search + sliding window, with comment | maximize-the-minimum-powered-city | 1 | 1 | > **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n---\n\n# Intuition\n1. Notice "Maximize the Minimum", obviously binary searching on the value domain should be considered.\n2. When checking... | 16 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
Python - Binary Search - Video Solution | maximize-the-minimum-powered-city | 0 | 1 | I have explained the complete solution [here](https://youtu.be/E6aEq7V9TDk).\n\n# Intuition\nThis is a problem to maximize, so Binary Search is a candidate pattern.\nGiven an answer, we can reverse cross-check too if it is valid or not.\n\n# Logic\n**Min ans** can obviously be the min. of array\n\n**Max ans** can be `s... | 7 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
[Python 3] Work on the left bounary, binary search + line sweep | maximize-the-minimum-powered-city | 0 | 1 | If we can distribute k power stations to bring minimun power level to x, power level x - 1 is also achieveable. Intuitively, the problem can be solved by binary search of the maximum minimum power level.\n\nFirst we use a size 2 * r + 1 sliding window to find the current power level. Left and right bounds for binary se... | 2 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
Difference Array + Binary Search | maximize-the-minimum-powered-city | 0 | 1 | \n# Code\n```\nclass Solution:\n # \u5DEE\u5206:[0, |0, 0, 0|, 0] -> \u533A\u95F4\u52A0k [0, k, 0, 0, -k] -> \u524D\u7F00\u548C[0, k, k, k, 0]\u4E3A\u53D8\u5316\u540E\u7684\u6570\u7EC4\n # \u521D\u59CB\u6570\u76EE [3, 7, 11, 9, 5]: s[i] = prefix[max(n, i + r + 1)] - prefix[min(0, i - r)]\n # \u5DEE\u5206\u6570... | 0 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
[Python3] Binary Search with Sliding Window to Determine Possibility | maximize-the-minimum-powered-city | 0 | 1 | ```python\nclass Solution:\n def maxPower(self, stations: List[int], r: int, k: int) -> int:\n """We know this is a binary search problem from the start, but the\n implementation has still evaded me for a quite a while.\n\n First, we need to obtain the current power level for each station. I\n ... | 0 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
Binary search | Explanation | maximize-the-minimum-powered-city | 0 | 1 | # Intuition\n\nThere are 2 key points:\n1. We have a function `canAchieve` which determind if we can achieve **provided** minimum power by adding `k` stations. In other words we assume that we know a possible answer and try to check if it\'s true.\n2. We have a binary search from `min(stations)` to `sum(stations) + k`.... | 0 | You are given a **0-indexed** integer array `stations` of length `n`, where `stations[i]` represents the number of power stations in the `ith` city.
Each power station can provide power to every city in a fixed **range**. In other words, if the range is denoted by `r`, then a power station at city `i` can provide powe... | null |
Easy Python Solution using filter() method🚀🚀 | maximum-count-of-positive-integer-and-negative-integer | 0 | 1 | # Approach:\nThe filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. \n\nThus using filter() the code has become more easier and effective\n\n# Code\n```\nclass Solution:\n def maximumCount(self, nums: List[int]) -> int:\n l1 = list... | 2 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Python || 2 diff method || 1 line code || simple code | maximum-count-of-positive-integer-and-negative-integer | 0 | 1 | \n# Code\n# bisect method\n```\nclass Solution:\n def maximumCount(self, nums: List[int]) -> int:\n return max(bisect_left(nums,0), len(nums)-bisect_left(nums,1))\n```\n> # count approach\n```\nclass Solution:\n def maximumCount(self, nums: List[int]) -> int:\n ne = 0 \n po = 0\n for e... | 1 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Extra simple solution in Python3/TypeScript | maximum-count-of-positive-integer-and-negative-integer | 0 | 1 | # Intuition\nThe problem description is the following:\n- there\'s a list of `nums`\n- and goal is to find a maximum between count of **negative** and **positive integers**\n\n# Approach\n1. initialize `neg` and `pos`\n2. iterate over `nums`\n3. increment `pos`, if `nums[i] > 0`\n4. increment `neg`, if `nums[i] < 0`\n5... | 1 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Python3| readable solution | maximum-count-of-positive-integer-and-negative-integer | 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 an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Simple and Easy | 100% Faster Solution | C++ | Java | Python | maximum-count-of-positive-integer-and-negative-integer | 1 | 1 | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Keeping two variables for storing count of negative `\nneg` and positive `\npos\n`integers in an array.\n2. Traversing array from 0 to n-1 `\nfor(auto i:nums)\n`\n - if element is less than 0 `i < 0`\n ... | 2 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
python ONE LINE solution!!! | maximum-count-of-positive-integer-and-negative-integer | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use the filter method to create a list of negative and a list of positive numbers\n2. Compare their length.\n3. Return max length\n# Complexity\n- Time complexity:$$O(2n)$$ \n<!-- Add your time complexity here, e.g. -->\n\n- Space complexity:$$O(n)... | 0 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
с использованием фильтра | maximum-count-of-positive-integer-and-negative-integer | 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 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Python3 Simple solution || Beats 90+% ||💻🤖🧑💻 | maximum-count-of-positive-integer-and-negative-integer | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maximumCount(self, nums: List[int]) -> int:\n pos=0\n neg=0\n for i in nums:\n if i <0 :\n neg +=1\n elif i>0:\n pos+=1\n return max(pos,neg)\n \n``` | 1 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Python3 || Easy solution. | maximum-count-of-positive-integer-and-negative-integer | 0 | 1 | # Please upvote if you find the solution helpful guys!\n# Code:\n**Beats 92.46%**\n```\nclass Solution:\n def maximumCount(self, nums: List[int]) -> int:\n neg_count=0\n pos_count = 0\n for i in nums:\n if i<0:\n neg_count += 1\n elif i>0:\n po... | 1 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Python | Very easy counting solution | maximum-count-of-positive-integer-and-negative-integer | 0 | 1 | # Approach\nJust count positive and negative numbers (except zeros) in array and maximum of them \n\n# Complexity\n- Time complexity: $$O(N)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def maximumCount(self, nums: List[int]) -> int:\n pos, neg = 0, 0\n for num in nums:\n ... | 3 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
A solution that is better than 91% in speed | maximum-count-of-positive-integer-and-negative-integer | 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 an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Python3 | maximum-count-of-positive-integer-and-negative-integer | 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 an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
[C++|Java|Python3] binary search | maximum-count-of-positive-integer-and-negative-integer | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/cd738c7122f758231c4f575936d09271343de490) for solutions of weekly 327. \n\n**Intuition**\nWe binary search for the number of negative numbers and positive numbers in the array. \n\n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n in... | 44 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._
* In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`.... | null |
Easy-understanding solution! (Heap) | maximal-score-after-applying-k-operations | 0 | 1 | ```\nclass Solution:\n def maxKelements(self, nums: List[int], k: int) -> int:\n nums = [-n for n in nums]\n res = 0\n heap = heapq.heapify(nums)\n for _ in range(k):\n a = heapq.heappop(nums) * -1\n res += a\n heapq.heappush(nums, -math.ceil(a/3))\n ... | 2 | You are given a **0-indexed** integer array `nums` and an integer `k`. You have a **starting score** of `0`.
In one **operation**:
1. choose an index `i` such that `0 <= i < nums.length`,
2. increase your **score** by `nums[i]`, and
3. replace `nums[i]` with `ceil(nums[i] / 3)`.
Return _the maximum possible **sco... | null |
[Python 3] MaxHeap | maximal-score-after-applying-k-operations | 0 | 1 | ```\nclass Solution:\n def maxKelements(self, nums: List[int], k: int) -> int:\n nums = [-i for i in nums]\n heapify(nums)\n \n res = 0\n for i in range(k):\n t = -heappop(nums)\n res += t\n heappush(nums, -ceil(t / 3))\n \n return res... | 2 | You are given a **0-indexed** integer array `nums` and an integer `k`. You have a **starting score** of `0`.
In one **operation**:
1. choose an index `i` such that `0 <= i < nums.length`,
2. increase your **score** by `nums[i]`, and
3. replace `nums[i]` with `ceil(nums[i] / 3)`.
Return _the maximum possible **sco... | null |
Python solution using Max Heap | maximal-score-after-applying-k-operations | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxKelements(self, nums: List[int], k: int) -> int:\n \n heap=[-val for val in nums]\n\n heapify(heap)\n ans=0\n \n while k:\n mx=-heappop(heap)\n ans+=mx\n heappush(heap,-math.ceil(mx/3))\n k... | 1 | You are given a **0-indexed** integer array `nums` and an integer `k`. You have a **starting score** of `0`.
In one **operation**:
1. choose an index `i` such that `0 <= i < nums.length`,
2. increase your **score** by `nums[i]`, and
3. replace `nums[i]` with `ceil(nums[i] / 3)`.
Return _the maximum possible **sco... | null |
Python Solution using Priority Queue | maximal-score-after-applying-k-operations | 0 | 1 | ```\nclass Solution:\n def maxKelements(self, nums: List[int], k: int) -> int:\n score = 0\n pq = []\n for num in nums:\n heapq.heappush(pq, (-num, num))\n while k > 0:\n max_element = heapq.heappop(pq)[1]\n score += max_element\n updated_value ... | 1 | You are given a **0-indexed** integer array `nums` and an integer `k`. You have a **starting score** of `0`.
In one **operation**:
1. choose an index `i` such that `0 <= i < nums.length`,
2. increase your **score** by `nums[i]`, and
3. replace `nums[i]` with `ceil(nums[i] / 3)`.
Return _the maximum possible **sco... | null |
[Python] | Priority Queue | maximal-score-after-applying-k-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem greedily, each time taking the max number from the array. However taking the max number from an array take 0(n) time and doing this k times makes the time complexity k * 0(n) time. As this approach requires takin... | 1 | You are given a **0-indexed** integer array `nums` and an integer `k`. You have a **starting score** of `0`.
In one **operation**:
1. choose an index `i` such that `0 <= i < nums.length`,
2. increase your **score** by `nums[i]`, and
3. replace `nums[i]` with `ceil(nums[i] / 3)`.
Return _the maximum possible **sco... | null |
Python3 | Similar to 1962. Remove Stones to Minimize the Total | In-built Max Heap | maximal-score-after-applying-k-operations | 0 | 1 | This problem is similar to [1962. Remove Stones to Minimize the Total](https://leetcode.com/problems/remove-stones-to-minimize-the-total/)\n\nHere is the python3 solution using max heap.\n```\nclass Solution:\n def maxKelements(self, nums: List[int], k: int) -> int:\n heapq._heapify_max(nums)\n ans=0\n... | 1 | You are given a **0-indexed** integer array `nums` and an integer `k`. You have a **starting score** of `0`.
In one **operation**:
1. choose an index `i` such that `0 <= i < nums.length`,
2. increase your **score** by `nums[i]`, and
3. replace `nums[i]` with `ceil(nums[i] / 3)`.
Return _the maximum possible **sco... | null |
Python - Heap - Video Solution | maximal-score-after-applying-k-operations | 0 | 1 | I have explained the whole solution [here](https://youtu.be/WxtI_i3JfaM).\n\n```\nclass Solution:\n def maxKelements(self, nums: List[int], k: int) -> int:\n res = 0\n h = [-v for v in nums]\n \n heapq.heapify(h)\n \n for i in range(k):\n x = -heapq.heappop(h)\n ... | 4 | You are given a **0-indexed** integer array `nums` and an integer `k`. You have a **starting score** of `0`.
In one **operation**:
1. choose an index `i` such that `0 <= i < nums.length`,
2. increase your **score** by `nums[i]`, and
3. replace `nums[i]` with `ceil(nums[i] / 3)`.
Return _the maximum possible **sco... | null |
✅ Python3 | Brute Force | O(26 * 26) | make-number-of-distinct-characters-equal | 0 | 1 | # Approach\n**Brute Force:**\n- iterate over all possible iterations (i.e., 2 `for` loops)\n- if both the letters exists (i.e., their count != 0)\n- Swap\n- Check for Validity\n- Restore\n\n# Complexity\n- Time complexity: $$O(26*26)$$\n\n# Code\n```\nclass Solution:\n def isItPossible(self, word1: str, word2: str) ... | 1 | You are given two **0-indexed** strings `word1` and `word2`.
A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`.
Return `true` _if it is possible to get the number of distinct characters in_ `word1` _and_ `word2... | null |
[Python] Very interesting solution, take advantage of nested loops (115 ms) | make-number-of-distinct-characters-equal | 0 | 1 | We do not mess with `Counter` directly, we play with constant numbers here.\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe know swapping can have the following possible results:\n1. `word1[i] == word2[j]`\n2. `word1[i]` not in `word2`\n3. `word2[j]` not in `word1`\n4. `word1[i]`... | 3 | You are given two **0-indexed** strings `word1` and `word2`.
A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`.
Return `true` _if it is possible to get the number of distinct characters in_ `word1` _and_ `word2... | null |
✅ [Java/ C++/Python] Detailed Explanation, fully commented, Try all combs O(N+M) time | make-number-of-distinct-characters-equal | 1 | 1 | **Intution:**\nSince we can choose **any** indices from both strings to swap and at the end we just need both to have same number of distinct characters. The only thing that matters is which alphabet (\'a\',\'b\', \'c\',...) we choose from word1 and which alphabet (\'a\',\'b\', \'c\',...) we choose from word2 to swap. ... | 109 | You are given two **0-indexed** strings `word1` and `word2`.
A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`.
Return `true` _if it is possible to get the number of distinct characters in_ `word1` _and_ `word2... | null |
[C++|Java|Python3] freq table | make-number-of-distinct-characters-equal | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/cd738c7122f758231c4f575936d09271343de490) for solutions of weekly 327. \n\n**Intuition**\nWe attempt each character pair (`a`, `a`), (`a`, `b`), ..., (`z`, `z`) and see if any swap can result in equal number of unique characters. \n**Implementation... | 16 | You are given two **0-indexed** strings `word1` and `word2`.
A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`.
Return `true` _if it is possible to get the number of distinct characters in_ `word1` _and_ `word2... | null |
Python, using set operation, beats 100% time | make-number-of-distinct-characters-equal | 0 | 1 | # Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nI try to discuss how the number of character changes after the operation.\nThe time beats 100%, but it take me about an hour to cover all the cases.... So my ranking in the contest is bad :(\n\nThis might be not that efficient to cover all... | 6 | You are given two **0-indexed** strings `word1` and `word2`.
A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`.
Return `true` _if it is possible to get the number of distinct characters in_ `word1` _and_ `word2... | null |
Python3 solution | make-number-of-distinct-characters-equal | 0 | 1 | # Code\n```\nclass Solution:\n def isItPossible(self, word1: str, word2: str) -> bool:\n temp1, temp2 = [0] * 26, [0] * 26\n for i in range(len(word1)):\n temp1[ord(word1[i]) - ord(\'a\')] += 1\n for i in range(len(word2)):\n temp2[ord(word2[i]) - ord(\'a\')] += 1\n\n ... | 1 | You are given two **0-indexed** strings `word1` and `word2`.
A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`.
Return `true` _if it is possible to get the number of distinct characters in_ `word1` _and_ `word2... | null |
python3 Solution | make-number-of-distinct-characters-equal | 0 | 1 | \n```\nclass Solution:\n def isItPossible(self, word1: str, word2: str) -> bool:\n c1=collections.Counter(word1)\n c2=collections.Counter(word2)\n c1k=list(c1.keys())\n c2k=list(c2.keys())\n for x in c1k:\n for y in c2k:\n c1[y]+=1\n c1[x]-=... | 2 | You are given two **0-indexed** strings `word1` and `word2`.
A **move** consists of choosing two indices `i` and `j` such that `0 <= i < word1.length` and `0 <= j < word2.length` and swapping `word1[i]` with `word2[j]`.
Return `true` _if it is possible to get the number of distinct characters in_ `word1` _and_ `word2... | null |
[Python3] Heap-Based Simulation | time-to-cross-a-bridge | 0 | 1 | Credit to @Yawn_Sean for this incredible solution (for self-learning purpose).\n\n# Code\n```\nclass Solution:\n def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int:\n ans = 0\n left = [[-t[0]-t[2], -i] for i, t in enumerate(time)]\n right = []\n save = []\n he... | 1 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
Simulation with 3 queues (bridge left/right side and events queue) | time-to-cross-a-bridge | 0 | 1 | # Intuition/Ideas\nSimulate with 3 queues:\n- Time-series queue (based on timestamp)\n- Bridge left and right side waiting queue (based on their efficiency)\n\nDefine 4 events\n- waitL: complete putNew and join bridge left side queue\n- waitR: complete pickOld and join bridge right side queue\n- reachL: complete rightT... | 4 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
[C++|Java|Python3] simulation | time-to-cross-a-bridge | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/cd738c7122f758231c4f575936d09271343de490) for solutions of weekly 327. \n\n**Intuition**\nHere, we maintain 4 prioirty queues. \n1) `l` ready to join the queue `ll` once the time allows\n2) `ll` ready to cross the bridge from left to right \n3) `r`... | 22 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
[Python 3] Priority Queue (Heap) with Thought Process and Full Explanation | time-to-cross-a-bridge | 0 | 1 | This is a really hard and interesting problem, which took me many hours to solve. I could only get the final code (with all the conditions) after multiple attemps. The hardest part is to get all the right conditions (other posted solutions do not seem to give explanations for their conditions).\n\nMy first solution is ... | 2 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
Python simulation | time-to-cross-a-bridge | 0 | 1 | Use 2 priority queues (based on the efficiency) to simulate workers queuing on both sides of the bridge (l and r).\n\nUse 2 priority queues (based on the time) to simulate workers in the warehouses (ll and rr).\n\nFinally, t defines the time of the last crossing.\n\nWe "wait" till the bridge is available.\n- We move wo... | 8 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
[Python] Simple & Organized Heap Queue | time-to-cross-a-bridge | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nMaintain 4 minimum Heap queue to record workers at different situation:\n* Waiting at **left side** of bridge\n* Waiting at **right side** of bridge\n* **Picking** box\n* **Putting** box\n\nWorker jump amount these 4 queue as time pass.... | 1 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
[Python3] Simulate CPU Scheduler with Four Priority Queues | time-to-cross-a-bridge | 0 | 1 | ```python\nclass Solution:\n def cross(self, wait, cpu, time, tick, is_left_to_right) -> int:\n cur = heapq.heappop(wait)\n i = 0 if is_left_to_right else 2\n tick += time[-cur[2]][i]\n cur[0] = tick + time[-cur[2]][i + 1]\n heapq.heappush(cpu, cur)\n return tick\n\n def ... | 1 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
[C++ || Python] Big Simulation | time-to-cross-a-bridge | 0 | 1 | > **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n\n> **Vote welcome if this solution helped.**\n---\n\n# Intuition\n1. Notice that either answer or main logic are about the bridge, so we sh... | 2 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
Python solution using 4 priority queues | time-to-cross-a-bridge | 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\n# Code\n```\nclass Solution:\n def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int:\n # workers putting new boxes\n put_new =... | 0 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
[Python] Simulation with 4 priority queues; Explained | time-to-cross-a-bridge | 0 | 1 | We are using 4 priority queues to track the workers at four different points:\n(1) the new site on left bank of river;\n(2) the old site on right bank of river;\n(3) the left end of bridge;\n(4) the right end of bridge.\n\nqueue (1) and (2) are ordered based on the finishing time;\nqueue (3) and (4) are ordered based o... | 0 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
python simple solution | time-to-cross-a-bridge | 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 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
Simulation | Explanation | time-to-cross-a-bridge | 0 | 1 | # Intuition\n\nThere are 4 queues:\n1. Workers waiting on the left side `left_q`\n2. Workers with box waiting on the right side `right_q`\n3. Workers picking box `right_box_q`\n4. Workers putting box `left_box_q`\n\n**Waiting queues** contain tubles `(x, y)` where `x` is a worker efficiency miltipled by `-1`. Doing tha... | 0 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
Rephrasing the problem + Python O(nlogk) with descriptive comments | time-to-cross-a-bridge | 0 | 1 | # Rephrasing the Problem\nThis problem is very verbose and has some flaws in the wording. I\'ll re-explain it quickly, but I won\'t be as technical.\n\nThere are $$k$$ workers at the new warehouse and $$n$$ boxes in the old warehouse. The workers need to cross a bridge to the old warehouse, pick up a box, cross the bri... | 0 | There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`.
The warehouses are separated by a river and connected by a bridge. The old wa... | null |
Element Sum and Digit Sum in Python | difference-between-element-sum-and-digit-sum-of-an-array | 0 | 1 | # Code\n```\nclass Solution:\n def differenceOfSum(self, nums: List[int]) -> int:\n element_sum = sum(nums)\n digit_sum = 0\n for i in nums:\n for character in str(i):\n digit_sum += int(character)\n\n return abs(element_sum - digit_sum)\n``` | 1 | You are given a positive integer array `nums`.
* The **element sum** is the sum of all the elements in `nums`.
* The **digit sum** is the sum of all the digits (not necessarily distinct) that appear in `nums`.
Return _the **absolute** difference between the **element sum** and **digit sum** of_ `nums`.
**Note** ... | null |
PYTHON3 SOLUTION FOR BEGINNERS | difference-between-element-sum-and-digit-sum-of-an-array | 0 | 1 | PLEASE UPVOTE :)\n\n# Code\n```\nclass Solution:\n def differenceOfSum(self, nums: List[int]) -> int:\n sum1 = sum(nums)\n sum2 = 0\n for i in nums:\n for j in str(i):\n sum2 += int(j)\n return abs(sum1 - sum2)\n``` | 1 | You are given a positive integer array `nums`.
* The **element sum** is the sum of all the elements in `nums`.
* The **digit sum** is the sum of all the digits (not necessarily distinct) that appear in `nums`.
Return _the **absolute** difference between the **element sum** and **digit sum** of_ `nums`.
**Note** ... | null |
Python - one liner | difference-between-element-sum-and-digit-sum-of-an-array | 0 | 1 | # Complexity\n- Time complexity: O(n<sup>2</sup>)\n- Space complexity: O(n)\n\n# Code (one liner)\n```\nclass Solution:\n def differenceOfSum(self, nums: List[int]) -> int:\n return abs(sum(nums) - sum([sum([int(j) for j in list(str(i))]) for i in nums]))\n```\n# Code (expanded)\n```\nclass Solution:\n def... | 1 | You are given a positive integer array `nums`.
* The **element sum** is the sum of all the elements in `nums`.
* The **digit sum** is the sum of all the digits (not necessarily distinct) that appear in `nums`.
Return _the **absolute** difference between the **element sum** and **digit sum** of_ `nums`.
**Note** ... | null |
[C++] [Python] Brute Force Approach || Too Easy || Fully Explained | difference-between-element-sum-and-digit-sum-of-an-array | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. `digiSum(int num)`:\n - This function calculates the sum of the digits of an integer `num`.\n - It initializes a variable `sum` to 0.\n - It enters a `while` loop that continues as long as `num` is not equal to 0.\n - In each iteration, it ... | 2 | You are given a positive integer array `nums`.
* The **element sum** is the sum of all the elements in `nums`.
* The **digit sum** is the sum of all the digits (not necessarily distinct) that appear in `nums`.
Return _the **absolute** difference between the **element sum** and **digit sum** of_ `nums`.
**Note** ... | null |
Python/Python3 easy solution | difference-between-element-sum-and-digit-sum-of-an-array | 0 | 1 | \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n * log10(nums[i]))$$\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 differenceOfSum(s... | 3 | You are given a positive integer array `nums`.
* The **element sum** is the sum of all the elements in `nums`.
* The **digit sum** is the sum of all the digits (not necessarily distinct) that appear in `nums`.
Return _the **absolute** difference between the **element sum** and **digit sum** of_ `nums`.
**Note** ... | null |
Easy | Python Solution | Numpy | increment-submatrices-by-one | 0 | 1 | # Code\n```\nimport numpy as np\nclass Solution:\n def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:\n mat = [[0 for _ in range(n)] for _ in range(n)]\n mat = np.array(mat)\n for vals in queries:\n x1, x2, y1, y2 = vals[0], vals[1], vals[2], vals[3]\n ... | 11 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
PREFIX SUM APPROACH || BEATS 100% SUBMISSIONS || JAVA || INTUITIVE | increment-submatrices-by-one | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPREFIX SUM APPROACH IMPLEMENTED FOR EACH QUERY WHICH DRASTICALLY REDUCES THE TC.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBRUTE FORCE APPROACH WONT WORK FOR C++ SUNMISSIONS . SO GO AHEAD WITH THIS PREFIX SUM... | 1 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
Simple Python Solution Faster than 100% | increment-submatrices-by-one | 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 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
[Python3] Difference Array | Postfix Sum | increment-submatrices-by-one | 0 | 1 | The strategy is to keep track of the changes made to each cell at the boundaries, instead of maintaining the final value of each cell.\n\nInitially, we initialize the matrix with all zeroes. For each query, we add 1 to the top-left corner cell ($r_{start}, c_{start}$) and subtract 1 from the cells at ($r_{start}, c_{en... | 1 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
[Python🤫🐍🐍🐍] Simple Clean Hashmap Counter Solution | increment-submatrices-by-one | 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. -->\nUse a HM that tells you how much to add to the counter for each row when you reach (i,j)\nUse a second HM that tells you how much to remove from the counter when you r... | 1 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
[Python3] prefix sum | increment-submatrices-by-one | 0 | 1 | \n```\nclass Solution:\n def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:\n ans = [[0]*n for _ in range(n)]\n for i, j, ii, jj in queries: \n ans[i][j] += 1\n if ii+1 < n: ans[ii+1][j] -= 1\n if jj+1 < n: ans[i][jj+1] -= 1\n if ... | 1 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
Python3 | Prefix-Sum-Difference Array- Accepted Solutions | increment-submatrices-by-one | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing the difference array to solve the problem\n# Approach\nThe method is applying prefix sum to each row. we only need to mark the start and end position\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(... | 2 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
[Python3] Sweep Line (Range Addition w/ Visualization), Clean & Concise | increment-submatrices-by-one | 0 | 1 | # Na\xEFve Approach\nFollowing the description of this problem, for each query, we update the every element covered in the submatrix defined by `(r1, c1)` and `(r2, c2)`. However, it is pretty clear to know that the time complexity for this approach is $$O(n^2q)$$, which could be up to $$500 \\times 500 \\times 10^4 = ... | 193 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
✔ Python3 Solution | 100% faster | O(n * n) | increment-submatrices-by-one | 0 | 1 | # Complexity\n- Time complexity: $$O(n * n)$$\n- Space complexity: $$O(n * n)$$\n\n# Code\n```\nclass Solution:\n def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:\n mat = [[0] * n for _ in range(n)]\n for r1, c1, r2, c2 in queries:\n mat[r1][c1] += 1\n ... | 9 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
[Python 3] Sweep Line - Simple | increment-submatrices-by-one | 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)$$ --... | 4 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
Accepeted in Java but got TLE in C++ & Python !! | increment-submatrices-by-one | 1 | 1 | Java Brute Force Solution got accepted\n ```\nclass Solution {\n public int[][] rangeAddQueries(int n, int[][] queries) {\n int[][] mat = new int[n][n];\n for (int[] q : queries) {\n int row1 = q[0], col1 = q[1], row2 = q[2], col2 = q[3];\n for (int i = row1; i <= row2; i++) {\n for (... | 1 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
C++ and Python 70% Faster Code | Prefix Sum | Range Caching Behaviour | increment-submatrices-by-one | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nPrefix Sum\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.... | 1 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
[Python] Evolving Linear-time Sweep (3 Approaches), The Best | increment-submatrices-by-one | 0 | 1 | # Intuition\nApproach 1: Sort the queries, then for each result row scan the queries and maintain a min-heap of query right columns. This puts the solution in slowest 5%, narrowly avoiding TLE.\n\nApproach 2: Get rid of sorting and min-heap, and instead scan the queries for each row, adding $$1$$ at left column and $$-... | 1 | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... | null |
Very Short Python solution | Sliding Window | count-the-number-of-good-subarrays | 0 | 1 | ```\nclass Solution:\n def countGood(self, nums: List[int], k: int) -> int:\n res, cnt, l = 0, 0, 0\n hm = defaultdict(int)\n for r, v in enumerate(nums):\n hm[v] += 1\n cnt += hm[v] - 1\n while cnt >= k:\n hm[nums[l]] -= 1\n cnt -= ... | 1 | Given an integer array `nums` and an integer `k`, return _the number of **good** subarrays of_ `nums`.
A subarray `arr` is **good** if it there are **at least** `k` pairs of indices `(i, j)` such that `i < j` and `arr[i] == arr[j]`.
A **subarray** is a contiguous **non-empty** sequence of elements within an array.
*... | null |
detailed Intuition,concise solution and python | count-the-number-of-good-subarrays | 0 | 1 | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs my usual blogs i am partioning this blog into 3 parts\n1. prerequisites\n2. intuition\n3. code\n\n*Read as much as you want*\n#### prerequisites(optional)\n1. subsequences hold some properties which will be used in the solutio... | 3 | Given an integer array `nums` and an integer `k`, return _the number of **good** subarrays of_ `nums`.
A subarray `arr` is **good** if it there are **at least** `k` pairs of indices `(i, j)` such that `i < j` and `arr[i] == arr[j]`.
A **subarray** is a contiguous **non-empty** sequence of elements within an array.
*... | null |
Python - 2 pointers with counting | count-the-number-of-good-subarrays | 0 | 1 | # Intuition\nJust count frequency, add up pairs, when enough account to result current plus everything after (if condition is met then adding every element one by one after are also solutions), then move left pointer until rule is broken and not enough pairs.\nRepeat this till end.\n\n\n# Complexity\n- Time complexity:... | 1 | Given an integer array `nums` and an integer `k`, return _the number of **good** subarrays of_ `nums`.
A subarray `arr` is **good** if it there are **at least** `k` pairs of indices `(i, j)` such that `i < j` and `arr[i] == arr[j]`.
A **subarray** is a contiguous **non-empty** sequence of elements within an array.
*... | null |
Python 3 || 11 lines, two pointers, dict || T/M: 689 ms / 31.7 MB | count-the-number-of-good-subarrays | 0 | 1 | Here\'s the plan:\n1. We increment`right` and use a dict `d` to keep track of the count of each integer in `nums[:right+1]`.\n2. Once the number of pairs reaches`k`, we add the count of subarrays with subarray `[right+1]`to`ans`].\n3. We increment`left`and adjust`d`. If we still have`k`pairs, we add a similar count to ... | 10 | Given an integer array `nums` and an integer `k`, return _the number of **good** subarrays of_ `nums`.
A subarray `arr` is **good** if it there are **at least** `k` pairs of indices `(i, j)` such that `i < j` and `arr[i] == arr[j]`.
A **subarray** is a contiguous **non-empty** sequence of elements within an array.
*... | null |
Intuitive Sliding Window O(n) Python Solution | count-the-number-of-good-subarrays | 0 | 1 | ### Sliding Window\nEasy read on [LeetCode Weekly Contest Medium (Sliding Window) 2537. Count the Number of Good Subarrays \u2014 Hung, Chien-Hsiang | Blog (chienhsiang-hung.github.io)](https://chienhsiang-hung.github.io/blog/posts/2023/leetcode-weekly-contest-medium-sliding-window-2537.-count-the-number-of-good-subarr... | 4 | Given an integer array `nums` and an integer `k`, return _the number of **good** subarrays of_ `nums`.
A subarray `arr` is **good** if it there are **at least** `k` pairs of indices `(i, j)` such that `i < j` and `arr[i] == arr[j]`.
A **subarray** is a contiguous **non-empty** sequence of elements within an array.
*... | null |
✔ Python3 Solution | 100% faster | Sliding Window | count-the-number-of-good-subarrays | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def countGood(self, A: List[int], k: int) -> int:\n D = defaultdict(int)\n ans = cnt = l = 0\n for i in A:\n cnt += D[i]\n D[i] += 1\n while cnt >= k:\n ... | 2 | Given an integer array `nums` and an integer `k`, return _the number of **good** subarrays of_ `nums`.
A subarray `arr` is **good** if it there are **at least** `k` pairs of indices `(i, j)` such that `i < j` and `arr[i] == arr[j]`.
A **subarray** is a contiguous **non-empty** sequence of elements within an array.
*... | null |
[Python3] sliding window | count-the-number-of-good-subarrays | 0 | 1 | \n```\nclass Solution:\n def countGood(self, nums: List[int], k: int) -> int:\n freq = Counter()\n ans = ii = total = 0 \n for x in nums: \n total += freq[x]\n freq[x] += 1\n while total >= k: \n freq[nums[ii]] -= 1\n total -= freq[n... | 4 | Given an integer array `nums` and an integer `k`, return _the number of **good** subarrays of_ `nums`.
A subarray `arr` is **good** if it there are **at least** `k` pairs of indices `(i, j)` such that `i < j` and `arr[i] == arr[j]`.
A **subarray** is a contiguous **non-empty** sequence of elements within an array.
*... | null |
damn just need one more line to get AK this week 😭 | difference-between-maximum-and-minimum-price-sum | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nuse dfs to build max price of each node\ndon\'t look at my code, its too complex and not elegant\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 complexit... | 1 | There exists an undirected and initially unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Each node has an associated price. You ... | null |
[Python] 2 DFS | difference-between-maximum-and-minimum-price-sum | 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)$$ -->\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def m... | 1 | There exists an undirected and initially unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Each node has an associated price. You ... | null |
[Python3] dfs | difference-between-maximum-and-minimum-price-sum | 0 | 1 | \n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n tree = [[] for _ in range(n)]\n for u, v in edges: \n tree[u].append(v)\n tree[v].append(u)\n \n def dfs(u, p): \n """Return """\n nonlocal ... | 1 | There exists an undirected and initially unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Each node has an associated price. You ... | null |
[Python] DFS traverse, similar to the maximum path sum problem; Explained | difference-between-maximum-and-minimum-price-sum | 0 | 1 | This problem is similar to the "maximum path sum" problem.\n\nWe pick any node, and DFS traverse the graph.\n\nFor each of the visiting node, we need to get **(1) the maximum path sum with the end node value; and (2) the maximum path sum without the end value**.\n\nSee the details in code:\n\n```\nclass Solution:\n ... | 2 | There exists an undirected and initially unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Each node has an associated price. You ... | null |
Python 3 || 14 lines dfs (updated) || T/M: 90 % / 100% | difference-between-maximum-and-minimum-price-sum | 0 | 1 | My original submission was weak, and with the recently added test case, it went TLE. The comment below (thank you [@user7784J](/user7784J)) included a link from which I got the idea for a better way to approach the problem.\n\nWe assign a three-uple`state`to each node. the root and each leaf gets `(0,price,0)`, and eac... | 3 | There exists an undirected and initially unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Each node has an associated price. You ... | null |
✅ 🔥 O(n) Python3 || ⚡ solution | difference-between-maximum-and-minimum-price-sum | 0 | 1 | ```\nfrom typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n graph = defaultdict(list)\n for a, b in edges:\n graph[a].append(b)\n graph[b].append(a)\n\n def dfs(node... | 1 | There exists an undirected and initially unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Each node has an associated price. You ... | null |
Very simple DFS + DP Explained | difference-between-maximum-and-minimum-price-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAssuming any of the nodes can be root, we will check for each node.\nFor any node:\n Mininum sum= node.val (as -ve numbers are not present)\n Maximum sum= node.val + max of all the paths through children ie. Maximum Sum (child) \n\n... | 2 | There exists an undirected and initially unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Each node has an associated price. You ... | null |
✅ Explained - Simple and Clear Python3 Code✅ | minimum-common-value | 0 | 1 | # Intuition\nThe intuition behind the solution is that since the arrays are sorted in non-decreasing order, the minimum common integer must be the smallest value that appears in both arrays. Therefore, by comparing the first elements of both arrays, we can determine if they are equal, smaller in nums1, or smaller in nu... | 5 | Given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, return _the **minimum integer common** to both arrays_. If there is no common integer amongst `nums1` and `nums2`, return `-1`.
Note that an integer is said to be **common** to `nums1` and `nums2` if both arrays have **at least one** occurre... | null |
Simplest Python two-liner | minimum-common-value | 0 | 1 | # Code\n```\nclass Solution(object):\n def getCommon(self, nums1, nums2):\n st = set(nums1) & set(nums2)\n return min(st) if len(st) else -1\n```\nWe can also return a one liner solution just for fun which is basically the same code:\n```\nclass Solution(object):\n def getCommon(self, nums1, nums2):... | 1 | Given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, return _the **minimum integer common** to both arrays_. If there is no common integer amongst `nums1` and `nums2`, return `-1`.
Note that an integer is said to be **common** to `nums1` and `nums2` if both arrays have **at least one** occurre... | null |
[C++|Java|Python3] 2-pointer | minimum-common-value | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7c339707e031611c80809107e7a667b2c6b6f7f0) for solutions of biweekly 96. \n\n**C++**\n```\nclass Solution {\npublic:\n int getCommon(vector<int>& nums1, vector<int>& nums2) {\n for (int i = 0, ii = 0; i < nums1.size() && ii < nums2.size();... | 2 | Given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, return _the **minimum integer common** to both arrays_. If there is no common integer amongst `nums1` and `nums2`, return `-1`.
Note that an integer is said to be **common** to `nums1` and `nums2` if both arrays have **at least one** occurre... | null |
Python | Easy Solution✅ | minimum-common-value | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def getCommon(self, nums1: List[int], nums2: List[int]) -> int:\n nums1, nums2 = set(nums1), set(nums2)\n common = sorted(list(nums1.intersection(nums2))) # sorted(list(nums1 & nums2)) will also work\n return -1 if not len(common) else common[0]\n \n`... | 5 | Given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, return _the **minimum integer common** to both arrays_. If there is no common integer amongst `nums1` and `nums2`, return `-1`.
Note that an integer is said to be **common** to `nums1` and `nums2` if both arrays have **at least one** occurre... | null |
Python 3 || 5 lines, loop and ptr, w/ example || T/M: 98% / 95% | minimum-common-value | 0 | 1 | My first thought was`sets`, but now I see that also was true for most of you, so here\'s my second thought.\n```\nclass Solution:\n def getCommon(self, nums1: List[int], nums2: List[int]) -> int:\n\n i, len2 = 0, len(nums2) # Example: nums1 = [ 2, 4, 8, 13] \n for n1 ... | 5 | Given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, return _the **minimum integer common** to both arrays_. If there is no common integer amongst `nums1` and `nums2`, return `-1`.
Note that an integer is said to be **common** to `nums1` and `nums2` if both arrays have **at least one** occurre... | null |
Fastest beats 100% | minimum-common-value | 0 | 1 | # Upvote it :)\n```\nclass Solution:\n def getCommon(self, nums1: List[int], nums2: List[int]) -> int:\n n = set(nums1).intersection(set(nums2))\n return min(n) if n else -1\n``` | 4 | Given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, return _the **minimum integer common** to both arrays_. If there is no common integer amongst `nums1` and `nums2`, return `-1`.
Note that an integer is said to be **common** to `nums1` and `nums2` if both arrays have **at least one** occurre... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.