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 |
|---|---|---|---|---|---|---|---|
[Python] Binary search, 2-liner, 1-liner | minimum-cost-to-make-array-equal | 0 | 1 | # Intuition\nIf we try to calculate the cost of any value from min(nums) to max(nums), we see that the cost starts high, goes down to a minimum, and then goes up again. For example, for nums = `[1,3,5,2]` and cost = `[2,3,1,14]`, the cost for any value from 1 (min of nums) to 5 (max of nums) is `[24,8,20,38,56]`.\n\nTo... | 2 | You are given two **0-indexed** arrays `nums` and `cost` consisting each of `n` **positive** integers.
You can do the following operation **any** number of times:
* Increase or decrease **any** element of the array `nums` by `1`.
The cost of doing one operation on the `ith` element is `cost[i]`.
Return _the **min... | null |
Sort odd and even fully explained Python. | minimum-number-of-operations-to-make-arrays-similar | 0 | 1 | 1. Seperate tha given nums and target arrays into two i.e., nums1 and target1 for even and nums2 and target2 for odd. Because, by adding multiples of 2 to an odd number, we can only can an odd number and same goes with even one.\n\n2. Now Sort them, because then only we will find the nearest number which can be acheive... | 2 | You are given two positive integer arrays `nums` and `target`, of the same length.
In one operation, you can choose any two **distinct** indices `i` and `j` where `0 <= i, j < nums.length` and:
* set `nums[i] = nums[i] + 2` and
* set `nums[j] = nums[j] - 2`.
Two arrays are considered to be **similar** if the fre... | null |
[Python3] SortedList + Greedy O(NlogN) | minimum-number-of-operations-to-make-arrays-similar | 0 | 1 | ```\nfrom sortedcontainers import SortedList\nclass Solution:\n def makeSimilar(self, nums: List[int], target: List[int]) -> int:\n odd_nums = SortedList([num for num in nums if num % 2 == 1])\n even_nums = SortedList([num for num in nums if num % 2 == 0])\n odd_target = SortedList([num for num ... | 2 | You are given two positive integer arrays `nums` and `target`, of the same length.
In one operation, you can choose any two **distinct** indices `i` and `j` where `0 <= i, j < nums.length` and:
* set `nums[i] = nums[i] + 2` and
* set `nums[j] = nums[j] - 2`.
Two arrays are considered to be **similar** if the fre... | null |
Python | Simple Odd/Even Sorting O(nlogn) | Walmart OA India | Simple Explanation | minimum-number-of-operations-to-make-arrays-similar | 0 | 1 | ```\nclass Solution:\n def makeSimilar(self, A: List[int], B: List[int]) -> int:\n if sum(A)!=sum(B): return 0\n # The first intuition is that only odd numbers can be chaged to odd numbers and even to even hence separate them\n # Now minimum steps to making the target to highest number in B is b... | 4 | You are given two positive integer arrays `nums` and `target`, of the same length.
In one operation, you can choose any two **distinct** indices `i` and `j` where `0 <= i, j < nums.length` and:
* set `nums[i] = nums[i] + 2` and
* set `nums[j] = nums[j] - 2`.
Two arrays are considered to be **similar** if the fre... | null |
Python Hard | minimum-number-of-operations-to-make-arrays-similar | 0 | 1 | ```\nclass Solution:\n def makeSimilar(self, nums: List[int], target: List[int]) -> int:\n \'\'\'\n keep track of even and odd numbers in target\n \n \'\'\'\n ans = 0\n nums.sort()\n target.sort()\n\n hOdd = []\n hEven = []\n hTargetOdd = []\n ... | 0 | You are given two positive integer arrays `nums` and `target`, of the same length.
In one operation, you can choose any two **distinct** indices `i` and `j` where `0 <= i, j < nums.length` and:
* set `nums[i] = nums[i] + 2` and
* set `nums[j] = nums[j] - 2`.
Two arrays are considered to be **similar** if the fre... | null |
Python Solve | minimum-number-of-operations-to-make-arrays-similar | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def makeSimilar(self, nums: List[int], target: List[int]) -> int:\n n=len(nums)\n inc=0\n dec=0\n arr=[]\n nums.sort()\n target.sort()\n i=0\n j=0\n\n while i<n and j<n:\n if nums[i]%2==0 and target[j]%2==0:\... | 0 | You are given two positive integer arrays `nums` and `target`, of the same length.
In one operation, you can choose any two **distinct** indices `i` and `j` where `0 <= i, j < nums.length` and:
* set `nums[i] = nums[i] + 2` and
* set `nums[j] = nums[j] - 2`.
Two arrays are considered to be **similar** if the fre... | null |
Easy to understand python solution | odd-string-difference | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def oddString(self, words: List[str]) -> str:\n k=len(words[0])\n arr=[]\n for i in words:\n l=[]\n for j in range(1,k):\n diff=ord(i[j])-ord(i[j-1])\n l.append(diff)\n arr.append(l)\n for i ... | 4 | You are given an array of equal-length strings `words`. Assume that the length of each string is `n`.
Each string `words[i]` can be converted into a **difference integer array** `difference[i]` of length `n - 1` where `difference[i][j] = words[i][j+1] - words[i][j]` where `0 <= j <= n - 2`. Note that the difference be... | null |
2 liner in python for fun | odd-string-difference | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def oddString(self, words: List[str]) -> str:\n a = [[ord(s[i])-ord(s[i-1]) for i in range(1,len(s))] for s in words]\n return words[a.index(*[arr for arr in a if a.count(arr) == 1])]\n``` | 2 | You are given an array of equal-length strings `words`. Assume that the length of each string is `n`.
Each string `words[i]` can be converted into a **difference integer array** `difference[i]` of length `n - 1` where `difference[i][j] = words[i][j+1] - words[i][j]` where `0 <= j <= n - 2`. Note that the difference be... | null |
Odd String Difference with step by step explanation | odd-string-difference | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. First, we initialize n with the length of the words array and m with the length of each word in the words array.\n\n2. Next, we initialize an empty list diff to store the difference arrays of all the words.\n\n3. Then, we... | 1 | You are given an array of equal-length strings `words`. Assume that the length of each string is `n`.
Each string `words[i]` can be converted into a **difference integer array** `difference[i]` of length `n - 1` where `difference[i][j] = words[i][j+1] - words[i][j]` where `0 <= j <= n - 2`. Note that the difference be... | null |
Python ✅✅✅ || Faster than 90.54% || Memory Beats 78.47% | odd-string-difference | 0 | 1 | ### ***Note***: List Comprehension is used in my code!\n\n# Code\n```\nclass Solution:\n def oddString(self, words):\n difference = []\n alphabet = "abcdefghijklmnopqrstuvwxyz"\n for word in words:\n diff = []\n for j in range(len(word) - 1):\n diff.append(al... | 1 | You are given an array of equal-length strings `words`. Assume that the length of each string is `n`.
Each string `words[i]` can be converted into a **difference integer array** `difference[i]` of length `n - 1` where `difference[i][j] = words[i][j+1] - words[i][j]` where `0 <= j <= n - 2`. Note that the difference be... | null |
[Python] Simple HashSet solution O((N+M) * L^3) | words-within-two-edits-of-dictionary | 0 | 1 | With the help of a generator we can produce all the possible modifications:\n* 1 character is different (e.g. wood --> `[\'*ood\', \'w*od\', \'wo*d\', \'woo*\']`)\n* 2 characters are different (e.g. wood --> `[\'**od\', \'*o*d\', \'*oo*\', \'w**d\', \'w*o*\', \'wo**\']`)\n\nWe traverse the dictionary array and store ea... | 2 | You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length.
In one **edit** you can take a word from `queries`, and change any letter in it to any other letter. Find all words from `queries` that, after a **maximum** of two edits,... | null |
Words Within Two Edits of Dictionary with step by step explanation | words-within-two-edits-of-dictionary | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- The function is_valid takes two words as input, query and word, and returns True if the number of different characters between the two words is less than or equal to 2.\n- The main function wordWithinTwoEdits loops through... | 1 | You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length.
In one **edit** you can take a word from `queries`, and change any letter in it to any other letter. Find all words from `queries` that, after a **maximum** of two edits,... | null |
[Java/Python 3] Bruteforce code. | words-within-two-edits-of-dictionary | 1 | 1 | **Q & A**\n*Q1*: What is the `outer` in java code?\n*A1*: It is a java statement label. Please refer to [w3resource](https://www.w3resource.com/java-tutorial/java-branching-statements.php#:~:text=Labeled%20Statements.%20Although%20many%20statements%20in%20a%20Java,valid%20identifier%20that%20ends%20with%20a%20colon%20%... | 9 | You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length.
In one **edit** you can take a word from `queries`, and change any letter in it to any other letter. Find all words from `queries` that, after a **maximum** of two edits,... | null |
python3 Solution O(1) and O(Q*D*L) | words-within-two-edits-of-dictionary | 0 | 1 | ```\n\nclass Solution:\n def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]:\n res=[]\n N=len(queries[0])\n for query in queries:\n for word in dictionary:\n delta=0\n \n for i in range(N):\n i... | 2 | You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length.
In one **edit** you can take a word from `queries`, and change any letter in it to any other letter. Find all words from `queries` that, after a **maximum** of two edits,... | null |
[Java/Python 3] Count the frequency of the remainder of modulo. | destroy-sequential-targets | 1 | 1 | **Q & A**\n\nQ1: What does `freqs.merge(n, 1, Integer::sum)` mean in Java code?\nA1: `freqs.merge(n, 1, Integer::sum)` is simiar to `freqs.put(n, freqs.getOrDefault(n, 0) + 1)`, which increase the frequency (occurrence) of `n` by `1`; The difference between them is that `merge` return the increased frequency but `put` ... | 18 | You are given a **0-indexed** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.
You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]` allows it to destroy all targets with values that can be represented as `nu... | null |
[Python 3] Hash Table + Counting + Greedy - Easy to Understand | destroy-sequential-targets | 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)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here... | 3 | You are given a **0-indexed** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.
You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]` allows it to destroy all targets with values that can be represented as `nu... | null |
Python (Simple Maths) | destroy-sequential-targets | 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** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.
You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]` allows it to destroy all targets with values that can be represented as `nu... | null |
Python | Greedy | Group | Example | destroy-sequential-targets | 0 | 1 | \n```\nclass Solution:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n\t\t# example: nums = [3,7,8,1,1,5], space = 2\n groups = defaultdict(list)\n for num in nums:\n groups[num % space].append(num)\n \n # print(groups) # defaultdict(<class \'list\'>, {1: [3,... | 3 | You are given a **0-indexed** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.
You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]` allows it to destroy all targets with values that can be represented as `nu... | null |
Python, use a Counter (almost always) | destroy-sequential-targets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the hint suggests, the first step is to calculate for all ```nums[i]``` the value ```nums[i] % space```; let\'s refer to this as ```mod_num[i]```. It turns out that ```nums``` that go into the same "kill group" (the subset of ```nums`... | 0 | You are given a **0-indexed** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.
You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]` allows it to destroy all targets with values that can be represented as `nu... | null |
Python | HashMap Solution| O(n) | destroy-sequential-targets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKeeping track of remainders is the key to this problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nProblem can be divided into following cases:\n1. len(nums) == 1: only 1 value then return it as seed value\n2.... | 0 | You are given a **0-indexed** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.
You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]` allows it to destroy all targets with values that can be represented as `nu... | null |
[Python3] intermediate stack | next-greater-element-iv | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/a90ca3f9de0f99297262514c111f27700c24c04a) for solutions of biweekly 90. \n\n```\nclass Solution:\n def secondGreaterElement(self, nums: List[int]) -> List[int]:\n ans = [-1] * len(nums)\n s, ss = [], []\n for i, x in enumera... | 1 | You are given a **0-indexed** array of non-negative integers `nums`. For each integer in `nums`, you must find its respective **second greater** integer.
The **second greater** integer of `nums[i]` is `nums[j]` such that:
* `j > i`
* `nums[j] > nums[i]`
* There exists **exactly one** index `k` such that `nums[k... | null |
Python3 (First ,Helper and Second stacks) || O(n) || 100% Faster | next-greater-element-iv | 0 | 1 | \n```\nclass Solution:\n def secondGreaterElement(self, nums: List[int]) -> List[int]:\n st1 = [] # monotonic decreasing first stack.\n st2 = [] # Monotonic decreasing second stack.(having only that elements which have first greater)\n helper = [] # monotonic increasing helper stack(help in movi... | 2 | You are given a **0-indexed** array of non-negative integers `nums`. For each integer in `nums`, you must find its respective **second greater** integer.
The **second greater** integer of `nums[i]` is `nums[j]` such that:
* `j > i`
* `nums[j] > nums[i]`
* There exists **exactly one** index `k` such that `nums[k... | null |
Python beats 100% | next-greater-element-iv | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust hold another stack with those already having 1 successor.\nRememeber to reverse the order\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e... | 0 | You are given a **0-indexed** array of non-negative integers `nums`. For each integer in `nums`, you must find its respective **second greater** integer.
The **second greater** integer of `nums[i]` is `nums[j]` such that:
* `j > i`
* `nums[j] > nums[i]`
* There exists **exactly one** index `k` such that `nums[k... | null |
mono stack + minheap python3 concise solution | next-greater-element-iv | 0 | 1 | # Intuition\nmono stack to find the first larger\nminheap to find the second larger\n\n# Approach\nBuild a mono stack to find the \'first larger\' of each num, while poping smaller nums off the stack, push them onto a minheap. Then before pushing any number onto the stack, try to compare it with the numbers in the heap... | 0 | You are given a **0-indexed** array of non-negative integers `nums`. For each integer in `nums`, you must find its respective **second greater** integer.
The **second greater** integer of `nums[i]` is `nums[j]` such that:
* `j > i`
* `nums[j] > nums[i]`
* There exists **exactly one** index `k` such that `nums[k... | null |
Easy Python Solution | average-value-of-even-numbers-that-are-divisible-by-three | 0 | 1 | # Code\n```\nclass Solution:\n def averageValue(self, nums: List[int]) -> int:\n l=[]\n for i in nums:\n if i%6==0:\n l.append(i)\n return sum(l)//len(l) if len(l)>0 else 0\n``` | 2 | Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._
Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
**Example 1:**
**Input:** nums = \[1,3,6,10,12,... | null |
Python Super Simple 2-Lines Pythonic Solution | average-value-of-even-numbers-that-are-divisible-by-three | 0 | 1 | # Approach\nFirst we filter all the even numbers that are divisible by three.\nThen we calculate their average.\n\n# Code\n```\nclass Solution:\n def averageValue(self, nums: List[int]) -> int:\n res = [a for a in nums if ((a % 2 == 0) and (a % 3 == 0))]\n return 0 if len(res) == 0 else sum(res) // len... | 1 | Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._
Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
**Example 1:**
**Input:** nums = \[1,3,6,10,12,... | null |
Easiest Python Solution || With Explanation ✔ | average-value-of-even-numbers-that-are-divisible-by-three | 0 | 1 | Here is my solution in Python:-\n```\nclass Solution:\n def averageValue(self, nums: List[int]) -> int:\n ans=0 # ans will store the sum of elements which are even and divisible by 3; \n cnt=0 # cnt will store the number of elements which are even and divisible by 3; \n\t\t\t\t\t\t\t\... | 1 | Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._
Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
**Example 1:**
**Input:** nums = \[1,3,6,10,12,... | null |
Python one pass O(n) | average-value-of-even-numbers-that-are-divisible-by-three | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom the question, we know we need to check which numbers are both even and divisible by three.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLoop through nums, check what fits reqs, add it to array. If the array h... | 1 | Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._
Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
**Example 1:**
**Input:** nums = \[1,3,6,10,12,... | null |
Python | Easy Solution✅ | average-value-of-even-numbers-that-are-divisible-by-three | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def averageValue(self, nums: List[int]) -> int:\n nums = list(filter(lambda x: x % 2 == 0 and x % 3 == 0, nums)) # list(filter(lambda x: x % 6 == 0, nums)) will also works\n return 0 if not len(nums) else sum(nums)//len(nums)\n``` | 4 | Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._
Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
**Example 1:**
**Input:** nums = \[1,3,6,10,12,... | null |
Python simple two lines solution | average-value-of-even-numbers-that-are-divisible-by-three | 0 | 1 | # Approach\nLeave in the array only the even elements that divided to 3.\nCalaulate the average of the array.\n\n\n# Code\n```\nclass Solution:\n def averageValue(self, nums: List[int]) -> int:\n nums = [i for i in nums if not i % 3 and not i % 2]\n return 0 if not len(nums) else (sum(nums) // len(nums... | 3 | Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._
Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
**Example 1:**
**Input:** nums = \[1,3,6,10,12,... | null |
Average Value of Even Numbers Divisible by Three | average-value-of-even-numbers-that-are-divisible-by-three | 0 | 1 | \n# Intuition\nThe task is to find the average value of even numbers in a list that are divisible by three. The solution iterates through each element in the input list, identifies even numbers divisible by three, and calculates their average. The check for an empty list is included to handle the case where no qualifyi... | 0 | Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._
Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
**Example 1:**
**Input:** nums = \[1,3,6,10,12,... | null |
[ Python ]🐍🐍Simple Python Solution ✅✅ | average-value-of-even-numbers-that-are-divisible-by-three | 0 | 1 | ```\nclass Solution:\n def averageValue(self, nums: List[int]) -> int:\n s=0\n k=0\n for i in nums:\n if i%6==0:\n k+=1\n s+=i\n \n if k==0:\n return 0\n else:\n return(s//k)\n``` | 2 | Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._
Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
**Example 1:**
**Input:** nums = \[1,3,6,10,12,... | null |
pandas | most-popular-video-creator | 0 | 1 | Doesn\'t actually work since leetcode doesn\'t support pandas\n\n\n# Approach\nUse pandas\n\n# Code\n```\nimport pandas as pd \nimport numpy as np \nclass Solution:\n def mostPopularCreator(self, creators: List[str], ids: List[str], views: List[int]) -> List[List[str]]:\n df = pd.DataFrame({"creators": creato... | 1 | You are given two string arrays `creators` and `ids`, and an integer array `views`, all of length `n`. The `ith` video on a platform was created by `creator[i]`, has an id of `ids[i]`, and has `views[i]` views.
The **popularity** of a creator is the **sum** of the number of views on **all** of the creator's videos. Fi... | null |
Python Hashmap solution | No Sorting | most-popular-video-creator | 0 | 1 | Approach: \nI have declared a hashmap to collect the following values,\n1. total number current views for the creator\n2. store the lexicographic id of the creator\'s popular video\n3. current popular view of the creator\n\nSo my final hashmap for the given basic test case looks like {\'alice\': [10, \'one\', 5], \'bob... | 6 | You are given two string arrays `creators` and `ids`, and an integer array `views`, all of length `n`. The `ith` video on a platform was created by `creator[i]`, has an id of `ids[i]`, and has `views[i]` views.
The **popularity** of a creator is the **sum** of the number of views on **all** of the creator's videos. Fi... | null |
Easy Solution using Hash Table !! | most-popular-video-creator | 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:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def mostPopularCreator(self, creators: List[str], ids: List[... | 1 | You are given two string arrays `creators` and `ids`, and an integer array `views`, all of length `n`. The `ith` video on a platform was created by `creator[i]`, has an id of `ids[i]`, and has `views[i]` views.
The **popularity** of a creator is the **sum** of the number of views on **all** of the creator's videos. Fi... | null |
Python | With Example | Greedy | minimum-addition-to-make-integer-beautiful | 0 | 1 | ```\n\nclass Solution:\n def makeIntegerBeautiful(self, n: int, target: int) -> int:\n total = added = 0\n mask = 10\n while sum([int(c) for c in str(n)]) > target:\n added = mask - n % mask\n if added != mask:\n n += added\n total += added\n ... | 1 | You are given two positive integers `n` and `target`.
An integer is considered **beautiful** if the sum of its digits is less than or equal to `target`.
Return the _minimum **non-negative** integer_ `x` _such that_ `n + x` _is beautiful_. The input will be generated such that it is always possible to make `n` beautif... | null |
Python 3 || 6 lines, w/example || T/M: 99% / 71% | minimum-addition-to-make-integer-beautiful | 0 | 1 | ```\nclass Solution:\n def makeIntegerBeautiful(self, n: int, target: int) -> int:\n\n sm = lambda n: sum(map(int,list(str(n))))\n\n zeros, diff = 10, 0 # Ex: n = 5617 ; target = 7\n\n while sm(n + diff) > target: # n zeros diff n+diff sm(n+diff)\n ... | 6 | You are given two positive integers `n` and `target`.
An integer is considered **beautiful** if the sum of its digits is less than or equal to `target`.
Return the _minimum **non-negative** integer_ `x` _such that_ `n + x` _is beautiful_. The input will be generated such that it is always possible to make `n` beautif... | null |
Greedy Algorithm - O(log n) - Comprehensive Explanation | minimum-addition-to-make-integer-beautiful | 0 | 1 | # Intuition\nTo find the minimum number to add to an integer n such that the sum of its digits is no more than a target value, we can use a greedy approach. We will try to minimize the added value while ensuring that the sum of the digits does not exceed the target.\n\n# Approach\nThe approach involves iterating throug... | 1 | You are given two positive integers `n` and `target`.
An integer is considered **beautiful** if the sum of its digits is less than or equal to `target`.
Return the _minimum **non-negative** integer_ `x` _such that_ `n + x` _is beautiful_. The input will be generated such that it is always possible to make `n` beautif... | null |
Check next 10, next 100, next 1000 and so on... | minimum-addition-to-make-integer-beautiful | 0 | 1 | e.g 467\nif 467 is not sufficient, we have to directly check 470 because till 470 sum will increase only.\nafter 470,check 500 beacuse till 500 sum will increase only\nthus we have to check next 10th base every time\n\n```\nclass Solution:\n def makeIntegerBeautiful(self, n: int, target: int) -> int:\n i=n\n ... | 3 | You are given two positive integers `n` and `target`.
An integer is considered **beautiful** if the sum of its digits is less than or equal to `target`.
Return the _minimum **non-negative** integer_ `x` _such that_ `n + x` _is beautiful_. The input will be generated such that it is always possible to make `n` beautif... | null |
Simple math | minimum-addition-to-make-integer-beautiful | 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 two positive integers `n` and `target`.
An integer is considered **beautiful** if the sum of its digits is less than or equal to `target`.
Return the _minimum **non-negative** integer_ `x` _such that_ `n + x` _is beautiful_. The input will be generated such that it is always possible to make `n` beautif... | null |
Segment Tree | O(nlogn) | height-of-binary-tree-after-subtree-removal-queries | 0 | 1 | # Approach\nDo a dfs traversal to append each depth (from root to leaf) to compute a list `depth`. \n\n`pre` and `post` determine the range of element in `depth` list so that all values inside this range are from path rooted at this node. \n\nFor each queries, we want to find out the max depth without choosing element ... | 5 | You are given the `root` of a **binary tree** with `n` nodes. Each node is assigned a unique value from `1` to `n`. You are also given an array `queries` of size `m`.
You have to perform `m` **independent** queries on the tree where in the `ith` query you do the following:
* **Remove** the subtree rooted at the nod... | null |
simple and fast - DFS + heap | height-of-binary-tree-after-subtree-removal-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEach node has a height and a depth associated with it. Height is the number of levels above the node and depth is the number of levels below the node. So the nodes potential contribution to the maximum height of the binary tree is its hei... | 3 | You are given the `root` of a **binary tree** with `n` nodes. Each node is assigned a unique value from `1` to `n`. You are also given an array `queries` of size `m`.
You have to perform `m` **independent** queries on the tree where in the `ith` query you do the following:
* **Remove** the subtree rooted at the nod... | null |
Python3 | 100% T | 85% S | O(N) Time and Space | Explained for Beginner Friendly | height-of-binary-tree-after-subtree-removal-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can think of solving offline query. \nNot all nodes will affect the height of tree, only those node who are in path of maximum height will affect the height of tree\n# Approach\n<!-- Describe your approach to solving the problem. -->\n... | 1 | You are given the `root` of a **binary tree** with `n` nodes. Each node is assigned a unique value from `1` to `n`. You are also given an array `queries` of size `m`.
You have to perform `m` **independent** queries on the tree where in the `ith` query you do the following:
* **Remove** the subtree rooted at the nod... | null |
Python (Simple DFS) | height-of-binary-tree-after-subtree-removal-queries | 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)$$ --... | 6 | You are given the `root` of a **binary tree** with `n` nodes. Each node is assigned a unique value from `1` to `n`. You are also given an array `queries` of size `m`.
You have to perform `m` **independent** queries on the tree where in the `ith` query you do the following:
* **Remove** the subtree rooted at the nod... | null |
[Python 3]Topological sort + Hashmap | height-of-binary-tree-after-subtree-removal-queries | 0 | 1 | ```\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\nclass Solution:\n def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:\n par =... | 1 | You are given the `root` of a **binary tree** with `n` nodes. Each node is assigned a unique value from `1` to `n`. You are also given an array `queries` of size `m`.
You have to perform `m` **independent** queries on the tree where in the `ith` query you do the following:
* **Remove** the subtree rooted at the nod... | null |
Python Solution (Beats 99.50%) || 41ms|| O(N) || Easy Solution | apply-operations-to-an-array | 0 | 1 | # Complexity\n- Time complexity:\n O(N)\n# Code\n```\nclass Solution:\n def applyOperations(self, nums: List[int]) -> List[int]:\n zeros=0\n i=0\n while(i<(len(nums)-1)):\n if(nums[i]==nums[i+1]):\n nums[i]*=2\n nums[i+1]=0\n i+=1\n ... | 3 | You are given a **0-indexed** array `nums` of size `n` consisting of **non-negative** integers.
You need to apply `n - 1` operations to this array where, in the `ith` operation (**0-indexed**), you will apply the following on the `ith` element of `nums`:
* If `nums[i] == nums[i + 1]`, then multiply `nums[i]` by `2`... | null |
Sliding window with hashmap to count distinct | maximum-sum-of-distinct-subarrays-with-length-k | 0 | 1 | ```\nfrom collections import Counter\n\nclass Solution:\n def maximumSubarraySum(self, nums: List[int], k: int) -> int:\n n = len(nums)\n s = 0\n res = 0\n ctr = Counter()\n l = 0\n for i in range(n):\n s += nums[i]\n if ctr[nums[i]] == 0:\n ... | 3 | You are given an integer array `nums` and an integer `k`. Find the maximum subarray sum of all the subarrays of `nums` that meet the following conditions:
* The length of the subarray is `k`, and
* All the elements of the subarray are **distinct**.
Return _the maximum subarray sum of all the subarrays that meet t... | null |
Python O(n) by prefix sum + sliding window [w/ Hint] | maximum-sum-of-distinct-subarrays-with-length-k | 0 | 1 | **Hint**\n\nThis is a combination of [**Leetcode #303 Range Sum Query**](https://leetcode.com/problems/range-sum-query-immutable/) and [**Leetcode #3 Longest substring without repetition**](https://leetcode.com/problems/longest-substring-without-repeating-characters/) in numerical version.\n\nWhen it comes to **range s... | 1 | You are given an integer array `nums` and an integer `k`. Find the maximum subarray sum of all the subarrays of `nums` that meet the following conditions:
* The length of the subarray is `k`, and
* All the elements of the subarray are **distinct**.
Return _the maximum subarray sum of all the subarrays that meet t... | null |
python/java solution | maximum-sum-of-distinct-subarrays-with-length-k | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given an integer array `nums` and an integer `k`. Find the maximum subarray sum of all the subarrays of `nums` that meet the following conditions:
* The length of the subarray is `k`, and
* All the elements of the subarray are **distinct**.
Return _the maximum subarray sum of all the subarrays that meet t... | null |
Clear Explanation | 1 Queue and 2 Priority-Queues | total-cost-to-hire-k-workers | 0 | 1 | # Intuition\nThe conditions are clearly stated.\nImplement the conditions stated.\n\n\n# Approach\n- Use 2 priority-queues to store and obtain the smallest costs for the first and last candidates respectively.\n\n- Store the middle elements(elements that are not currently in any of the priority-queues) in a Queue.\n- C... | 1 | You are given a **0-indexed** integer array `costs` where `costs[i]` is the cost of hiring the `ith` worker.
You are also given two integers `k` and `candidates`. We want to hire exactly `k` workers according to the following rules:
* You will run `k` sessions and hire exactly one worker in each session.
* In eac... | null |
EASY PYTHON SOLUTION || HEAPSORT | total-cost-to-hire-k-workers | 0 | 1 | \n# Code\n```\nimport heapq\nclass Solution:\n def totalCost(self, costs: List[int], k: int, candidates: int) -> int:\n n=len(costs)\n if 2*candidates>=n:\n costs.sort()\n return sum(costs[:k])\n df=n-(2*candidates)\n df2=df\n sm=0\n s1=costs[:candidate... | 1 | You are given a **0-indexed** integer array `costs` where `costs[i]` is the cost of hiring the `ith` worker.
You are also given two integers `k` and `candidates`. We want to hire exactly `k` workers according to the following rules:
* You will run `k` sessions and hire exactly one worker in each session.
* In eac... | null |
O(n^3) solution, sort + shift the minimum subarray of assignments | minimum-total-distance-traveled | 0 | 1 | # Intuition\nAs you shift the factory assignment of any given robot from left to right, the distance traveled first decreases to a minimum (or starts from the minimum), and then starts to increase again. As we go through the robots\' initial positions one by one from left the right, the closest factory either stays the... | 1 | There are some robots and factories on the X-axis. You are given an integer array `robot` where `robot[i]` is the position of the `ith` robot. You are also given a 2D integer array `factory` where `factory[j] = [positionj, limitj]` indicates that `positionj` is the position of the `jth` factory and that the `jth` facto... | null |
[Python3] O(MN) DP | minimum-total-distance-traveled | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/6a94b729b8594be1319f14da1cf3c97ddb12a427) for solutions of weekly 318.\n\nThis is an overkill for this problem as cubic solutions can pass the OJ as well. But a quadratic solution is possible. \n\n**Intuition**\nHere, I define `dp[i][j]` as the min... | 16 | There are some robots and factories on the X-axis. You are given an integer array `robot` where `robot[i]` is the position of the `ith` robot. You are also given a 2D integer array `factory` where `factory[j] = [positionj, limitj]` indicates that `positionj` is the position of the `jth` factory and that the `jth` facto... | null |
[Python] assignment problem with scipy | minimum-total-distance-traveled | 0 | 1 | classic assignment problem, scipy implements linear_sum_assignment with [Jonker-Volgenant/Hungarian algorithm](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html). Time complexity is o(n^3). \n\nAssignment solution treats robots and factories as bipatite graph, it didn\'t uti... | 10 | There are some robots and factories on the X-axis. You are given an integer array `robot` where `robot[i]` is the position of the `ith` robot. You are also given a 2D integer array `factory` where `factory[j] = [positionj, limitj]` indicates that `positionj` is the position of the `jth` factory and that the `jth` facto... | null |
Python || Easy || Sorting || O(nlogn) Solution | number-of-distinct-averages | 0 | 1 | ```\nclass Solution:\n def distinctAverages(self, nums: List[int]) -> int:\n n=len(nums)\n i=0\n j=n-1\n s=set()\n nums.sort()\n while i<=j:\n s.add((nums[i]+nums[j])/2)\n i+=1\n j-=1\n return len(s)\n```\n\n**Upvote if you like the so... | 1 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
✅✅[ Python ] 🐍🐍 Simple Python Solution ✅✅ | number-of-distinct-averages | 0 | 1 | ```\nclass Solution:\n def distinctAverages(self, nums: List[int]) -> int:\n a=[]\n for i in range(len(nums)//2):\n a.append((max(nums)+min(nums))/2)\n nums.remove(max(nums))\n nums.remove(min(nums))\n b=set(a)\n print(a)\n print(b)\n ret... | 1 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
[Python Answer🤫🐍🐍🐍] Heap and Set Solution | number-of-distinct-averages | 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 heap to remember the highest and lowest values\nUse a set to remember the averages\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. ... | 1 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
✅✅easy python solution|| easy to understand | number-of-distinct-averages | 0 | 1 | ```\nclass Solution:\n def distinctAverages(self, nums: List[int]) -> int:\n lis = []\n \n while nums!=[]:\n if (min(nums)+max(nums))/2 not in lis:\n lis.append((min(nums)+max(nums))/2)\n nums.remove(max(nums))\n nums.remove(min(nums))\n return len... | 1 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
[Python3] set | number-of-distinct-averages | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/e8b87d04cc192c5227286692921910fe93fee05d) for solutions of biweekly 91. \n\n```\nclass Solution:\n def distinctAverages(self, nums: List[int]) -> int:\n nums.sort()\n seen = set()\n for i in range(len(nums)//2): \n ... | 1 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
Easy Python Solution || using two pointers 99.80% runtime | number-of-distinct-averages | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def distinctAverages(self, nums: List[int]) -> int:\n nums.sort()\n i=0\n j=len(nums)-1\n l=[]\n while i<j:\n l.append((num... | 2 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
Easy Python Solution | number-of-distinct-averages | 0 | 1 | # Code\n```\nclass Solution:\n def distinctAverages(self, nums: List[int]) -> int:\n av=[]\n nums.sort()\n while nums:\n av.append((nums[-1]+nums[0])/2)\n nums.pop(-1)\n nums.pop(0)\n return len(set(av))\n``` | 3 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
[Java/Python 3] Put into HashSet Int instead of double/float. | number-of-distinct-averages | 1 | 1 | Essentially a two pointers algorithm is impelemented.\n```java\n public int distinctAverages(int[] nums) {\n Set<Integer> seen = new HashSet<>();\n Arrays.sort(nums);\n for (int i = 0, n = nums.length; i < n / 2; ++i) {\n seen.add(nums[i] + nums[n - 1 - i]);\n }\n return... | 18 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
Python | Easy Solution✅ | number-of-distinct-averages | 0 | 1 | # Code\n```\nclass Solution:\n def distinctAverages(self, nums: List[int]) -> int:\n distinct = set()\n while len(nums) != 0:\n nums = sorted(nums)\n avg = (nums.pop(0) + nums.pop(len(nums)-1))/2\n distinct.add(avg)\n return len(distinct)\n``` | 3 | You are given a **0-indexed** integer array `nums` of **even** length.
As long as `nums` is **not** empty, you must repetitively:
* Find the minimum number in `nums` and remove it.
* Find the maximum number in `nums` and remove it.
* Calculate the average of the two removed numbers.
The **average** of two numb... | null |
Python shortest 1-liner. Recursive DP. Functional programming. | count-ways-to-build-good-strings | 0 | 1 | # Approach\n1. Say there is a function `f`, which returns the number of good strings possible with lengths between `low (l)` and `high (h)`, given that the string is already of length `n`.\n i.e `def f(n: int) -> int: ...`\n\n2. In ideal case, recursively try both options of appending `zero` number of `0`s or `one` ... | 2 | Given the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following:
* Append the character `'0'` `zero` times.
* Append the character `'1'` `one` times.
This can be performed any number of times.
A **good** string... | null |
Python Elegant & Short | Top-Down DP | Memoization | count-ways-to-build-good-strings | 0 | 1 | # Complexity\n\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n MOD = 1_000_000_007\n\n def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:\n @cache\n def dp(length: int) -> int:\n if length > high:\n retu... | 2 | Given the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following:
* Append the character `'0'` `zero` times.
* Append the character `'1'` `one` times.
This can be performed any number of times.
A **good** string... | null |
🚀 Beats 100% | Java, C++, Python3 | Forward-style DP iterative solution | count-ways-to-build-good-strings | 1 | 1 | > \u26A0\uFE0F **Disclaimer**: The original solution was crafted in Java. Thus, when we mention "Beats 100%" it applies specifically to Java submissions. The performance may vary for other languages.\n\n**Dont forget to upvote if you like the content below. \uD83D\uDE43**\n\n\n[TOC]\n\n# Problem\nThe problem involves c... | 1 | Given the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following:
* Append the character `'0'` `zero` times.
* Append the character `'1'` `one` times.
This can be performed any number of times.
A **good** string... | null |
Python3 dp solution (beats 100%) | count-ways-to-build-good-strings | 0 | 1 | # Code\n```\nclass Solution:\n def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:\n strCount = 0\n\n dp = [0]*(high+1)\n dp[0] = 1\n\n greater = max(zero,one)\n lesser = min(zero,one)\n\n for i in range(lesser,greater):\n dp[i] += dp[i-le... | 1 | Given the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following:
* Append the character `'0'` `zero` times.
* Append the character `'1'` `one` times.
This can be performed any number of times.
A **good** string... | null |
Dynamic Programming based Python solution | count-ways-to-build-good-strings | 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 the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following:
* Append the character `'0'` `zero` times.
* Append the character `'1'` `one` times.
This can be performed any number of times.
A **good** string... | null |
Easy solution | count-ways-to-build-good-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nComputing the number of strings is similar to computing Fibonacci numbers.\nThe number of strings of length n is equal to the number of strings of length n-zero plus the number of strings of length n-one, depending on what sequence they e... | 1 | Given the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following:
* Append the character `'0'` `zero` times.
* Append the character `'1'` `one` times.
This can be performed any number of times.
A **good** string... | null |
Python3 Solution | count-ways-to-build-good-strings | 0 | 1 | \n```\nclass Solution:\n def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:\n mod=10**9+7\n dp=[1]\n total=0\n\n for i in range(1,high+1):\n dp.append(0)\n\n if i-zero>=0:\n dp[i]+=dp[i-zero]\n\n if i-one>=0:\n ... | 1 | Given the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following:
* Append the character `'0'` `zero` times.
* Append the character `'1'` `one` times.
This can be performed any number of times.
A **good** string... | null |
Python 3, DFS Backtracking with Explanation | most-profitable-path-in-a-tree | 0 | 1 | Since the undirected tree has $$n$$ nodes and $$n-1$$ edges, there is only one path from bob to root $$0$$. The path from bob to root 0 as well as the time Bob reaches each node on the path is used to compute the reward (price) Alice gets at each node. \n\nWe will first use a DFS backtracking to determine Bob\'s path. ... | 1 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1`, rooted at node `0`. You are given 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.
At every node `i`, there is a gate. You are also given an array of ... | null |
Double DFS | most-profitable-path-in-a-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. -->\nBasically we don\'t care about the cost of Bob\'s path as long as he finds the root. since its a tree there should only be one way of getting to the root. do DFS on Bo... | 0 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1`, rooted at node `0`. You are given 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.
At every node `i`, there is a gate. You are also given an array of ... | null |
[Python3] Intuitive two DFS | most-profitable-path-in-a-tree | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nRecord Bob\'s path and his time in reaching each node. Then compare with Alice\'s path, if there is interaction, split the rewards/costs. Also, if Alice reached this node earlier than Bob, then Alice can take the whole rewards/costs.\n\n\n# Complexity... | 0 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1`, rooted at node `0`. You are given 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.
At every node `i`, there is a gate. You are also given an array of ... | null |
[Python] Simple dumb O(N) solution, no binary search needed | split-message-based-on-limit | 0 | 1 | # Intuition\nThe idea is to figure out how many characters the parts count take up. Once we know that, generating all the parts is trivial.\n\n# Approach\nSimply check if 9, 99, 999, or 9999 parts are enough to split the whole message, since 9, 99, 999, or 9999 are the maximum possible parts count for 1, 2, 3, or 4 cha... | 3 | You are given a string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
Total parts number calculation | split-message-based-on-limit | 0 | 1 | # Intuition\nThe tricky part of this task is that the size of payload is changing even in already processed parts of the message. Because of this we need some structure, that will maintain the size of message\'s part. Also it\'s not a good idea to use some kind of "greedy" approach because we would have to rearrange pa... | 0 | You are given a string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
O(n) solution with O(1) space with "simple" math and problem constraints analysis | split-message-based-on-limit | 0 | 1 | # Intuition\nThe intuition is that no matter how many parts you have, they will always follow a pattern of digits. Any number between 100 and 999, for example, will always have 3 digits. So instead of combining everything and seeing if it magically works (I\'m looking at you brute-forcers), we can calculate how many pa... | 0 | You are given a string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
just impliment of task | split-message-based-on-limit | 0 | 1 | \n# Approach\njust impliment of task\n\n# Code\n```\nclass Solution:\n def splitMessage(self, m: str, l: int) -> List[str]:\n d=len(m)\n for i in range(1,5):\n t=d\n for j in range(1,i):t-=(10**j-1)\n if(k:=l-3-2*i)<=0:return []\n if (p:=(t-1+k)//k)>(10**i-... | 0 | You are given a string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
Python binary search solution beats 99.25% | split-message-based-on-limit | 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 string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
No Binary Search | Purely Mathematical | Beats 99.04% | split-message-based-on-limit | 0 | 1 | \n\n\n# Intuition\nFollowing formula can be deduced for this problem\n$$ \\sum_{i=1}^{d} 9 * 10^{ (i-1)} * ( limit - 3 -(i+d)) $$\n\nwhere limit is the given parameter in the program,... | 0 | You are given a string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
Beginner Understanding | split-message-based-on-limit | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBest in all the way to make the beginners understand good and the flow is user-friendly.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space ... | 0 | You are given a string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
Two phases python solution | split-message-based-on-limit | 0 | 1 | # Intuition\n\nFirst one need to find the number of parts. After that the splitting is obvious.\n\n# Complexity\n- Time complexity: $$O(n\\log(n))$$ where $n$ is the length of the message. \n\nThe $\\log(n)$ comes from the `tags_total_len` function which is called at most $n$ times, but this is a very rough estimation.... | 0 | You are given a string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
Python (Simple Maths) | split-message-based-on-limit | 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 string, `message`, and a positive integer, `limit`.
You must **split** `message` into one or more **parts** based on `limit`. Each resulting part should have the suffix `" "`, where `"b "` is to be **replaced** with the total number of parts and `"a "` is to be **replaced** with the index of the part, ... | null |
Python || One line Code || 99.6% beats | convert-the-temperature | 0 | 1 | **Plz Upvote ..if you got help from this..**\n# Code\n```\nclass Solution:\n def convertTemperature(self, celsius: float) -> List[float]:\n return [celsius + 273.15, celsius * 1.80 + 32.00 ]\n # or\n kelvin = celsius + 273.15\n fahrenheit = celsius * 1.80 + 32.00\n\n return [kelvin... | 2 | You are given a non-negative floating point number rounded to two decimal places `celsius`, that denotes the **temperature in Celsius**.
You should convert Celsius into **Kelvin** and **Fahrenheit** and return it as an array `ans = [kelvin, fahrenheit]`.
Return _the array `ans`._ Answers within `10-5` of the actual a... | null |
🔥🔥1 Liner🔥🔥 and that's it | convert-the-temperature | 0 | 1 | \n# Code\n```\nclass Solution:\n def convertTemperature(self, celsius: float) -> List[float]:\n return celsius + 273.15 , celsius * 1.80+32.00\n``` | 4 | You are given a non-negative floating point number rounded to two decimal places `celsius`, that denotes the **temperature in Celsius**.
You should convert Celsius into **Kelvin** and **Fahrenheit** and return it as an array `ans = [kelvin, fahrenheit]`.
Return _the array `ans`._ Answers within `10-5` of the actual a... | null |
Easy O(1): Create a new language from scratch, a register-based VM and calculate the result in it | convert-the-temperature | 0 | 1 | # Intuition\nSelf explanatory.\n\n# Approach\nCreate an x86 assembly-like language, a parser and an "infinite" (8 is good enough) register-based VM to execute the program.\n\n# Complexity\n- Time complexity:\n$$O(who\\:cares)$$\n\n- Space complexity:\n$$O(1)$$\n\n\n# Code\n```\nfrom enum import Enum\nfrom typing import... | 1 | You are given a non-negative floating point number rounded to two decimal places `celsius`, that denotes the **temperature in Celsius**.
You should convert Celsius into **Kelvin** and **Fahrenheit** and return it as an array `ans = [kelvin, fahrenheit]`.
Return _the array `ans`._ Answers within `10-5` of the actual a... | null |
Python short and easy | number-of-subarrays-with-lcm-equal-to-k | 0 | 1 | This question is just a variant of [2447](https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k/description/) asked in recent contest\n```\nfrom math import gcd\nclass Solution:\n \n def lcm(self,a, b):\n return abs(a*b) // math.gcd(a, b)\n\n def subarrayLCM(self, nums: List[int], k: in... | 2 | Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the least common multiple of the subarray's elements is_ `k`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
The **least common multiple of an array** is the smallest positive intege... | null |
Beginners Approach : | number-of-subarrays-with-lcm-equal-to-k | 0 | 1 | ```\nclass Solution:\n def subarrayLCM(self, nums: List[int], k: int) -> int:\n def find_lcm(num1, num2):\n if(num1>num2):\n num = num1\n den = num2\n else:\n num = num2\n den = num1\n rem = num % den\n whi... | 1 | Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the least common multiple of the subarray's elements is_ `k`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
The **least common multiple of an array** is the smallest positive intege... | null |
Python||Very Easy Implementation|| | number-of-subarrays-with-lcm-equal-to-k | 0 | 1 | \n def gcd(a,b):\n while b:\n a,b = b, a%b\n return abs(a)\n def lcm(a,b):\n return a*b / gcd(a,b)\n def subarrayLCM(self, nums: List[int], k: int) -> int:\n c=0\n l=len(nums)\n for i in range(l):\n x=nums[i]\n for j in range(i,l):\n ... | 4 | Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the least common multiple of the subarray's elements is_ `k`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
The **least common multiple of an array** is the smallest positive intege... | null |
python solution | number-of-subarrays-with-lcm-equal-to-k | 0 | 1 | ```\nimport math\nclass Solution:\n def subarrayLCM(self, nums: List[int], k: int) -> int:\n def gcd(a,b):\n return math.gcd(a,b)\n def lcm(n1,n2):\n return (n1*n2)//gcd(n1,n2)\n n=len(nums)\n ans=0\n for i in range(n):\n lcmi=nums[i]\n f... | 4 | Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the least common multiple of the subarray's elements is_ `k`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
The **least common multiple of an array** is the smallest positive intege... | null |
Recursive solution in python | number-of-subarrays-with-lcm-equal-to-k | 0 | 1 | # Approach\nConsider every index in the list, if it\'s lcm <= k, expand it in both sides until lcm >= k. And keep the subarray if its lcm = k. Avoid redundant computing with the memo dict. \n\n\n# Code\n```\nimport math\nclass Solution:\n def subarrayLCM(self, nums, k: int) -> int:\n if len(set(nums)) == 1:\n... | 0 | Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the least common multiple of the subarray's elements is_ `k`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
The **least common multiple of an array** is the smallest positive intege... | null |
Python Straightforward | number-of-subarrays-with-lcm-equal-to-k | 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 integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the least common multiple of the subarray's elements is_ `k`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
The **least common multiple of an array** is the smallest positive intege... | null |
Python3 | Easy Solution | minimum-number-of-operations-to-sort-a-binary-tree-by-level | 0 | 1 | # 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\nclass Solution:\n def minimumOperations(self, root: Optional[TreeNode]) -> int:\n queue = deque([ro... | 2 | You are given the `root` of a binary tree with **unique values**.
In one operation, you can choose any two nodes **at the same level** and swap their values.
Return _the minimum number of operations needed to make the values at each level sorted in a **strictly increasing order**_.
The **level** of a node is the num... | null |
level order + swap sort | minimum-number-of-operations-to-sort-a-binary-tree-by-level | 0 | 1 | class Solution:\n def minimumOperations(self, root: Optional[TreeNode]) -> int:\n \n def swp(arr):\n n = len(arr)\n ans = 0\n temp = arr.copy()\n h = {}\n temp.sort()\n\n for i in range(n):\n\n h[arr[i]] = i\n\n ... | 2 | You are given the `root` of a binary tree with **unique values**.
In one operation, you can choose any two nodes **at the same level** and swap their values.
Return _the minimum number of operations needed to make the values at each level sorted in a **strictly increasing order**_.
The **level** of a node is the num... | null |
[Python3] BFS | minimum-number-of-operations-to-sort-a-binary-tree-by-level | 0 | 1 | \n```\nclass Solution:\n def minimumOperations(self, root: Optional[TreeNode]) -> int:\n ans = 0 \n queue = deque([root])\n while queue: \n vals = []\n for _ in range(len(queue)): \n node = queue.popleft()\n vals.append(node.val)\n ... | 8 | You are given the `root` of a binary tree with **unique values**.
In one operation, you can choose any two nodes **at the same level** and swap their values.
Return _the minimum number of operations needed to make the values at each level sorted in a **strictly increasing order**_.
The **level** of a node is the num... | null |
Easy Level order traversal with comments || Python | minimum-number-of-operations-to-sort-a-binary-tree-by-level | 0 | 1 | ```\nclass Solution:\n def cntSwap(self,arr):\n \n n = len(arr)\n cnt = 0\n a = sorted(arr)\n index = {}\n \n\t\t# store index of elements in arr\n for ind in range(n):\n index[arr[ind]] = ind\n\n for ind in range(n):\n\t\t\t\n\t\t\t# If element in a... | 5 | You are given the `root` of a binary tree with **unique values**.
In one operation, you can choose any two nodes **at the same level** and swap their values.
Return _the minimum number of operations needed to make the values at each level sorted in a **strictly increasing order**_.
The **level** of a node is the num... | null |
[Python 3] BFS | Union-Find | minimum-number-of-operations-to-sort-a-binary-tree-by-level | 0 | 1 | ```\nclass Solution:\n def minimumOperations(self, root: Optional[TreeNode]) -> int:\n par = {}\n rank = {}\n \n def ins(n1):\n if n1 in par:\n return\n par[n1] = n1\n rank[n1] = 1\n \n def find(n1):\n while n1 != pa... | 2 | You are given the `root` of a binary tree with **unique values**.
In one operation, you can choose any two nodes **at the same level** and swap their values.
Return _the minimum number of operations needed to make the values at each level sorted in a **strictly increasing order**_.
The **level** of a node is the num... | null |
Python [Explained] | O(nlogn) | minimum-number-of-operations-to-sort-a-binary-tree-by-level | 0 | 1 | * We will find all the nodes at current level and then count minimum number of swaps required to make them sorted.\n\n* How to calculate minimum swaps required to make array sorted :\n\nmake a new array (called temp), which is the sorted form of the input array. We know that we need to transform the input array to the ... | 1 | You are given the `root` of a binary tree with **unique values**.
In one operation, you can choose any two nodes **at the same level** and swap their values.
Return _the minimum number of operations needed to make the values at each level sorted in a **strictly increasing order**_.
The **level** of a node is the num... | null |
[C++, Java, Python3] Palindromic Substrings + Non-overlapping Intervals | maximum-number-of-non-overlapping-palindrome-substrings | 1 | 1 | \n**Explanation**\nThis question is a combination of Palindromic Substring and Non-overlapping intervals\nhttps://leetcode.com/problems/palindromic-substrings/\nhttps://leetcode.com/problems/non-overlapping-intervals/\n* First find all palindromic substrings with length >= k in O(n*k) and store their start and end in a... | 97 | 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 |
[Python3] DP with Explanations | Only Check Substrings of Length k and k + 1 | maximum-number-of-non-overlapping-palindrome-substrings | 0 | 1 | **Observation**\nGiven the constraints, a solution with quadratic time complexity suffices for this problem. The key to this problem is to note that, if a given palindromic substring has length greater or equal to `k + 2`, then we can always remove the first and last character of the substring without losing the optima... | 12 | 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 |
✅ [Python] Very simple solution - O(n) || no DP | maximum-number-of-non-overlapping-palindrome-substrings | 0 | 1 | ## Intuition\nSimilar to 647 https://leetcode.com/problems/palindromic-substrings/\nJust need to add the constraint - non-overlapping\n\n## Approach\nExpand from centers to make the time complexity O(N), space complexity O(1)\nOnly count the palindrome with shortest length (>=k)\nKeep track of the last end position to ... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.