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 Heap | Explained | find-score-of-an-array-after-marking-all-elements | 0 | 1 | # Intuition\nWe have to mark the smallest index as well as its left and right element too if they exist.\nTo find the smallest integer present use a heap pushing (ele, index)\nnow pop the smallest element and add it to seen and score if we havent seen this index before and then also add its left and right index if they... | 1 | You are given an array `nums` consisting of positive integers.
Starting with `score = 0`, apply the following algorithm:
* Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.
* Add the value of the chosen integer to `score`.
* Mark **the chosen... | null |
Python 3 || 3 lines, bisect_left || T/M: 1712 ms / 17.7 MB | minimum-time-to-repair-cars | 0 | 1 | Note that we can use integer division and integer square root `isqrt` because of the nature of the problem. \n```\nclass Solution:\n def repairCars(self, ranks: List[int], cars: int) -> int:\n \n arr = range(cars*cars * max(ranks))\n\n f = lambda t: sum(isqrt(t//r) for r in ranks)\n\n ret... | 3 | You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
Python Easy solution with Easy explanation | minimum-time-to-repair-cars | 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. -->\nApply binary search on time.\nImportant things:\n1) Setting the limits\n left limit: 0(if no cars)\n right limit: cars*(maximum rating)<sup>2</sup>\n2) Check fun... | 1 | You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
✅98.44%🔥3 line code🔥 | minimum-time-to-repair-cars | 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 `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
python3 Solution | minimum-time-to-repair-cars | 0 | 1 | \n```\nclass Solution:\n def repairCars(self, ranks: List[int], cars: int) -> int:\n count=Counter(ranks)\n left=1\n right=min(count)*cars*cars\n while left<right:\n mid=(left+right)//2\n if sum(isqrt(mid//a)*count[a] for a in count)<cars:\n left=mid+1... | 1 | You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
[Python 3] Binary Search | minimum-time-to-repair-cars | 0 | 1 | The helper function *repair(time)* determines if *cars* can be repaired within *time*.\n\n# Code\n```\nclass Solution:\n def repairCars(self, ranks: List[int], cars: int) -> int:\n lo,hi = 0,100*cars*cars\n def repair(time):\n n = cars\n for r in ranks:\n n -= floor... | 2 | You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
[Java/Python 3] Binary Search. | minimum-time-to-repair-cars | 1 | 1 | **Q & A:**\n\n*Q1:* What is the logic behind setting higher bound for binary search as `hi = 1L * maxRank * cars * cars`?\n \n *A1:* The one with highest rank repairing all cars will cost longest time, and there is no way that we could spend more time to finish all jobs. Therefore, we set the worst case of `L * maxRank... | 12 | You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
[C++, Java, Python3] Binary Search + 1 liner | minimum-time-to-repair-cars | 1 | 1 | \n# Intuition\nA mechanic can repair `n` cars in `r * n * n` minutes. So in `mid` minutes a mechanic can repair `n` cars where, `n = sqrt(mid / r)` \nLet\'s assume that the correct answer is `mid` minutes, we can find the number of cars each mechanic can repair in `mid` minutes, then find the find the total number of c... | 62 | You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
Python Binary search with explanation | minimum-time-to-repair-cars | 0 | 1 | # Intuition\n1. Find minimum time within which given number of cars could be repaired.\n2. Count cars that can be repaired by each person within x time. If more cars can be repaired during x time than given number of cars, search for a lesser time.\n3. If lesser cars can be repaired during x time than given number of c... | 1 | You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
Python, binary seach solution | minimum-time-to-repair-cars | 0 | 1 | Question is similar to koko eating bananas, binary search is used to find optimal answer.\n\n# Complexity\n- Time complexity:\n$$O(nlog(r*c^2))$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def repairCars(self, ranks: List[int], cars: int) -> int:\n left, right = 0, min(ranks) * cars * ... | 0 | You are given an integer array `ranks` representing the **ranks** of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank `r` can repair n cars in `r * n2` minutes.
You are also given an integer `cars` representing the total number of cars waiting in the garage to be repaired.
Return _the **... | null |
Easy Python Solution | number-of-even-and-odd-bits | 0 | 1 | \n# Code\n```\nclass Solution:\n def evenOddBit(self, n: int) -> List[int]:\n x=(bin(n)[2:])[::-1]\n even=0\n odd=0\n for i in range(len(x)):\n if i%2==0:\n if x[i]=="1":\n even+=1\n else:\n if x[i]=="1":\n ... | 2 | You are given a **positive** integer `n`.
Let `even` denote the number of even indices in the binary representation of `n` (**0-indexed**) with value `1`.
Let `odd` denote the number of odd indices in the binary representation of `n` (**0-indexed**) with value `1`.
Return _an integer array_ `answer` _where_ `answer ... | null |
Easy Binary | number-of-even-and-odd-bits | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def evenOddBit(self, n: int) -> List[int]:\n x=bin(n)\n s=x[2:]\n s=s[::-1]\n # s=str(n)\n l=list(s)\n ot=[0,0]\n for i in range(len(s)) :\n if(l[i]==\'1\' and (i)%2==1) :\n ot[1]+=1\n elif(l[i]==... | 1 | You are given a **positive** integer `n`.
Let `even` denote the number of even indices in the binary representation of `n` (**0-indexed**) with value `1`.
Let `odd` denote the number of odd indices in the binary representation of `n` (**0-indexed**) with value `1`.
Return _an integer array_ `answer` _where_ `answer ... | null |
[c++ & Python] O(n) soution | number-of-even-and-odd-bits | 0 | 1 | \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(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# C++\n```\nclass Solution {\npublic:\n vector<int> evenOddBit(int n... | 1 | You are given a **positive** integer `n`.
Let `even` denote the number of even indices in the binary representation of `n` (**0-indexed**) with value `1`.
Let `odd` denote the number of odd indices in the binary representation of `n` (**0-indexed**) with value `1`.
Return _an integer array_ `answer` _where_ `answer ... | null |
Python easy 100% beats - 2595. Number of Even and Odd Bits | number-of-even-and-odd-bits | 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`.
Let `even` denote the number of even indices in the binary representation of `n` (**0-indexed**) with value `1`.
Let `odd` denote the number of odd indices in the binary representation of `n` (**0-indexed**) with value `1`.
Return _an integer array_ `answer` _where_ `answer ... | null |
Python 3 || 2 lines, w/ example || T/M: 31 ms / 13.8 MB | number-of-even-and-odd-bits | 0 | 1 | Here\'s the code:\n```\nclass Solution:\n def evenOddBit(self, n: int) -> List[int]: \n evens, odds = int(\'0101010101\',2), int(\'1010101010\',2)\n\n return [(evens&n).bit_count(),(odds&n).bit_count()]\n```\nHere\'s an example:\n```\n Example: n = 545 --> \'0b1000100001\'\n\n ... | 6 | You are given a **positive** integer `n`.
Let `even` denote the number of even indices in the binary representation of `n` (**0-indexed**) with value `1`.
Let `odd` denote the number of odd indices in the binary representation of `n` (**0-indexed**) with value `1`.
Return _an integer array_ `answer` _where_ `answer ... | null |
[Python3] Simple solutions with explanation (string, bit manipulation) | number-of-even-and-odd-bits | 0 | 1 | The logic behind is based on the observation that the least significant group of ones can be determined by checking whether the least significant bit of n is a \'1\' or a \'0\'. Similarly, the next group of ones can be determined by checking the second least significant bit, and so on.\nWe count adjacent groups of ones... | 3 | You are given a **positive** integer `n`.
Let `even` denote the number of even indices in the binary representation of `n` (**0-indexed**) with value `1`.
Let `odd` denote the number of odd indices in the binary representation of `n` (**0-indexed**) with value `1`.
Return _an integer array_ `answer` _where_ `answer ... | null |
Python 3 || 12 lines, iteration and dict || T/M: 100% / 89% | check-knight-tour-configuration | 0 | 1 | ```\nclass Solution:\n def checkValidGrid(self, grid: List[List[int]]) -> bool:\n\n n, d = len(grid), defaultdict(tuple)\n if n < 5: return n == 1\n\n notLegal = lambda x, y : {abs(x[0]-y[0]),\n abs(x[1]-y[1])} != {1,2}\n\n for row, col in product(range(n)... | 4 | There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**.
You are given an `n x n` integer matrix `grid` consisting of distinct integers from the range `[0, n * n - 1]` where `grid[row][col]` indica... | null |
Python easy solution | check-knight-tour-configuration | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def checkValidGrid(self, grid: List[List[int]]) -> bool:\n n = len(grid)\n size = n*n\n directions = [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, -2), (-1, 2)]\n\n def dfs(i, j, curr_size):\n if curr_size == size-1:\n ... | 2 | There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**.
You are given an `n x n` integer matrix `grid` consisting of distinct integers from the range `[0, n * n - 1]` where `grid[row][col]` indica... | null |
Python 2 solutions | Move Thourgh Grid | Save the steps | check-knight-tour-configuration | 0 | 1 | # Method 1\nWe save the index of steps, in our moves array, \nindex0: pos of first step in grid\nindex1: pos of second step in grid\nand so on\n\nThen we check if the moves are valid or not the absolute value of change in direction can be either (1,2) or (2,1)\notherwise its an illegal move \n```\nclass Solution:\n ... | 1 | There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**.
You are given an `n x n` integer matrix `grid` consisting of distinct integers from the range `[0, n * n - 1]` where `grid[row][col]` indica... | null |
Simply put chessbord into an array and simulate knight's movement | check-knight-tour-configuration | 0 | 1 | # Code\n```\ndef checkValidGrid(self, grid: List[List[int]]) -> bool:\n n = len(grid)\n arr = [None] * (n*n)\n for row in range(n):\n for col in range(n):\n arr[grid[row][col]] = (row, col)\n pos = arr[0]\n if pos != (0,0):\n return False\n for i in range(1, n*n):\n a =... | 1 | There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**.
You are given an `n x n` integer matrix `grid` consisting of distinct integers from the range `[0, n * n - 1]` where `grid[row][col]` indica... | null |
Simple BFS Traversal (Python) | check-knight-tour-configuration | 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 | There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**.
You are given an `n x n` integer matrix `grid` consisting of distinct integers from the range `[0, n * n - 1]` where `grid[row][col]` indica... | null |
[Python 3] BFS | Iterative | check-knight-tour-configuration | 0 | 1 | ```\nclass Solution:\n def checkValidGrid(self, grid: List[List[int]]) -> bool:\n n = len(grid)\n \n q = deque( [(0, 0)] )\n res = 0\n \n while q:\n res += 1\n x, y = q.popleft()\n\n for i, j in [ (x + 1, y + 2), (x + 1, y - 2), (x - 1, y + 2... | 4 | There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**.
You are given an `n x n` integer matrix `grid` consisting of distinct integers from the range `[0, n * n - 1]` where `grid[row][col]` indica... | null |
Simple Python3 Solution || =~100% Faster || Commented & Explained || Using simple {Dictionary} | check-knight-tour-configuration | 0 | 1 | \n# Approach\n1. First, create a list of all possible valid knight moves using the given "diff" list.\n2. Then, create a dictionary "new" that maps each cell number to its row and column indices.\n3. Iterate through the cell numbers from 0 to (n*n)-1, and check if the difference between the row and column indices of th... | 1 | There is a knight on an `n x n` chessboard. In a valid configuration, the knight starts **at the top-left cell** of the board and visits every cell on the board **exactly once**.
You are given an `n x n` integer matrix `grid` consisting of distinct integers from the range `[0, n * n - 1]` where `grid[row][col]` indica... | null |
Sorting + Preprocessing + DFS Speed up DFS to squeeze by weird time cutoff | the-number-of-beautiful-subsets | 0 | 1 | Given n <= 20, iterating all possible subsets and checking for violations seem reasonable, but checking each pair for every subset results in a complexity of O(2^n * n ^ 2). Which TLE\'s when n == 19.\n\nSubsequently, we might instead try DFS, which not only prunes many incorrect subsets, when adding an element to exis... | 1 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
Why is this giving wrong answer Python | the-number-of-beautiful-subsets | 0 | 1 | I am testing whether the set is valid for all the subset. I know that it will give TLE But instead it is giving wrong answer what is the problem in the code.\n\n```\nclass Solution:\n def beautifulSubsets(self, nums: List[int], k: int) -> int:\n n = len(nums)\n val = pow(2,n)-1\n res = 0\n ... | 1 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
[C++, Java, Python] Evolve Brute Force to DP | Explained 7 Approaches | the-number-of-beautiful-subsets | 1 | 1 | For every element $x$, we have a choice to take or not take it to make the subset. So, maximum number of possible subsets can be $2^n$.\n\n---\n\n***\u2714\uFE0F Solution - I (Recursion + Backtracking) [Accepted]***\n\nLet\'s say we have to decide to take or not take the element at index $i$. We can recursively make tw... | 63 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
✔💯 DAY 362 || [JAVA/C++/PYTHON] || 100% || EXPLAINED || INTUTION || TC 0(N) | the-number-of-beautiful-subsets | 1 | 1 | \n\n# UPVOTE PLS\n\n# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### \u2022\tThe goal is to count the number of subsets of an integer array nums that satisf... | 3 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
python backtracking | the-number-of-beautiful-subsets | 0 | 1 | # Code\n```\nclass Solution:\n def beautifulSubsets(self, nums: List[int], k: int) -> int:\n n = len(nums)\n output = 0\n \n def dfs(i, ctr):\n nonlocal output\n if i == n:\n if ctr:\n output += 1\n return\n ... | 9 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
[Python 3] Iterative BackTracking | the-number-of-beautiful-subsets | 0 | 1 | ```\nclass Solution:\n def beautifulSubsets(self, nums: List[int], k: int) -> int:\n q = deque( [([], -1)] )\n res = 0\n \n while q:\n cur, idx = q.popleft()\n res += 1\n \n for i in range(idx + 1, len(nums)):\n if nums[i] - k in ... | 9 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
[python] O(n) | the-number-of-beautiful-subsets | 0 | 1 | # Intuition\nwe have to notice that the only elements that affect one another are those that exist in a streak of numbers that differ by k.\n\n# Approach\ni group these numbers together into these streaks, and find the number of subsets of each streak separately. we can then multiply the answers together, since all str... | 4 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
Python || dynamic programming || 90ms | the-number-of-beautiful-subsets | 0 | 1 | 1. First we group `nums` by `n % k`. These buckets are disjoint, we could compute the number of beautiful subsets for each bucket(including empty set), and the product of these numbers minus 1 would be the answer.\n2. For each bucket, use dynamic programming. Here we consider an example, [2,2,2,4,4,6], `k = 2`.\n![imag... | 2 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
Follow Procedure || Easy || Python3 | the-number-of-beautiful-subsets | 0 | 1 | \n```\nclass Solution:\n def beautifulSubsets(self, nums: List[int], k: int) -> int: \n \n def count(n,prev):\n if n == 0:\n return 1 \n ans = 0\n if prev[nums[n-1]-k] == 0 and prev[nums[n-1]+k] == 0:\n prev[nums[n-1]] += 1\n ... | 2 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
Python Backtracking || Explanation | the-number-of-beautiful-subsets | 0 | 1 | # Intuition\nSubset problem, think of using backtracking!\n\n***Why using dictionary instead of set or list?***\nUsing List : When checking numbers in seen, it needs O(n) to check which is inefficient. \n***Then you will think about use set***. However, when you are going yo pop out the number for current dfs level and... | 3 | You are given an array `nums` of positive integers and a **positive** integer `k`.
A subset of `nums` is **beautiful** if it does not contain two integers with an absolute difference equal to `k`.
Return _the number of **non-empty beautiful** subsets of the array_ `nums`.
A **subset** of `nums` is an array that can ... | null |
[Python3] Modulus O(n), Clean & Concise | smallest-missing-non-negative-integer-after-operations | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(value)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findSmallestInteger(self, nums: List[int], value: int) -> int:\n counter = Counter(... | 2 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
[C++ / Python] | | Easy && Concise ✅ | smallest-missing-non-negative-integer-after-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne can observe that the elements of the array can be increased/decreased by k any number of times. We use the modular arithmetic approach to set the value to the elements to maximise the **MEX.**\n\n# Approach\n<!-- Describe your approac... | 2 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
Find Remainder || python3 || simple and concise | smallest-missing-non-negative-integer-after-operations | 0 | 1 | \n```\nclass Solution:\n def findSmallestInteger(self, nums: List[int], value: int) -> int:\n count = Counter() \n for i in nums:\n count[i%value] += 1 \n \n for i in range(len(nums)):\n rem = i % value \n if count[rem] <= 0:\n return i \n ... | 2 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
python3 Solution | smallest-missing-non-negative-integer-after-operations | 0 | 1 | \n```\nclass Solution:\n def findSmallestInteger(self, nums: List[int], value: int) -> int:\n count=Counter(num%value for num in nums)\n stop=0\n for i in range(value):\n if count[i]<count[stop]:\n stop=i\n\n return value*count[stop]+stop \n``` | 1 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
Python solution | smallest-missing-non-negative-integer-after-operations | 0 | 1 | \n# Code\n```\nclass Solution:\n def findSmallestInteger(self, nums: List[int], value: int) -> int:\n # here in order to find the first non negative missing number \n # first calculate the remainder (nums[i]%value) of all element and count the no of occurences of same remainders\n # the maximum ... | 2 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
[Python 3] MOD | Greedy | smallest-missing-non-negative-integer-after-operations | 0 | 1 | ```\nclass Solution:\n def findSmallestInteger(self, nums: List[int], val: int) -> int:\n nums = sorted( [i % val for i in nums] )\n seen = set(nums)\n t = 1\n \n for i in range(len(nums) - 1):\n if nums[i] == nums[i + 1]:\n seen.add(nums[i] + (t * val))\n... | 4 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
Count Moduli | smallest-missing-non-negative-integer-after-operations | 0 | 1 | For an element `n`, we can achieve the minimum non-negative value of `n % value`.\n\nWe can also transform element `n` to `n % value + k * value`. So, we first count moduli we can get from all numbers.\n\nThen, we iterate `i` from zero upwards, and check if we have a modulo (`i % value`) that we can tranform to `i`.\n\... | 51 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
python3 :-) | smallest-missing-non-negative-integer-after-operations | 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` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
✔️ Python3 Solution | Clean & Concise | smallest-missing-non-negative-integer-after-operations | 0 | 1 | # Approach\nSince we can `add or subtract` as many times, first we made all the elements in range(0, value) by taking its `modulus` (simply by adding or subtracting) and store its count in `dp`. \n\nNow we just need to check that `i % v` exist or not in `dp` for making a number equal to i , if it exist then by adding `... | 2 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
Counting % || Linear TC and SC | smallest-missing-non-negative-integer-after-operations | 1 | 1 | # Intuition\nJust count the modulo of all the elements with K.\nnums[i]%value\nFor -ve, add +k too(To make it +ve) since MEX is >= 0.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n int findSmallestInteger(vector<int>&nums, int val) {\n ... | 4 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
Python 3 || 3 lines, Counter, w/explanation || T/M: 952 ms / 33.2 MB | smallest-missing-non-negative-integer-after-operations | 0 | 1 | For the sake of discussion let `nums = [7,7,7,4,6,8]`, `value= 5`, and in particular, `n = 7`. the rules allow us to replace any occurrence of 7 with any element of the set:\n```\n {..., -13, -8, -3, 2, 7, 12, 17, ...},\n```\nwhich can be expressed as `{7%5 + 5*k for integer k }`.\n\nNow, because `nums` has ... | 5 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
fastest in python | smallest-missing-non-negative-integer-after-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a **0-indexed** integer array `nums` and an integer `value`.
In one operation, you can add or subtract `value` from any element of `nums`.
* For example, if `nums = [1,2,3]` and `value = 2`, you can choose to subtract `value` from `nums[0]` to make `nums = [-1,2,3]`.
The MEX (minimum excluded) of an ... | null |
python3 Solution | k-items-with-the-maximum-sum | 0 | 1 | \n```\nclass Solution:\n def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:\n a=2*numOnes+numZeros-k\n return min(k,numOnes,a)\n``` | 1 | There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it.
You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`.
The bag initially contains:
* `numOnes` items with `1`s written on them.
* `numZeroes` items with `0`s written on them.
* `nu... | null |
[C++|Java|Python3] 1-line | k-items-with-the-maximum-sum | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/600a9175b06c42c9713cda8ed8724cb52a9d94ac) for solutions of weekly 338. \n\n**C++**\n```\nclass Solution {\npublic:\n int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {\n return min({k, numOnes, 2*numOnes+numZeros... | 1 | There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it.
You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`.
The bag initially contains:
* `numOnes` items with `1`s written on them.
* `numZeroes` items with `0`s written on them.
* `nu... | null |
One Liner, Simple Intuition. | k-items-with-the-maximum-sum | 1 | 1 | # Intuition\n\nThe Maximum Positive Value we can get is Minimum of k and numOnes.\n\nIf k > numOnes + numZeros, we must select (k - numOnes - numZeros)Negative numbers as we need to select k numbers.\n\n\n# Complexity\n- Time complexity:\n$$O(1)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```Java []\nclass Solution {... | 1 | There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it.
You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`.
The bag initially contains:
* `numOnes` items with `1`s written on them.
* `numZeroes` items with `0`s written on them.
* `nu... | null |
Python | 99% Faster | Easy Solution✅ | k-items-with-the-maximum-sum | 0 | 1 | # Code\n```\nclass Solution:\n def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:\n if numOnes > k:\n return k\n rem = k - numOnes - numZeros\n if rem <= 0:\n return numOnes\n return numOnes - rem\n``` | 3 | There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it.
You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`.
The bag initially contains:
* `numOnes` items with `1`s written on them.
* `numZeroes` items with `0`s written on them.
* `nu... | null |
✔💯DAY 361 || 100% || 0ms || faster || easy || concise & clean code || explained || meme || proof | k-items-with-the-maximum-sum | 1 | 1 | \n\n# Intuition\n##### \u2022\tThe function takes four integer arguments: numOnes, numZeros, numNegOnes, and k.\n##### \u2022\tThe variable onesPicked is initialized to the minimum of k and numOnes. This is... | 2 | There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it.
You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`.
The bag initially contains:
* `numOnes` items with `1`s written on them.
* `numZeroes` items with `0`s written on them.
* `nu... | null |
1 and 2 liner Python | k-items-with-the-maximum-sum | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:\n arr = [1] * numOnes + [0] * numZeros + [-1] * numNegOnes\n return sum(arr[:k])\n```\n```\nclass Solution:\n def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, nu... | 3 | There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it.
You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`.
The bag initially contains:
* `numOnes` items with `1`s written on them.
* `numZeroes` items with `0`s written on them.
* `nu... | null |
Python 3 || 1 line || T/M: 93% / 93% | k-items-with-the-maximum-sum | 0 | 1 | ```\nclass Solution:\n def kItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:\n\n return k if k<= numOnes else numOnes - max(0, k-numOnes-numZeros)\n```\n\n\nI could be wrong, but I think that time complexity is *O*(1) and space complexity is *O*(1).\n | 5 | There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it.
You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`.
The bag initially contains:
* `numOnes` items with `1`s written on them.
* `numZeroes` items with `0`s written on them.
* `nu... | null |
O(1) solution ------------------------------------------------------------->No language | k-items-with-the-maximum-sum | 0 | 1 | # Intuition\nAfter looking the edge cases i found that we have to make k Zero \n# Approach\ngreedy the k until it becomes by going in this way 1,0,-1 \n# Complexity\n- Time complexity: O(1)\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def kItem... | 1 | There is a bag that consists of items, each item has a number `1`, `0`, or `-1` written on it.
You are given four **non-negative** integers `numOnes`, `numZeros`, `numNegOnes`, and `k`.
The bag initially contains:
* `numOnes` items with `1`s written on them.
* `numZeroes` items with `0`s written on them.
* `nu... | null |
python3 Solution | prime-subtraction-operation | 0 | 1 | \n```\nclass Solution:\n def primeSubOperation(self, nums: List[int]) -> bool:\n prime=[True]*1001\n prime[0]=prime[1]=False\n for x in range(2,1001):\n if prime[x]:\n for i in range(x*x,1001,x):\n prime[i]=False\n\n\n prev=0\n for x in ... | 1 | You are given a **0-indexed** integer array `nums` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`.
Return _true if you can make `nums` a str... | null |
[Python Answer🤫🐍] Find all Primes + remove the largest possible prime | prime-subtraction-operation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Find all Primes\n2. Keep a previous_min\n3. Find the next number larger than previous_min by removing all possible primes smaller than n from n. Save it as previous... | 2 | You are given a **0-indexed** integer array `nums` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`.
Return _true if you can make `nums` a str... | null |
Python - O(NlogP), fast | prime-subtraction-operation | 0 | 1 | # Intuition\nConstraints are low, primes upto 1000 can be stored in array and binary searched. \nGo from back and if current item is not smaller then next after\ntry to find smallest prime that can make current smaller then one after it.\nThis can be done in greedy way, until beggining is reached or current problematic... | 4 | You are given a **0-indexed** integer array `nums` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`.
Return _true if you can make `nums` a str... | null |
The most intuitive way to solve the problem(code with comments)!!😶🌫️ | prime-subtraction-operation | 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` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`.
Return _true if you can make `nums` a str... | null |
✔💯DAY 361|| greedy approach | O(n * sqrt(x)) | o(1) | dry run | explained in detailed | meme | prime-subtraction-operation | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### \u2022\tsolution uses a greedy approach to solve the problem. The idea is to use the smallest prime number greater than or equal to each element in the nums vector to reduce that element so that the resulting array is strictly incre... | 11 | You are given a **0-indexed** integer array `nums` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`.
Return _true if you can make `nums` a str... | null |
Python, almost linear solution with explanation | prime-subtraction-operation | 0 | 1 | # Intuition\nFirst we need to know all the primes numbers we can use. They are generated with the sieve of erathosphen which is $O(n \\log log n)$ time and it generates ~$log(n)$ numbers.\n\nNow we go over all the numbers and for each of them we are trying to subtract as big prime as we can (we can find position using ... | 1 | You are given a **0-indexed** integer array `nums` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`.
Return _true if you can make `nums` a str... | null |
Easy python solution | prime-subtraction-operation | 0 | 1 | # Code\n```\nclass Solution:\n def primeSubOperation(self, nums: List[int]) -> bool:\n if len(nums)==1000 and len(set(nums))==1:\n return False\n l = []\n p = []\n for i in range(2,1001):\n for j in range(len(l)):\n if i%l[j]==0:\n b... | 0 | You are given a **0-indexed** integer array `nums` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`.
Return _true if you can make `nums` a str... | null |
Python Solution | Sieve of Erathosnes | Binary Search | Optimal | prime-subtraction-operation | 0 | 1 | Commented code for your convenience\n\n# Complexity\n- Time complexity: $$O(n * log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ for the sieve itself, another $$O(n)$$ for the ```primes``` array\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python ... | 0 | You are given a **0-indexed** integer array `nums` of length `n`.
You can perform the following operation as many times as you want:
* Pick an index `i` that you haven't picked before, and pick a prime `p` **strictly less than** `nums[i]`, then subtract `p` from `nums[i]`.
Return _true if you can make `nums` a str... | null |
🐍Python Solution: Sort+PrefixSum+BinSearch | minimum-operations-to-make-all-array-elements-equal | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n prefix_sum = [nums[0]]\n ans = []\n for i in range(1, len(nums)):\n prefix_sum.append(prefix_sum[-1] + nums[i])\n \n for target in queries... | 1 | You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times:
* **Increase** or **decre... | null |
python3 Solution | minimum-operations-to-make-all-array-elements-equal | 0 | 1 | \n```\nclass Solution:\n def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n n=len(nums)\n prefix=[0]+list(accumulate(nums))\n ans=[]\n for x in queries:\n i=bisect_left(nums,x)\n ans.append(x*(2*i-n)+prefix[n]-2*prefix[i... | 1 | You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times:
* **Increase** or **decre... | null |
[Java/Python 3] Sort, compute prefix sum then binary search. | minimum-operations-to-make-all-array-elements-equal | 1 | 1 | Within each query, for each number in `nums`, if it is less than `q`, we need to deduct it from `q` and get the number of the increment operations; if it is NO less than `q`, we need to deduct `q` from the number to get the number of the decrement operations.\n\nTherfore, we can sort `nums`, then use prefix sum to co... | 12 | You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times:
* **Increase** or **decre... | null |
[C++, Java, Python3] Prefix Sums + Binary Search | minimum-operations-to-make-all-array-elements-equal | 1 | 1 | # Intuition\n* If there are `j` numbers in `nums` that are smaller than `query[i]`, you need to find `query[i] * j - sum(j numbers smaller than query[i])` to find increments required in `nums`\n* If there are `k` numbers in `nums` that are greater than `query[i]`, you need to find `sum(k numbers larger than query[i]) -... | 84 | You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times:
* **Increase** or **decre... | null |
Prefix Sum | minimum-operations-to-make-all-array-elements-equal | 0 | 1 | To make all elements equal, we need to increase elements smaller than query `q`, and decrease larger ones.\n \nWe sort our array first, so we can find index `i` of first element larger than `q`.\n \nThen, we use the prefix sum array to get:\n- sum of smaller elements `ps[i]`.\n- sum of larger elements `ps[-1] - p... | 22 | You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times:
* **Increase** or **decre... | null |
✔💯DAY 361 || 100% || 0MS || EXPLAINED || DRY RUN || MEME | minimum-operations-to-make-all-array-elements-equal | 1 | 1 | # Please Upvote as it really motivates me\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### \u2022\tThe intuition behind this code is to first sort the input array of numbers and the array of queries. Then, for each query, we calculate the prefix sum of all numbers in the input ar... | 5 | You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times:
* **Increase** or **decre... | null |
Easy solution in python-3 | minimum-operations-to-make-all-array-elements-equal | 0 | 1 | # Intuition\nIt can be solved using naive approach in O(n^2) time complexity, which includes one outer for loop for iterating in queries list and the inner outer loop for calculating the sum (as shown) in \'nums\' list. Since, this solution is not optimal, we have to reduce the time complexity further.\n# Naive approac... | 2 | You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times:
* **Increase** or **decre... | null |
NLogN | Easy Solution | minimum-operations-to-make-all-array-elements-equal | 0 | 1 | For each query target in queries, the solution performs binary search on the sorted array nums to find the index i such that nums[i] is the smallest element greater than or equal to the target. It then calculates the sum of the following two parts:\n\nThe total number of operations required to make the first i elements... | 1 | You are given an array `nums` consisting of positive integers.
You are also given an integer array `queries` of size `m`. For the `ith` query, you want to make all of the elements of `nums` equal to `queries[i]`. You can perform the following operation on the array **any** number of times:
* **Increase** or **decre... | null |
Python (Simple Topological Sorting) | collect-coins-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. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | There exists an undirected and unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given an 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. You are also given an array `coins` of size `n` where... | null |
✔💯DAY 361 || 100% || [JAVA/C++/PYTHON] || EXPLAINED || MOST UPVOTED || MEME | collect-coins-in-a-tree | 1 | 1 | \n\n# Please Upvote as it really motivates me\n\n\n# Intuition\n<!-- Describe your first thou... | 26 | There exists an undirected and unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given an 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. You are also given an array `coins` of size `n` where... | null |
Trim Graph | collect-coins-in-a-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Idea was to first prune leaf nodes with no coin and continue this process till no leaf node is possible to remove .\n- Afterwards we can remove two layers of leaves and then at last we return 2*(number of edges still left) as each ed... | 5 | There exists an undirected and unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given an 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. You are also given an array `coins` of size `n` where... | null |
python3 Solution | form-smallest-number-from-two-digit-arrays | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minNumber(self, nums1: List[int], nums2: List[int]) -> int:\n if set(nums1).intersection(set(nums2)):\n return sorted(set(nums1).intersection(set(nums2)))[0]\n\n a=sorted(nums1)[0]\n b=sorted(nums2)[0]\n return min(a*10+b,b*10+a) \n``` | 1 | Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It ca... | null |
Python 3 || 3 lines, set || T/M: 100% / 100% | form-smallest-number-from-two-digit-arrays | 0 | 1 | ```\nclass Solution:\n def minNumber(self, nums1: List[int], nums2: List[int]) -> int:\n \n if mn := min(set(nums1)&set(nums2),\n default = None): return mn # <-- one-digit case\n\n d1, d2 = min(nums1), min(nums2) # <-- two-digit case\n return 10*d1+d... | 4 | Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It ca... | null |
Intersection | form-smallest-number-from-two-digit-arrays | 0 | 1 | \n**Python 3**\n```python\nclass Solution:\n def minNumber(self, n1: List[int], n2: List[int]) -> int:\n common, m1, m2 = set(n1).intersection(n2), min(n1), min(n2)\n return min(common) if common else min(m1, m2) * 10 + max(m1, m2)\n``` | 23 | Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It ca... | null |
[Python3] check intersection | form-smallest-number-from-two-digit-arrays | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/1dc118daa80cfe1161dcee412e7c3536970ca60d) for solutions of biweely 101. \n\n```\nclass Solution:\n def minNumber(self, nums1: List[int], nums2: List[int]) -> int:\n inter = set(nums1) & set(nums2)\n if inter: return min(inter)\n ... | 3 | Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It ca... | null |
BEATS 100 % SUBMISSIONS || Easy solution using Hashmap!! | form-smallest-number-from-two-digit-arrays | 0 | 1 | # Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(N)\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def minNumber(self, nums1: List[int], nums2: List[int]) -> int:\n a=nums1[:]\n a.extend(nums2)\n dic=Counter(a)\n m=max(dic.values())\n ans=[]\n ... | 1 | Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It ca... | null |
Be Greedy! | form-smallest-number-from-two-digit-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf there is a digit that is in both the lists, then that is the answer.\nElse, the concatenation of the two smallest numbers from the list will be the answer. See the code for more clarification.\n\n\n\n# Code\n```\nclass Solution:\n d... | 1 | Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It ca... | null |
simple solution in python | form-smallest-number-from-two-digit-arrays | 0 | 1 | \n```\nclass Solution:\n def minNumber(self, nums1: List[int], nums2: List[int]) -> int:\n nums1.sort()\n nums2.sort()\n for i in nums1:\n if i in nums2:\n return i\n break\n else:\n return min(nums1[0]*10+nums2[0],nums2[0]*10+nums1[0])\... | 2 | Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It ca... | null |
Python | Easy Solution✅ | form-smallest-number-from-two-digit-arrays | 0 | 1 | # Code\n```\nclass Solution:\n def minNumber(self, nums1: List[int], nums2: List[int]) -> int:\n small1, small2, common = min(nums1), min(nums2), set(nums1) & set(nums2)\n output1, output2 = int(f"{small1}{small2}"), int(f"{small2}{small1}")\n if common:\n common = min(common)\n ... | 4 | Given two arrays of **unique** digits `nums1` and `nums2`, return _the **smallest** number that contains **at least** one digit from each array_.
**Example 1:**
**Input:** nums1 = \[4,1,3\], nums2 = \[5,7\]
**Output:** 15
**Explanation:** The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It ca... | null |
Python3 Solution Well Explained (Easy & Clear) | find-the-substring-with-maximum-cost | 0 | 1 | # Intuition:\nThe problem requires finding the maximum cost among all substrings of the given string s. We can find the cost of each character by assigning a value to each character based on whether it is present in the given chars string or not. We can then find the cost of each substring using this assigned value for... | 3 | You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring. The cost of an empty string is considered `0`.
The **value of the character** is defined in the ... | null |
[Python3] Kadane-ish DP | find-the-substring-with-maximum-cost | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/1dc118daa80cfe1161dcee412e7c3536970ca60d) for solutions of biweely 101. \n\n```\nclass Solution:\n def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int:\n mp = dict(zip(chars, vals))\n ans = val = 0 \n ... | 3 | You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring. The cost of an empty string is considered `0`.
The **value of the character** is defined in the ... | null |
Simple Easy Solution | Beats 99% | Accepted🔥🚀🚀 | find-the-substring-with-maximum-cost | 0 | 1 | # Code\n```\nclass Solution:\n def maximumCostSubstring(self, a: str, c: str, x: List[int]) -> int:\n y=[]\n for i in a:\n if i in c: y.append(x[c.index(i)])\n else: y.append(ord(i)-96)\n s=t=0\n for i in y:\n t=max(t,0)\n s=max(s,t)\n ... | 1 | You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring. The cost of an empty string is considered `0`.
The **value of the character** is defined in the ... | null |
Python3 Solution | find-the-substring-with-maximum-cost | 0 | 1 | \n```\nclass Solution:\n def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int:\n nums = []\n c = {i: idx for idx, i in enumerate(chars)}\n \n for i in s:\n if i in c:\n nums.append(vals[c[i]])\n else:\n nums.append(... | 1 | You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring. The cost of an empty string is considered `0`.
The **value of the character** is defined in the ... | null |
Python 3 || 3 lines, w/ example || T/M: 288 ms / 15.7 MB | find-the-substring-with-maximum-cost | 0 | 1 | ```\nclass Solution:\n def maximumCostSubstring(self, s: str, chars: str, vals: List[int])-> int:\n # Example: s = "adcnc"\n # chars = "dn" \n ... | 4 | You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring. The cost of an empty string is considered `0`.
The **value of the character** is defined in the ... | null |
I WILL OPEN IT AT MY OWN RISK(SOME GHOST MAY APPEAR IN SOLUTION) | find-the-substring-with-maximum-cost | 1 | 1 | # Intuition\nTRIPPY\'S BAKCHOD APPROACH\nYou may easily convert into c++ and java\n\n# Approach\nSS Smile and solve\n\n# Complexity\nNothing\n\n# WARNING BEFORE MOVING TO SOL\n\n\n\n![BAKCHODI 3.jpeg... | 8 | You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring. The cost of an empty string is considered `0`.
The **value of the character** is defined in the ... | null |
[Java/Python 3] Kadane Algorithm. | find-the-substring-with-maximum-cost | 1 | 1 | \n\n```java\n public int maximumCostSubstring(String s, String chars, int[] vals) {\n Map<Character, Integer> charToVal = new HashMap<>();\n for (int i = 0; i < vals.length; ++i) {\n charToVal.put(chars.charAt(i), vals[i]);\n }\n int maxCost = 0;\n for (int i = 0, maxCos... | 8 | You are given a string `s`, a string `chars` of **distinct** characters and an integer array `vals` of the same length as `chars`.
The **cost of the substring** is the sum of the values of each character in the substring. The cost of an empty string is considered `0`.
The **value of the character** is defined in the ... | null |
Python 3 || 4 lines, w/comments || T/M: 51% / 96% | make-k-subarray-sums-equal | 0 | 1 | ```\nclass Solution:\n def makeSubKSumEqual(self, arr: List[int], k: int) -> int:\n\n g, d, ans = gcd(k,len(arr)), defaultdict(list), 0\n\n for i, a in enumerate(arr): d[i%g].append(a) # <-- construct a dict of sorted lists\n for i in d:d[i].sort() # ... | 3 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
[Python 3] median and mod GCD | make-k-subarray-sums-equal | 0 | 1 | \n# Code\n```\nclass Solution:\n def makeSubKSumEqual(self, A: List[int], K: int) -> int:\n lA = len(A)\n g = gcd(lA, K)\n retV = 0\n for i in range(g):\n med = int(median(A[i::g]))\n retV += sum(abs(a-med) for a in A[i::g])\n \n return retV ... | 2 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
python3 Solution | make-k-subarray-sums-equal | 0 | 1 | \n```\nclass Solution:\n def makeSubKSumEqual(self, arr: List[int], k: int) -> int:\n n = len(arr)\n g = gcd(n, k)\n ret = 0\n for i in range(g):\n med = int(median(arr[i::g]))\n ret += sum(abs(a-med) for a in arr[i::g])\n \n return ret\n``` | 1 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
[Python 3] Disjoin Set | make-k-subarray-sums-equal | 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 `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
Python || greatest common divisor || O(n log n) | make-k-subarray-sums-equal | 0 | 1 | 1. Consider the example:\n\n`arr[0] + arr[1] + arr[2] + arr[3] = arr[1] + arr[2] + arr[3] + arr[4]`, so `arr[0] = arr[4]`. \nBy similar calculation we have `arr[0] = arr[4] = arr[2]`, `arr[1] = arr[5] = arr[3]`... | 1 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
✔💯DAY 366 || [PYTHON/JAVA/C++] || Explained || Intuition || Algorithm || 100% beats || o(n) & o(1) | make-k-subarray-sums-equal | 1 | 1 | # Please Upvote as it really motivates me\n\n##### \u2022\tThe problem statement is to make the sum of all subarrays of length k equal changing the elements of the array. The approach used in this problem is to group the elements of the array into k subarrays based on their remainder when divided by k. Then, for each s... | 8 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
[Python3] Find Median of Each GCD-Defined Subarray (w/ Examples) | make-k-subarray-sums-equal | 0 | 1 | # First Thought\nAny na\xEFve checking algorithm would not work here as both `k` and `n (= arr.length)` could be up to $$10^5$$.\n\nSo, how can we come up with a better algorithm with improved time complexity?\n\n# Key Intuition\nLet\u2019s first look at a toy example by assuming `k = 3`. Because the problem requires t... | 62 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
Python | Cycle Partition | O(nlogn) | make-k-subarray-sums-equal | 0 | 1 | # Code\n```\nclass Solution:\n def makeSubKSumEqual(self, arr: List[int], k: int) -> int:\n visited = set()\n n = len(arr)\n res = 0\n for i in range(len(arr)):\n if i in visited: continue\n curlist = []\n while i not in visited:\n visited.a... | 4 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
🧒🏻 Explaining like you are five years old !! | make-k-subarray-sums-equal | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n[1,4,1,3]\n\nIt is a Circular Array, What are the possible subarray sums \n```\na. 1 + 4 = 5\nb. 4 + 1 = 5\nc. 1 + 3 = 4\nd. 3 + 1 = 4\n```\n\nFrom above you can understand the num which goes in should be equal t... | 29 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
[Python3] grouping by gcd | make-k-subarray-sums-equal | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/1dc118daa80cfe1161dcee412e7c3536970ca60d) for solutions of biweely 101. \n\n```\nclass Solution:\n def makeSubKSumEqual(self, arr: List[int], k: int) -> int:\n ans = 0 \n g = gcd(len(arr), k)\n for i in range(g): \n ... | 3 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
[Java/Python 3] Divide into sequences such that every two consecutive items's distance is gcd.. | make-k-subarray-sums-equal | 1 | 1 | **Intuition:**\nAll `k`-size subarrays are equal => \n`sum(arr[0,...,k- 1]) == sum(arr[1,...,k])` =>\n`arr[0] == arr[k]`\n\nsimilarly, we can conclude that `arr[i] = arr[i + k]`, further more, `arr` is **circular** array, hence we need stronger condition than `arr[i] = arr[i + k]`: only `gcd(k, arr.length)` to guarant... | 11 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
Python + explanation (why gcd?) | make-k-subarray-sums-equal | 0 | 1 | Right from the beginning: I am not that smart to solve this by myself. It took some time to read the solutions given by others. Specifically [this post](https://leetcode.com/problems/make-k-subarray-sums-equal/solutions/3366442/python3-find-median-of-each-gcd-defined-subarray-w-examples/) by [xil899](https://leetcode.c... | 1 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
[Proof] why use gcd | make-k-subarray-sums-equal | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGiven ```n = len(arr)``` and ```k```, we prove that every ```gcd(n,k)```-th element in ```arr``` should be the same in order to make k-subarray sums equal.\n\n1. Assume ```arr``` is just a regular array. If ```arr[i]+...+arr[i+k-1] = arr[... | 1 | You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of tim... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.