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 |
|---|---|---|---|---|---|---|---|
Ever used pairwise() ?? | find-the-original-array-of-prefix-xor | 0 | 1 | # Intuition\nI have knowledge of builtin modules.\n\n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n return [pref[0]] + [ a ^ b for a, b in pairwise(pref)]\n```\n\n> Comment a better solution than this. | 1 | You are given an **integer** array `pref` of size `n`. Find and return _the array_ `arr` _of size_ `n` _that satisfies_:
* `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`.
Note that `^` denotes the **bitwise-xor** operation.
It can be proven that the answer is **unique**.
**Example 1:**
**Input:** pref = \[5,2,0,3,1\... | null |
Single list-comprehension (without concat or ifs) using walrus operator | find-the-original-array-of-prefix-xor | 0 | 1 | Additional solution to the list, this time using python\'s `walrus operator` which allows us to build the array result in a single list comprehension expression.\nWith the idea of `i++` in other languages, we use the value of `x` and assign it to `last` for the next iteration.\n\nExample:\n```\nlast = 3\nx = 7\nresult ... | 1 | You are given an **integer** array `pref` of size `n`. Find and return _the array_ `arr` _of size_ `n` _that satisfies_:
* `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`.
Note that `^` denotes the **bitwise-xor** operation.
It can be proven that the answer is **unique**.
**Example 1:**
**Input:** pref = \[5,2,0,3,1\... | null |
✅✅OPTIMIZED PYTHON | C++ SOLUTION ✅✅ | find-the-original-array-of-prefix-xor | 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 an **integer** array `pref` of size `n`. Find and return _the array_ `arr` _of size_ `n` _that satisfies_:
* `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`.
Note that `^` denotes the **bitwise-xor** operation.
It can be proven that the answer is **unique**.
**Example 1:**
**Input:** pref = \[5,2,0,3,1\... | null |
2433. Find The Original Array of Prefix Xor | find-the-original-array-of-prefix-xor | 0 | 1 | \n# Code\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n x = []\n res = 0\n for i in range(0,len(pref)):\n if(i==0):\n x.append(pref[i])\n else:\n x.append(pref[i]^pref[i-1])\n return x\n\n \n``` | 1 | You are given an **integer** array `pref` of size `n`. Find and return _the array_ `arr` _of size_ `n` _that satisfies_:
* `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`.
Note that `^` denotes the **bitwise-xor** operation.
It can be proven that the answer is **unique**.
**Example 1:**
**Input:** pref = \[5,2,0,3,1\... | null |
Backward loop, Python - Easy 3 line solution. | find-the-original-array-of-prefix-xor | 0 | 1 | # Intuition\n\nModifying the input array to hold the result.\n\nFor the result, the result array should hold the values when xor-ed upto that index will give the value in the input array.\n\nFor this we can ... | 1 | You are given an **integer** array `pref` of size `n`. Find and return _the array_ `arr` _of size_ `n` _that satisfies_:
* `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`.
Note that `^` denotes the **bitwise-xor** operation.
It can be proven that the answer is **unique**.
**Example 1:**
**Input:** pref = \[5,2,0,3,1\... | null |
Python3 Readable Short solution | find-the-original-array-of-prefix-xor | 0 | 1 | # Intuition\nSame intuition as given in the Hints section\n\n# Approach\nMake an extra array `arr` containing the first element of `prev`. Then append `prev[i] ^ prev[i-1]` to the array in a loop from `1` to `N-1`. \n\n# Complexity\n- Time complexity:\nO(N) as it implements a single for loop from 1 to N-1\n\n- Space co... | 1 | You are given an **integer** array `pref` of size `n`. Find and return _the array_ `arr` _of size_ `n` _that satisfies_:
* `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`.
Note that `^` denotes the **bitwise-xor** operation.
It can be proven that the answer is **unique**.
**Example 1:**
**Input:** pref = \[5,2,0,3,1\... | null |
Python All Out Army Attack | maximum-enemy-forts-that-can-be-captured | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck 2 possible army movements - Forward and Backward\n# Approach\n<!-- Describe your approach to solving the problem. -->\nRaise flag True when encounter 1 and set count to zero\nWhen flag True and station is 0 then increment count by 1... | 1 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
[C++|Java|Python3] scan - one pass | maximum-enemy-forts-that-can-be-captured | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/3ffc910c12ff8c84890fb15351216a0fa85dc3ac) for solutions of biweekly 94. \n\n**Intuition**\nEffectively, this problem can be translated into "finding the number of 0\'s between a 1 and a -1". \n**Implementation**\n**C++**\n```\nclass Solution {\npub... | 31 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
Simple Python Solution | maximum-enemy-forts-that-can-be-captured | 0 | 1 | ```\nclass Solution(object):\n def captureForts(self, forts):\n def solve(arr):\n max_ = 0\n count, flag = 0, False\n for num in arr:\n if num == 1: \n count, flag = 0, True\n elif num == -1: \n max_, count, f... | 6 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
[Python 3] Check left and right | maximum-enemy-forts-that-can-be-captured | 0 | 1 | ```\nclass Solution:\n def captureForts(self, forts: List[int]) -> int:\n res = 0\n \n for i in range(len(forts)):\n if forts[i] == 1:\n curr = i\n \n for l in range(i - 1, -1, -1):\n if forts[l] == 1:\n ... | 1 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
python easy solution beats 91% | maximum-enemy-forts-that-can-be-captured | 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)$$ --... | 2 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
Python 2 pointer | maximum-enemy-forts-that-can-be-captured | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n 2 pointer\n move left pointer to right when right is not zero\n update max result when length of left to right window size > result\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time c... | 1 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
Python | O(n) | maximum-enemy-forts-that-can-be-captured | 0 | 1 | # Approach\n- So basically we just have to calculate the number of maximum continuous zerows between -1 and 1.\n- first we will find the first non zero element.\n- now we will start iteration through the array while calculating max zeros between 1 and -1.\n- every time we will find a zero we will count it and if we fin... | 1 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
⬆️🔥✅ 100% | 0MS | 3 LINES | EASY | EXPLAINED | PROOF 🔥⬆️✅ | maximum-enemy-forts-that-can-be-captured | 1 | 1 | # upvote pls\n\n# calculate max distance btw 1 to -1 & viceversa \n<!-- Describe your approach to solving the problem. -->\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.... | 2 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
Python3 solution | maximum-enemy-forts-that-can-be-captured | 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 `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
Python 3 || 2-6 lines, w/ explanation and example || T/M: 29 ms / 13.8 MB | maximum-enemy-forts-that-can-be-captured | 0 | 1 | Here\'s the plan:\n- First, we build a list of tuples with `itertools.groupby`. First element of each pair is the integer of the group(-1,0,or 1), and the second element is the length of the string.\n1. Second, we iterate through this list checking for whether `{grp[i-1][0], grp[i+1][0]} == {-1,1}`. If so, then `grp[i]... | 4 | You are given a **0-indexed** integer array `forts` of length `n` representing the positions of several forts. `forts[i]` can be `-1`, `0`, or `1` where:
* `-1` represents there is **no fort** at the `ith` position.
* `0` indicates there is an **enemy** fort at the `ith` position.
* `1` indicates the fort at the... | null |
Easy Python Solution | reward-top-k-students | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate an hashmap to store the point of each student.\n\n# Code\n```\nclass Solution:\n def topStudents(self, positive_feedback: List[str], negative_feedback: List[str], report: List[str], student_id: List[int], k: int) -> List[int]:\n... | 3 | You are given two string arrays `positive_feedback` and `negative_feedback`, containing the words denoting positive and negative feedback, respectively. Note that **no** word is both positive and negative.
Initially every student has `0` points. Each positive word in a feedback report **increases** the points of a stu... | null |
Python 3 || 4 lines, nsmallest || T/M: 82% / 70% | reward-top-k-students | 0 | 1 | ```\nclass Solution:\n def topStudents(self, positive_feedback: List[str], negative_feedback: List[str], report: List[str], student_id: List[int], k: int) -> List[int]:\n\n d = [0]*len(student_id)\n\n pSet,nSet = set(positive_feedback), set(negative_feedback)\n\n for i,s in enumerate(report):\n ... | 4 | You are given two string arrays `positive_feedback` and `negative_feedback`, containing the words denoting positive and negative feedback, respectively. Note that **no** word is both positive and negative.
Initially every student has `0` points. Each positive word in a feedback report **increases** the points of a stu... | null |
✅ [Python] code with proper comments and approach explained. | reward-top-k-students | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Convert the both positive and negative feedback to a set for faster accessing i.e. in O(1) time.\n2. Then iterating in every string of the report list and calculating the points and store the points in the dictionary.\n3. Sort the dictionary in dec... | 4 | You are given two string arrays `positive_feedback` and `negative_feedback`, containing the words denoting positive and negative feedback, respectively. Note that **no** word is both positive and negative.
Initially every student has `0` points. Each positive word in a feedback report **increases** the points of a stu... | null |
[Python 3] (Updated for new test cases) HashMap | Sorting | reward-top-k-students | 0 | 1 | ```\nclass Solution:\n def topStudents(self, positive_feedback: List[str], negative_feedback: List[str], report: List[str], stu_id: List[int], k: int) -> List[int]:\n hm = Counter()\n \n pos = set(positive_feedback)\n neg = set(negative_feedback)\n \n for rep in range(len(re... | 1 | You are given two string arrays `positive_feedback` and `negative_feedback`, containing the words denoting positive and negative feedback, respectively. Note that **no** word is both positive and negative.
Initially every student has `0` points. Each positive word in a feedback report **increases** the points of a stu... | null |
EASY SOLUTION USING MAX HEAP AND HASH SET!! | reward-top-k-students | 0 | 1 | # Intuition\nTo make the max heap according to the score of each student!!\n\n# Approach\n-> Fistly we will convert the both positive and negative array into hash set, so that we can find the result in O(1) time.\n\n-> Then we will start traversing the student_id array and for each student[i] we will go for report[i] w... | 1 | You are given two string arrays `positive_feedback` and `negative_feedback`, containing the words denoting positive and negative feedback, respectively. Note that **no** word is both positive and negative.
Initially every student has `0` points. Each positive word in a feedback report **increases** the points of a stu... | null |
Tedious | reward-top-k-students | 0 | 1 | Just bunch of data manipulation. Looks a bit better in Python.\n\n**Python 3**\n```python\nclass Solution:\n def topStudents(self, pos_feed: List[str], neg_feed: List[str], report: List[str], student_id: List[int], k: int) -> List[int]:\n pos, neg, score_id = set(pos_feed), set(neg_feed), []\n for r, i... | 16 | You are given two string arrays `positive_feedback` and `negative_feedback`, containing the words denoting positive and negative feedback, respectively. Note that **no** word is both positive and negative.
Initially every student has `0` points. Each positive word in a feedback report **increases** the points of a stu... | null |
Python | O(logn) Runtime | With explanation | minimize-the-maximum-of-two-arrays | 0 | 1 | # Intuition\n1st Insight: Seeing that uniqueCnt1 and uniqueCnt2 are order of $$10^9$$ and our answer is also potentially of that magnitude, we might think to consider a logarithmic solution such as binary search.\n\n2nd Insight: It isn\'t obvious how to find the minimum maximum value across all arrays satisfying the co... | 1 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
Python 3 || 7 lines, iteration, w/ explanation & example || T/M: 99.3% / 100% | minimize-the-maximum-of-two-arrays | 0 | 1 | Here\'s the plan:\nSuppose, for example: \n`divisor1 = 2, uniqueCnt1 = 11`, and `divisor2 = 3, uniqueCnt2 = 2`\n\nWe need at least 13 elements in total in the two groups. Four elements would be eligible for either\ngroup (`[1,5,7,11]`), two for Group1 only (`[3,9]`), four for Group2 only (`[2,4,8,10]`), and two for nei... | 3 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
python 3 Solution 7-lines,O(N),O(N) | minimize-the-maximum-of-two-arrays | 0 | 1 | \n```\nclass Solution:\n def minimizeSet(self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int) -> int:\n f=lambda x:(x+abs(x))//2\n n,prev,d=uniqueCnt1+uniqueCnt2,0,lcm(divisor1,divisor2)\n while n>prev:\n prev=n\n l1,l2=n//divisor2-n//d,n//divisor1-n//d\n ... | 1 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
[C++|Java|Python3] binary search | minimize-the-maximum-of-two-arrays | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/3ffc910c12ff8c84890fb15351216a0fa85dc3ac) for solutions of biweekly 94. \n\n**Intuition**\nHere, we can use binary search to look for the tightest upper bound. Given a value `x`, the condition for `x` to be a valid upper bound is that \n1) there is... | 19 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
NO Binary Search Solution [TOP 100% runtime&memory] | minimize-the-maximum-of-two-arrays | 0 | 1 | # Apporach\n<!-- Describe your approach to solving the problem. -->\nLet\'s $$f(u, d)$$ is the minimum possible maximum integer in an array of size $$u$$ that are not divisible by divisor $$d$$. There will be numbers from 1 to u, except that are divisible by $$d$$, and some numbers that are bigger than $$u$$.\n\nSo, we... | 14 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
Beginer Friendly | minimize-the-maximum-of-two-arrays | 0 | 1 | # Code\n```python []\nclass Solution:\n def minimizeSet(self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int) -> int:\n l, r = 0, 1 << 32 - 1\n\n lcm = math.lcm(divisor1, divisor2)\n def valid(num):\n div1 = num - num // divisor1\n if div1 < uniqueCnt1: \n ... | 6 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
Python3 | Binary search | minimize-the-maximum-of-two-arrays | 0 | 1 | # Python | Binary Search\nWe can think about `Given n, can we select some numbers from 1~n to have uniqueCnt1 numbers in arr1 and uniqueCnt2 in arr2?`\nWe can check by this way:\nFirst, we put in `arr1` the numbers that can fit in `arr1` but cannot fit in `arr2`, and put in `arr2` the numbers that can fit in `arr2` but... | 3 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
A simple solution that is readable and has comments. | minimize-the-maximum-of-two-arrays | 0 | 1 | # Approach\nStep 1: Identify logic to determine if a solution is possible for some number "n".\nStep 2: Find "n". \n\n# Complexity\n- Time complexity: O(logN)\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimizeSet(self, d1: int, d2: int, ... | 0 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
Binary search, counting with the inclusion/exclusion principle | minimize-the-maximum-of-two-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are 3 counts of interest that can be used to check if a given bound num provides enough space to cover the range while within the constraints. \n1. c1: how many are divisible by divisor1\n2. c2: how many are divisible by divisor2\n3... | 0 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
EZ understand, two lines of codes with full explanation | minimize-the-maximum-of-two-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNote that for each bunch of divisor size integers, there are divisor size - 1 integers do not divide the divisor, \nIf no integers will be candidate for both array, the Maximum for each array can be computed with following equation:\n`uni... | 0 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
python super easy lower bound (binary search) | minimize-the-maximum-of-two-arrays | 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 | We have two arrays `arr1` and `arr2` which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
* `arr1` contains `uniqueCnt1` **distinct** positive integers, each of which is **not divisible** by `divisor1`.
* `arr2` contains `uniqueCnt2` **distinct**... | null |
Python | Easy Solution | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | # Code\n```\nclass Solution:\n def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:\n n = len(words)\n # moving right\n moveright = 0\n flag = False\n for i in range(startIndex,len(words)+startIndex):\n if words[(i+1)%n] == target:\n ... | 2 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
[Python3] Two simultaneous pointers to different sides | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | Modulo operation for negative numbers in python works like: `(i + l) % l if i < 0`\n```python3 []\nclass Solution:\n def closetTarget(self, words: List[str], target: str, start: int) -> int:\n ln = len(words)\n for k in range(ln//2 + 1):\n l, r = start - k, start + k\n if words[l ... | 1 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
python - easy understanding | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | # Intuition\nMy first instinct was that It is circular, so in terms of calculation, I can\'t just count positive numbers, I have to count negative numbers too.\nIf I want to follow the intuitive way of writing in Python, I would just cut it into two parts, the front and the back, and then reverse them to form a new var... | 1 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
[Python] Easy Fast Solution With Explanation | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | # Intuition\n\n$\\cdot$ Target can appear more than once\n$\\cdot$ Each target has two possible shortest distance i.e. left or right\n$\\cdot$ Instead of infinite circle loop think of finite segment of concatenated arrays\n\n# Approach\nLoop through array to find each target. Then determine if target index is above or ... | 2 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
shortest-distance-to-target-string-in-a-circular-array | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | # Code\n```javascript []\n/**\n * @param {string[]} words\n * @param {string} target\n * @param {number} startIndex\n * @return {number}\n */\nvar closetTarget = function(words, t, s) {\n if(!words.includes(t)){\n return -1\n }\n let a = words.concat(words.slice(0,s+1));\n a = a.reverse();\n let l... | 1 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
[Python 3] Check left and right | Brute Force | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | ```\nclass Solution:\n def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:\n if target not in words:\n return -1\n \n words = words + words\n \n n = len(words)\n r = l = startIndex\n res = inf\n \n while words[l] != ... | 2 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
Python 3 || 7 lines, two loops, one pass || T/M: 42 ms / 13.9 MB | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | ```class Solution:\n def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:\n\n n = len(words)\n\n for left in range(n):\n if words[(startIndex+left)%n ] == target: break\n else: return -1 \n\n for right in range(n):\n if words[(startIndex-... | 10 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
Simple short Python solution | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:\n for i in range(0, len(words)):\n if target in [words[(startIndex - i) % len(words)], words[(startIndex + i) ... | 1 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
Python | Easy Solution✅ | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:\n if words[startIndex] == target:\n return 0\n\n for index in range(len(words)):\n if words[(startIndex+index) % len(words)] == target or words[(startIndex-index) %... | 6 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
8-Line Python Code | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 4 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
Simple Python Solution - O(N) - 3 lines of code | shortest-distance-to-target-string-in-a-circular-array | 0 | 1 | \n# Code\n```\nclass Solution:\n def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:\n if words[startIndex] == target:\n return 0\n \n for i in range(1, len(words)):\n if words[(startIndex-i) % len(words)] == target or words[(startIndex+i) % len(w... | 2 | You are given a **0-indexed** **circular** string array `words` and a string `target`. A **circular array** means that the array's end connects to the array's beginning.
* Formally, the next element of `words[i]` is `words[(i + 1) % n]` and the previous element of `words[i]` is `words[(i - 1 + n) % n]`, where `n` is... | null |
[python3] sliding window sol for reference | take-k-of-each-character-from-left-and-right | 0 | 1 | The intuition for the solution is below. \n\nlets assume that there are ta,tb and tc chars of a,b and c in the string, then we are looking for the longest window where number of a\'s is <= ta-a, b\'s is <= tb - b and c\'s is <= tc - c. \n\n```\nclass Solution:\n def takeCharacters(self, s: str, k: int) -> int:\n ... | 1 | You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.
Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each characte... | null |
[Python 3] Sliding Window | take-k-of-each-character-from-left-and-right | 0 | 1 | **INTUITION** :\n\nwe have to find length of **largest window/substring** where we have\n* occurences of \'a\' in window/substring **<=** (total occurences of \'a\' in s) - k\n* occurences of \'b\' in window/substring **<=** (total occurences of \'b\' in s) - k\n* occurences of \'c\' in window/substring **<=** (tota... | 9 | You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.
Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each characte... | null |
Sliding Window by adding `S` to itself | take-k-of-each-character-from-left-and-right | 0 | 1 | # Intuition\nSliding Window by adding `s` to itself. After appending `s` to itself there will be 3 exit points.\n\n1. at the beginning of the string\n2. at the end of the string\n3. at the middle of the string ( since we added `s` to itself )\n\nthese are represented by `exits` variable in code below\n\n\n\n# Approach\... | 1 | You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.
Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each characte... | null |
[Python] clean 12 line sliding window solution with explanation | take-k-of-each-character-from-left-and-right | 0 | 1 | **Explanation**\n\nInstead of taking `k` of each character from left and right, we take at most `count(c) - k` of each character from middle.\n\nFor Example 1, `s = "aabaaaacaabc"` with `k = 2`:\n- we have `freq = {\'a\': 8, \'b\': 2, \'c\': 2}`\n- this converts to `limits = freq - k = {\'a\': 6, \'b\': 0, \'c\': 0}`\n... | 113 | You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.
Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each characte... | null |
Python 😎😎😎 || Explained with comments || clever? | take-k-of-each-character-from-left-and-right | 0 | 1 | # Code\n```\nclass Solution:\n def takeCharacters(self, s: str, k: int) -> int:\n # make a duplicate and count\n ss = s*2\n freq = {\'a\': s.count(\'a\'), \'b\': s.count(\'b\'), \'c\': s.count(\'c\')}\n\n if any([v < k for v in freq.values()]): # using any() to check if impossible\n ... | 1 | You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.
Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each characte... | null |
[python3] time: O(n) & space: O(1) | take-k-of-each-character-from-left-and-right | 0 | 1 | # Code\n```\nclass Solution:\n def takeCharacters(self, s: str, k: int) -> int:\n a = s.count(\'a\') - k\n b = s.count(\'b\') - k\n c = s.count(\'c\') - k\n if any(i<0 for i in [a, b, c]):\n return -1\n dict = defaultdict(int)\n left = length = res = 0\n fo... | 1 | You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.
Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each characte... | null |
Python 3 || 12 lines, sliding window || T/M: 291 ms / 14.8 MB | take-k-of-each-character-from-left-and-right | 0 | 1 | ```\nclass Solution:\n def takeCharacters(self, s: str, k: int) -> int:\n\n d = Counter(s)\n if min(d.values()) < k: return -1\n\n d[\'a\']-= k ; d[\'b\']-= k ; d[\'c\']-= k \n\n ct = {\'a\':0, \'b\':0, \'c\':0}\n\n n, left, ans = len(s)-1, 0, inf\n\n for right, ch in enumer... | 5 | You are given a string `s` consisting of the characters `'a'`, `'b'`, and `'c'` and a non-negative integer `k`. Each minute, you may take either the **leftmost** character of `s`, or the **rightmost** character of `s`.
Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each characte... | null |
[C++, Java, Python] Binary Search and sorting | maximum-tastiness-of-candy-basket | 1 | 1 | \n\n# Intuition\nWe can use binary search to search the minimum difference. Since range is `0 - 10^9`, Time complexity will be `n * log(10 ^ 9) = 10 ^ 5 * 30`. This should be within constraints.\n\n# Approach\n* Sort `prices`\n* Run a binary search in the range `0 to 10 ^ 9`\n* The check function iterates over the arra... | 65 | You are given an array of positive integers `price` where `price[i]` denotes the price of the `ith` candy and a positive integer `k`.
The store sells baskets of `k` **distinct** candies. The **tastiness** of a candy basket is the smallest absolute difference of the **prices** of any two candies in the basket.
Return ... | null |
[Python3] | Sorting + Binary Search | maximum-tastiness-of-candy-basket | 0 | 1 | ```\nclass Solution:\n def maximumTastiness(self, price: List[int], k: int) -> int:\n if k == 0:\n return 0\n price.sort()\n def isValid(num):\n n = len(price)\n cnt = 1\n diff = price[0] + num\n for i in range(1,n):\n if pric... | 8 | You are given an array of positive integers `price` where `price[i]` denotes the price of the `ith` candy and a positive integer `k`.
The store sells baskets of `k` **distinct** candies. The **tastiness** of a candy basket is the smallest absolute difference of the **prices** of any two candies in the basket.
Return ... | null |
Python | Binary Search on answers | O(NlogN + NlogM) | maximum-tastiness-of-candy-basket | 0 | 1 | # Intuition\nIf we sort an array it becomes clear that the first $$n-1$$ minimal differences lie between neighbors (there is a less difference with neighbor than with an element next to neighbor). We can use that observation to built some backet of candies. How to decide which candies we need to put in backet? What if ... | 4 | You are given an array of positive integers `price` where `price[i]` denotes the price of the `ith` candy and a positive integer `k`.
The store sells baskets of `k` **distinct** candies. The **tastiness** of a candy basket is the smallest absolute difference of the **prices** of any two candies in the basket.
Return ... | null |
Easy to understand Python with full explanation, clear variable naming, and inline comments | maximum-tastiness-of-candy-basket | 0 | 1 | # Intuition\nThis problem presents itself as a max-min problem. In order to find the answer, we need to find the minimum absolute difference of candy prices in any k sized basket, and then find the maximum amongst those minimum values calculated.\n\n# Approach\nFirstly, we can sort the input array. This provides a usef... | 1 | You are given an array of positive integers `price` where `price[i]` denotes the price of the `ith` candy and a positive integer `k`.
The store sells baskets of `k` **distinct** candies. The **tastiness** of a candy basket is the smallest absolute difference of the **prices** of any two candies in the basket.
Return ... | null |
[Python3] [DP] Simple solution with steps and intuition | number-of-great-partitions | 0 | 1 | #### Intuition\nNotice in the problem description that k < 1000 while number of subsets of the array can go as high as 2^1000, instead of thinking from the perspextive of iterating through each subset, we should think about how to use this "k" to resolve the problem.\n#### Steps\n\n- Define a sub-problem: \n`Find the t... | 35 | You are given an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.
Return _the number of **di... | null |
[Python] DP O(n*k) - Video Solution | number-of-great-partitions | 0 | 1 | I have explained this [here](https://youtu.be/CQtLbU8x_vI).\n\n**Time:** `O(N.K)`\n\n**Space:** `O(N.K)`\n\n```\nclass Solution:\n def countPartitions(self, nums: List[int], k: int) -> int:\n n = len(nums)\n \n @cache\n def dfs(i, cur_sum):\n if i==n:\n return 1\... | 5 | You are given an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.
Return _the number of **di... | null |
[C++ || Java || Python] Direct approach to solve a deformed 01 knapsack problem | number-of-great-partitions | 0 | 1 | > **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n\n> **Vote welcome if this solution helped.**\n---\n\n# Intuition\n1. Step by step, each number must belong to a group. The sums of two grou... | 3 | You are given an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.
Return _the number of **di... | null |
Python Knapsack beats 100% | number-of-great-partitions | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt says the number can grow really big, which leads me thinking about DP, and from there goes to Knapsack problem.\n\nAnd given the constraint `1 <= nums.length, k <= 1000`, I guess this is a 2 dimensional dp (with 2 loops).\n\n# Approach... | 2 | You are given an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.
Return _the number of **di... | null |
Memoization in Python, fewer than 10 lines | number-of-great-partitions | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nI am lazy so I implement the solution in memoization instead of bottom-up dynamic programming. In this simple 3-D dynamic programming, every state is defined by `(i, s1, s2)`, where i is the current number `nums[i]` to consider, `s1` and `s2` are the ... | 0 | You are given an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.
Return _the number of **di... | null |
Python (Simple DP) | number-of-great-partitions | 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 an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.
Return _the number of **di... | null |
[Python3] Count the non-great partitions | number-of-great-partitions | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs k is small(<=1000), we count the non-great partitions, which means to store all subsequence count no more than target. Counting the great partitions will get TLE. All partitions is *2 * (2 * (n - 1) - 1)*.\n\n# Code\n```\nfrom math imp... | 0 | You are given an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.
Return _the number of **di... | null |
Direct Counting DP O(NK) | number-of-great-partitions | 0 | 1 | # Approach\nThis solution does not count complement subsets like other solutions, and instead count the desired subsets directly with a DP recursive function and memoization.\n\n```dp(index, curr_sum)``` represents state of deciding for whether or not to add ```index```th number to the first group knowing that the firs... | 0 | You are given an array `nums` consisting of **positive** integers and an integer `k`.
**Partition** the array into two ordered **groups** such that each element is in exactly **one** group. A partition is called great if the **sum** of elements of each group is greater than or equal to `k`.
Return _the number of **di... | null |
simplest way in python!! | count-the-digits-that-divide-a-number | 0 | 1 | \n# Code\n```\nclass Solution:\n def countDigits(self, num: int) -> int:\n if len(str(num)) == 1:\n return 1\n else:\n ans = 0\n for i in str(num):\n if num % int(i) == 0:\n ans += 1\n return ans\n``` | 1 | Given an integer `num`, return _the number of digits in `num` that divide_ `num`.
An integer `val` divides `nums` if `nums % val == 0`.
**Example 1:**
**Input:** num = 7
**Output:** 1
**Explanation:** 7 divides itself, hence the answer is 1.
**Example 2:**
**Input:** num = 121
**Output:** 2
**Explanation:** 121 is... | null |
python3 code | count-the-digits-that-divide-a-number | 0 | 1 | # Intuition\nThe method first creates a deep copy of the input integer using the deepcopy function from the copy module. It then initializes an empty list l, a variable count1 to zero.\n\nThe method then enters a while loop that continues until num is greater than zero. In each iteration, it computes the remainder of n... | 1 | Given an integer `num`, return _the number of digits in `num` that divide_ `num`.
An integer `val` divides `nums` if `nums % val == 0`.
**Example 1:**
**Input:** num = 7
**Output:** 1
**Explanation:** 7 divides itself, hence the answer is 1.
**Example 2:**
**Input:** num = 121
**Output:** 2
**Explanation:** 121 is... | null |
Python code for counting the digits that divide a number (TC: O(n) & SC: O(1)) | count-the-digits-that-divide-a-number | 0 | 1 | \n\n# Complexity\n- Time complexity:\nO(d), d is the number of digits.\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def countDigits(self, num: int) -> int:\n count = 0\n for i in str(num):\n if int(num)%int(i) == 0:\n count = count+1\n return count\n``... | 1 | Given an integer `num`, return _the number of digits in `num` that divide_ `num`.
An integer `val` divides `nums` if `nums % val == 0`.
**Example 1:**
**Input:** num = 7
**Output:** 1
**Explanation:** 7 divides itself, hence the answer is 1.
**Example 2:**
**Input:** num = 121
**Output:** 2
**Explanation:** 121 is... | null |
Python | Easy Solution✅ | count-the-digits-that-divide-a-number | 0 | 1 | # Code\u2705\nSolution 1:\n```\nclass Solution:\n def countDigits(self, num: int) -> int:\n count = [digit for digit in str(num) if num % int(digit) == 0]\n return len(count)\n```\nSolution 2:\n```\nclass Solution:\n def countDigits(self, num: int) -> int:\n count = 0\n for digit in st... | 4 | Given an integer `num`, return _the number of digits in `num` that divide_ `num`.
An integer `val` divides `nums` if `nums % val == 0`.
**Example 1:**
**Input:** num = 7
**Output:** 1
**Explanation:** 7 divides itself, hence the answer is 1.
**Example 2:**
**Input:** num = 121
**Output:** 2
**Explanation:** 121 is... | null |
simplest solution in python | count-the-digits-that-divide-a-number | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given an integer `num`, return _the number of digits in `num` that divide_ `num`.
An integer `val` divides `nums` if `nums % val == 0`.
**Example 1:**
**Input:** num = 7
**Output:** 1
**Explanation:** 7 divides itself, hence the answer is 1.
**Example 2:**
**Input:** num = 121
**Output:** 2
**Explanation:** 121 is... | null |
[Easy And Concise] | | Beats 93.43% ✅ | distinct-prime-factors-of-product-of-array | 0 | 1 | \n# Complexity\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Time complexity: **O(n * \u221An)**\n\n- Space complexity: **O(k)** *{k is distinct primes}*\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n``` C++ []\nclass Solution {\nprivate:\n void findprimefactors(int n){\n for(int i ... | 2 | Given an array of positive integers `nums`, return _the number of **distinct prime factors** in the product of the elements of_ `nums`.
**Note** that:
* A number greater than `1` is called **prime** if it is divisible by only `1` and itself.
* An integer `val1` is a factor of another integer `val2` if `val2 / val... | null |
sieve || python | distinct-prime-factors-of-product-of-array | 0 | 1 | # Intuition and Approach\n* use sieve to find the prime numbers between 1 to 1000.\n* then return the no. of prime no. among them which can perfeclty divide any no. of the given list\n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:o(1)\n\n# Code\n```\nclass Solution:\n p=[]\n def __init__(self):\n ... | 1 | Given an array of positive integers `nums`, return _the number of **distinct prime factors** in the product of the elements of_ `nums`.
**Note** that:
* A number greater than `1` is called **prime** if it is divisible by only `1` and itself.
* An integer `val1` is a factor of another integer `val2` if `val2 / val... | null |
[ Python ] ✅✅ Simple Python Solution Using Set | 100 % faster🥳✌👍 | distinct-prime-factors-of-product-of-array | 0 | 1 | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 351 ms, faster than 100.00% of Python3 online submissions for Distinct Prime Factors of Product of Array.\n# Memory Usage: 15.2 MB, less than 100.00% of Python3 online submissions for Distinct Prime Factors of Pr... | 12 | Given an array of positive integers `nums`, return _the number of **distinct prime factors** in the product of the elements of_ `nums`.
**Note** that:
* A number greater than `1` is called **prime** if it is divisible by only `1` and itself.
* An integer `val1` is a factor of another integer `val2` if `val2 / val... | null |
Python | O(nsqrt(n)) | distinct-prime-factors-of-product-of-array | 0 | 1 | # Complexity\n- Time complexity: O(n*sqrt(n))\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def distinctPrimeFactors(self, nums: List[int]) -> int: \n def prime(a):\n ans = set() \n for i in range (len(a)) :\n if a[i] == 2:\n ans... | 1 | Given an array of positive integers `nums`, return _the number of **distinct prime factors** in the product of the elements of_ `nums`.
**Note** that:
* A number greater than `1` is called **prime** if it is divisible by only `1` and itself.
* An integer `val1` is a factor of another integer `val2` if `val2 / val... | null |
python3 solution ||100% Faster Solution | distinct-prime-factors-of-product-of-array | 0 | 1 | \n```\nclass Solution:\n def distinctPrimeFactors(self, nums: List[int]) -> int:\n s=set()\n for x in nums:\n t=2\n while t*t<=x:\n while x%t==0:\n x//=t\n s.add(t)\n\n t+=1\n\n if x>1:\n ... | 2 | Given an array of positive integers `nums`, return _the number of **distinct prime factors** in the product of the elements of_ `nums`.
**Note** that:
* A number greater than `1` is called **prime** if it is divisible by only `1` and itself.
* An integer `val1` is a factor of another integer `val2` if `val2 / val... | null |
Easy Python solution with proper comments. | distinct-prime-factors-of-product-of-array | 0 | 1 | # Intuition\nThe approch is to calculate all prime factors of every number of nums and the adding the factors to a set for getting unique prime factors.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n*k)\n\n- Space complexity:\n<!-- Add your space complexity here,... | 2 | Given an array of positive integers `nums`, return _the number of **distinct prime factors** in the product of the elements of_ `nums`.
**Note** that:
* A number greater than `1` is called **prime** if it is divisible by only `1` and itself.
* An integer `val1` is a factor of another integer `val2` if `val2 / val... | null |
[Python3] Greedy O(N) Solution, Clean & Concise | partition-string-into-substrings-with-values-at-most-k | 0 | 1 | # Approach\nWe scan all digits in `s` from left to right, and add 1 to `ans` whenever the current value of the segment exceeds `k`.\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# Cod... | 4 | You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.
A partition of a string `s` is called **good** if:
* Each digit of `s` is part of **exactly** one substring.
* The value of each substring is less than or equal to `k`.
Return _the **minimum** number of substrings in a **good** p... | null |
Beats 100% | Explanation | O(n) | CodeDominar Solution | partition-string-into-substrings-with-values-at-most-k | 0 | 1 | # Code\n```\nclass Solution:\n def minimumPartition(self, s: str, k: int) -> int:\n # Initialize a temporary string to store the current substring\n tmp = \'\'\n \n # Initialize a counter for the number of substrings\n cnt = 0\n \n # Iterate through the characters in ... | 2 | You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.
A partition of a string `s` is called **good** if:
* Each digit of `s` is part of **exactly** one substring.
* The value of each substring is less than or equal to `k`.
Return _the **minimum** number of substrings in a **good** p... | null |
Two Pointers | Explanation | partition-string-into-substrings-with-values-at-most-k | 0 | 1 | # Intuition\n\n1. Calculate the length of number `k` - > `l`\n2. Go though `s` from end to start\n a. `k` can be bigger then a number with the same length and 100% bigger then a number with `l-1` length\n b. Convert last `l` symbols to number and compare to `k`\n c. `l-1` can be equal to `0` which means no goo... | 1 | You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.
A partition of a string `s` is called **good** if:
* Each digit of `s` is part of **exactly** one substring.
* The value of each substring is less than or equal to `k`.
Return _the **minimum** number of substrings in a **good** p... | null |
[python3] Greedy solution for ref | partition-string-into-substrings-with-values-at-most-k | 0 | 1 | ```\nclass Solution:\n def minimumPartition(self, s: str, k: int) -> int:\n rolling = ""\n ans = 0\n \n for i in s: \n if int(rolling + i) > k and (rolling and int(rolling) <= k):\n rolling = i\n ans += 1\n else: \n ... | 1 | You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.
A partition of a string `s` is called **good** if:
* Each digit of `s` is part of **exactly** one substring.
* The value of each substring is less than or equal to `k`.
Return _the **minimum** number of substrings in a **good** p... | null |
Python | Greedy | 100% | partition-string-into-substrings-with-values-at-most-k | 0 | 1 | # Code\n```\nclass Solution:\n def minimumPartition(self, s: str, k: int) -> int:\n if k < 10 and int(max(s)) > k: return -1\n j = 0\n n = len(s)\n cur = 0\n res = 1\n while j < n:\n cur = 10*cur + int(s[j])\n if cur > k:\n cur = int(s[j]... | 1 | You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.
A partition of a string `s` is called **good** if:
* Each digit of `s` is part of **exactly** one substring.
* The value of each substring is less than or equal to `k`.
Return _the **minimum** number of substrings in a **good** p... | null |
Python Greedy and DP approach | partition-string-into-substrings-with-values-at-most-k | 0 | 1 | # DP approach\n\n# Code\n```\ndef minimumPartition(self, s: str, k: int) -> int:\n n = len(s)\n dp = [-1] * n\n\n def dfs(ind):\n if ind >=n :\n return 0\n if dp[ind]!=-1:\n return dp[ind]\n\n partitions = math.inf\n curr = 0... | 1 | You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.
A partition of a string `s` is called **good** if:
* Each digit of `s` is part of **exactly** one substring.
* The value of each substring is less than or equal to `k`.
Return _the **minimum** number of substrings in a **good** p... | null |
Easy Solution in O(n) time with proper Comments. | partition-string-into-substrings-with-values-at-most-k | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe Approch is to calculate the sum of digits continuously and if sum exceeds the value of k then me make a partition and again start calculating sum and make partitions.\n\n\n\n# Complexity\n- Time complexity: $$O(n)$$ where n is the len... | 2 | You are given a string `s` consisting of digits from `1` to `9` and an integer `k`.
A partition of a string `s` is called **good** if:
* Each digit of `s` is part of **exactly** one substring.
* The value of each substring is less than or equal to `k`.
Return _the **minimum** number of substrings in a **good** p... | null |
Python | 39ms, Beat 100% | Queue | closest-prime-numbers-in-range | 0 | 1 | ```\nclass Solution:\n def closestPrimes(self, left: int, right: int) -> List[int]:\n def isPrime(n):\n if n < 2: return False\n for x in range(2, int(n**0.5) + 1):\n if n % x == 0:\n return False\n return True\n q = []\n diff = ... | 4 | Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that:
* `left <= nums1 < nums2 <= right` .
* `nums1` and `nums2` are both **prime** numbers.
* `nums2 - nums1` is the **minimum** amongst all other pairs satisfying the above conditions.
Return _the positive integer arr... | null |
Python 3 || 8 lines, w/ example || T/M: 7937 ms /35.8 MB | closest-prime-numbers-in-range | 0 | 1 | ```\nclass Solution:\n def closestPrimes(self, left: int, right: int) -> List[int]:\n \n right+= 1 # Example: right = 6 left = 15\n\n # Before sieve: \n prime = [False,False]+[True]*(right-2) # prime ... | 4 | Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that:
* `left <= nums1 < nums2 <= right` .
* `nums1` and `nums2` are both **prime** numbers.
* `nums2 - nums1` is the **minimum** amongst all other pairs satisfying the above conditions.
Return _the positive integer arr... | null |
Python Sieve of Eratosthenes | closest-prime-numbers-in-range | 0 | 1 | This solution uses the Sieve of Eratosthenes to iterate through all of the prime numbers up to `right`.\n\nOnce you can do that, simply find the pair with the smallest range.\n\nThis could be made faster by stopping as soon as $$right - left == 2$$, but this is so fast it isn\'t really necessary.\n\n# Code\n```\nclass ... | 3 | Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that:
* `left <= nums1 < nums2 <= right` .
* `nums1` and `nums2` are both **prime** numbers.
* `nums2 - nums1` is the **minimum** amongst all other pairs satisfying the above conditions.
Return _the positive integer arr... | null |
SieveOfEratosthenes + Sliding Window Python Easy Solution | closest-prime-numbers-in-range | 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 | Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that:
* `left <= nums1 < nums2 <= right` .
* `nums1` and `nums2` are both **prime** numbers.
* `nums2 - nums1` is the **minimum** amongst all other pairs satisfying the above conditions.
Return _the positive integer arr... | null |
[Python 3] Sieve of Eratosthenes | closest-prime-numbers-in-range | 0 | 1 | ```\nclass Solution:\n def closestPrimes(self, left: int, right: int) -> List[int]:\n prime = [True for i in range(right + 1)]\n \n p = 2\n while p ** 2 <= right:\n if prime[p]:\n for i in range(p ** 2, right + 1, p):\n prime[i] = False\n ... | 2 | Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that:
* `left <= nums1 < nums2 <= right` .
* `nums1` and `nums2` are both **prime** numbers.
* `nums2 - nums1` is the **minimum** amongst all other pairs satisfying the above conditions.
Return _the positive integer arr... | null |
Python | Twin Primes, No Sieve | closest-prime-numbers-in-range | 0 | 1 | # Intuition\n\n[Twin primes](https://en.wikipedia.org/wiki/Twin_prime) are quite common, so it won\'t take long to find some.\n\n# Approach\n\n**Lemma**: every range $$1 \\le L \\le R \\le 10^6$$ of length at least 1\'452 contains a pair of twin primes. _Proof_: run a sieve of Eratosthenes and see for yourself.\n\nIf t... | 22 | Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that:
* `left <= nums1 < nums2 <= right` .
* `nums1` and `nums2` are both **prime** numbers.
* `nums2 - nums1` is the **minimum** amongst all other pairs satisfying the above conditions.
Return _the positive integer arr... | null |
Brute force approach but terminate if you find a pair of primes whose difference is two | closest-prime-numbers-in-range | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you look at the list of primes, you will notice that there\nare many pairs of primes whose difference is two. \n\nFor example (3,5),(11,13),(101,103),....\n\nA pair of primes whose difference is two is called a twin prime.\nIf you are ... | 1 | Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that:
* `left <= nums1 < nums2 <= right` .
* `nums1` and `nums2` are both **prime** numbers.
* `nums2 - nums1` is the **minimum** amongst all other pairs satisfying the above conditions.
Return _the positive integer arr... | null |
EASY to UNDERSTAND || Conditional Logic | categorize-box-according-to-criteria | 0 | 1 | # Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n//Specifies a fixed set of possible values.\nfrom typing import Literal\n\nclass Solution:\n def categorizeBox(self, length:... | 1 | Given four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.
* The box is `"Bulky "` if:
* **Any** of the dimensions of the box is greater or equal to `104`.
* Or, the **volume** of th... | null |
Easy Solution | Java | Python | categorize-box-according-to-criteria | 1 | 1 | # Java\n```\nclass Solution {\n public boolean isBulky(int a, int b, int c, int d) {\n double val = Math.pow(10, 4);\n if(a >= val || b >= val || c >= val || d >= val) {\n return true;\n }\n else if((long) a * b * c >= Math.pow(10, 9)) {\n return true;\n }\n ... | 1 | Given four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.
* The box is `"Bulky "` if:
* **Any** of the dimensions of the box is greater or equal to `104`.
* Or, the **volume** of th... | null |
categorize-box-according-to-criteria | categorize-box-according-to-criteria | 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 four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.
* The box is `"Bulky "` if:
* **Any** of the dimensions of the box is greater or equal to `104`.
* Or, the **volume** of th... | null |
Easy solution. Beats 99 %. Match/Switch Case. Python. | categorize-box-according-to-criteria | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse match cases.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create boolean variabls bulky and heavy.\n2. Set valus acording the task description.\n3. Make cases.\n4. Return a required value dependent on a par... | 0 | Given four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.
* The box is `"Bulky "` if:
* **Any** of the dimensions of the box is greater or equal to `104`.
* Or, the **volume** of th... | null |
Python3 | categorize-box-according-to-criteria | 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```\nCode block\n```\n- Space complexity:\n<!-- Add your space complexity he... | 1 | Given four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.
* The box is `"Bulky "` if:
* **Any** of the dimensions of the box is greater or equal to `104`.
* Or, the **volume** of th... | null |
Python 3 || 2 lines, w/ explanation || T/M: 100% / 100% | categorize-box-according-to-criteria | 0 | 1 | Here\'s the plan: \n- We use this bit map for assigning a string:\n```\nBulky Heavy idx bits string\n\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\nFalse F... | 33 | Given four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.
* The box is `"Bulky "` if:
* **Any** of the dimensions of the box is greater or equal to `104`.
* Or, the **volume** of th... | null |
Python || Simple If...Else | categorize-box-according-to-criteria | 0 | 1 | # Code\n```\nclass Solution:\n def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:\n if length>=(10**4) or width>=(10**4) or height>=(10**4) or length*width*height>=(10**9):\n if mass>=100:\n return "Both"\n else:\n return "Bulky... | 1 | Given four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.
* The box is `"Bulky "` if:
* **Any** of the dimensions of the box is greater or equal to `104`.
* Or, the **volume** of th... | null |
[C++|Java|Python3] if-else | categorize-box-according-to-criteria | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7360be4d63ffa8b13518401baa628a6f6800d326) for solutions of weekly 95. \n\n**Intuition**\nThis is a `if-else` problem. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n string categorizeBox(int length, int width, int height, int mas... | 6 | Given four integers `length`, `width`, `height`, and `mass`, representing the dimensions and mass of a box, respectively, return _a string representing the **category** of the box_.
* The box is `"Bulky "` if:
* **Any** of the dimensions of the box is greater or equal to `104`.
* Or, the **volume** of th... | null |
[python3] Sol for reference | find-consecutive-integers-from-a-data-stream | 0 | 1 | ```\nclass DataStream:\n\n def __init__(self, value: int, k: int):\n self.count = 0 \n self.value = value\n self.k = k\n\n def consec(self, num: int) -> bool:\n if num == self.value:\n self.count += 1\n else: \n self.count = 0 \n \n return... | 2 | For a stream of integers, implement a data structure that checks if the last `k` integers parsed in the stream are **equal** to `value`.
Implement the **DataStream** class:
* `DataStream(int value, int k)` Initializes the object with an empty integer stream and the two integers `value` and `k`.
* `boolean consec(... | null |
Python3 counting Solution without creating queue/array | find-consecutive-integers-from-a-data-stream | 0 | 1 | \n# Code\n```\nclass DataStream:\n\n def __init__(self, value: int, k: int):\n self.key_ = value\n self.target_counter_ = k\n self.counter_ = 0\n \n\n def consec(self, num: int) -> bool:\n if num == self.key_:\n self.counter_ += 1\n if self.counter_ == self... | 3 | For a stream of integers, implement a data structure that checks if the last `k` integers parsed in the stream are **equal** to `value`.
Implement the **DataStream** class:
* `DataStream(int value, int k)` Initializes the object with an empty integer stream and the two integers `value` and `k`.
* `boolean consec(... | null |
[Python3] Record the Last Index of non-Value Element in the Data Stream | find-consecutive-integers-from-a-data-stream | 0 | 1 | # Intuition\nChecking the last `k` element in the Data Stream each time is computationally expensive and will get TLE. We need to come up with better algorithms.\n\n# Approach\nGiven the objective of this problem, we don\'t need to (physically) maintain the full Data Stream, but just need to record the last index of th... | 6 | For a stream of integers, implement a data structure that checks if the last `k` integers parsed in the stream are **equal** to `value`.
Implement the **DataStream** class:
* `DataStream(int value, int k)` Initializes the object with an empty integer stream and the two integers `value` and `k`.
* `boolean consec(... | null |
[Python] O(1) Time and Space | find-consecutive-integers-from-a-data-stream | 0 | 1 | ```\nclass DataStream:\n\n def __init__(self, value: int, k: int):\n self.k = k\n self.val = value\n self.t = k\n \n\n def consec(self, num: int) -> bool:\n if self.t > 0:\n self.t -= 1\n \n if num != self.val:\n self.t = self.k\n \... | 1 | For a stream of integers, implement a data structure that checks if the last `k` integers parsed in the stream are **equal** to `value`.
Implement the **DataStream** class:
* `DataStream(int value, int k)` Initializes the object with an empty integer stream and the two integers `value` and `k`.
* `boolean consec(... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.