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 || recursion || backtracking
maximum-rows-covered-by-columns
0
1
# Backtracking + recursion\n## Time -> O(2^N) {N is length of columns}\n## Space -> O(cols)\n\n```\nclass Solution:\n def maximumRows(self, mat: List[List[int]], cols: int) -> int:\n res = []\n M = len(mat)\n N = len(mat[0])\n def check(seen):\n count = 0\n for row i...
3
You are given a **0-indexed** `m x n` binary matrix `matrix` and an integer `numSelect`, which denotes the number of **distinct** columns you must select from `matrix`. Let us consider `s = {c1, c2, ...., cnumSelect}` as the set of columns selected by you. A row `row` is **covered** by `s` if: * For each cell `matr...
null
Python Simple Solution
maximum-rows-covered-by-columns
0
1
```\nclass Solution:\n def maximumRows(self, mat: List[List[int]], cols: int) -> int:\n n,m = len(mat),len(mat[0])\n ans = 0\n\n def check(state,row,rowIncludedCount):\n nonlocal ans\n if row==n:\n if sum(state)<=cols:\n ans = max(ans,rowIn...
5
You are given a **0-indexed** `m x n` binary matrix `matrix` and an integer `numSelect`, which denotes the number of **distinct** columns you must select from `matrix`. Let us consider `s = {c1, c2, ...., cnumSelect}` as the set of columns selected by you. A row `row` is **covered** by `s` if: * For each cell `matr...
null
Python | Simple and straightforward | Combinations | Explained
maximum-rows-covered-by-columns
0
1
```\nfrom itertools import combinations\nclass Solution:\n def maximumRows(self, mat: List[List[int]], cols: int) -> int:\n rows = 0\n \n # iterate over each combintion of the given numer of columns\n # the first argument passed to combinations is the list of columns\' indices\n # ...
1
You are given a **0-indexed** `m x n` binary matrix `matrix` and an integer `numSelect`, which denotes the number of **distinct** columns you must select from `matrix`. Let us consider `s = {c1, c2, ...., cnumSelect}` as the set of columns selected by you. A row `row` is **covered** by `s` if: * For each cell `matr...
null
Simple Solution
check-distances-between-same-letters
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** string `s` consisting of only lowercase English letters, where each letter in `s` appears **exactly** **twice**. You are also given a **0-indexed** integer array `distance` of length `26`. Each letter in the alphabet is numbered from `0` to `25` (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, ....
null
Python3 easy solution
check-distances-between-same-letters
0
1
\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkDistances(self, s: str, dis: List[int]) -> bool:\n d = {}\n for i in range(len(...
1
You are given a **0-indexed** string `s` consisting of only lowercase English letters, where each letter in `s` appears **exactly** **twice**. You are also given a **0-indexed** integer array `distance` of length `26`. Each letter in the alphabet is numbered from `0` to `25` (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, ....
null
Python Solution | Easy Understanding
check-distances-between-same-letters
0
1
```\nclass Solution:\n def mapper(self, s): # finds difference of indices\n result = dict()\n for letter in set(s):\n indices = []\n for idx, value in enumerate(s):\n if value == letter:\n indices.append(idx)\n result[letter] = indices...
1
You are given a **0-indexed** string `s` consisting of only lowercase English letters, where each letter in `s` appears **exactly** **twice**. You are also given a **0-indexed** integer array `distance` of length `26`. Each letter in the alphabet is numbered from `0` to `25` (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, ....
null
Python3 || 3 lines, T/M: 36ms/13.8MB
check-distances-between-same-letters
0
1
```\nclass Solution: # Pretty much explains itself.\n def checkDistances(self, s: str, distance: List[int]) -> bool:\n \n d = defaultdict(list)\n\n for i, ch in enumerate(s):\n d[ch].append(i)\n\n return all(b-a-1 == distance[ord(ch)-97] for ch, (a,b) in d.items())
16
You are given a **0-indexed** string `s` consisting of only lowercase English letters, where each letter in `s` appears **exactly** **twice**. You are also given a **0-indexed** integer array `distance` of length `26`. Each letter in the alphabet is numbered from `0` to `25` (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, ....
null
Python | S.C. and T.C. = O(n)
number-of-ways-to-reach-a-position-after-exactly-k-steps
0
1
\n\n# Complexity\n- Time complexity : $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def numberOfWays(self, startPos: int, endPos: int, k: int) -> int:\n mod = 10**9+7\...
1
You are given two **positive** integers `startPos` and `endPos`. Initially, you are standing at position `startPos` on an **infinite** number line. With one step, you can move either one position to the left, or one position to the right. Given a positive integer `k`, return _the number of **different** ways to reach ...
null
DP }| Recursion || Memoization || Python3
number-of-ways-to-reach-a-position-after-exactly-k-steps
0
1
```\nclass Solution(object):\n def numberOfWays(self, startPos, endPos, k):\n """\n :type startPos: int\n :type endPos: int\n :type k: int\n :rtype: int\n """\n MOD=1e9+7\n \n dp={}\n \n def A(currpos,k):\n if (currpos,k) in dp:\...
2
You are given two **positive** integers `startPos` and `endPos`. Initially, you are standing at position `startPos` on an **infinite** number line. With one step, you can move either one position to the left, or one position to the right. Given a positive integer `k`, return _the number of **different** ways to reach ...
null
[Java/Python 3] Sliding window & bit manipulation, w/ explanation, comments and analysis.
longest-nice-subarray
1
1
**Q & A**\n\n*Q*: How to think of such approach in interview?\n*A*: I believe the key point is how to understand and then use the constraint "bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0."\n\nThe other point is that a subarray is a **contiguous** part of an array, ...
35
You are given an array `nums` consisting of **positive** integers. We call a subarray of `nums` **nice** if the bitwise **AND** of every pair of elements that are in **different** positions in the subarray is equal to `0`. Return _the length of the **longest** nice subarray_. A **subarray** is a **contiguous** part ...
null
[Python3] Sliding Window
longest-nice-subarray
0
1
Intuition:\n\nElements in a nice subarray should not have same bits of 1s\nFor example, we can not have 1 and 3 in a nice subarray, because bit #0 in both numbers is 1\n1 -> 0001\n3 -> 0011\n\nSo we use sliding window and keep tracking of all bits in the current window by using OR operator.\nAnd when we encounter a num...
3
You are given an array `nums` consisting of **positive** integers. We call a subarray of `nums` **nice** if the bitwise **AND** of every pair of elements that are in **different** positions in the subarray is equal to `0`. Return _the length of the **longest** nice subarray_. A **subarray** is a **contiguous** part ...
null
100% Python Solution
longest-nice-subarray
0
1
\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def longestNiceSubarray(self, nums: List[int]) -> int:\n l,r = 0,1\n res = 0\n\n while r < len(nums):\n i = l\n\n """do the bitwise AND for the entire window so far"""\...
1
You are given an array `nums` consisting of **positive** integers. We call a subarray of `nums` **nice** if the bitwise **AND** of every pair of elements that are in **different** positions in the subarray is equal to `0`. Return _the length of the **longest** nice subarray_. A **subarray** is a **contiguous** part ...
null
Bit Magic with Explanation and Complexities
longest-nice-subarray
0
1
##### Rationale\n* We need to do check whether we could include a number in the current window in constant time\n* We could represent the group with bitwise OR for the all the numbers in the current window\n\t* Given a window, `[3, 8, 48]`, we need to know whether we could include the next number in the window in const...
29
You are given an array `nums` consisting of **positive** integers. We call a subarray of `nums` **nice** if the bitwise **AND** of every pair of elements that are in **different** positions in the subarray is equal to `0`. Return _the length of the **longest** nice subarray_. A **subarray** is a **contiguous** part ...
null
Python | Sliding window
longest-nice-subarray
0
1
We start with the window `[0, 0]`. At each step we try to see if adding one more element to the contiguous subarray would overlap some bit to the used bits among the numbers present in the current subarray. * When we can make the window larger to the right, we update the used bits as well * When we cannot make the wi...
2
You are given an array `nums` consisting of **positive** integers. We call a subarray of `nums` **nice** if the bitwise **AND** of every pair of elements that are in **different** positions in the subarray is equal to `0`. Return _the length of the **longest** nice subarray_. A **subarray** is a **contiguous** part ...
null
Python 3 | 2 heaps — O(m log(max(m, n)) + n), O(m+n)
meeting-rooms-iii
0
1
# Intuition\nMaintain rooms sorted by their time of being available again.\nMaintain available rooms sorted by their nubmer to pick the smallest one.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $O(m\\log (\\max(m, n)) + n)$\n\n- Space complexity: $O(m + n)$...
2
You are given an integer `n`. There are `n` rooms numbered from `0` to `n - 1`. You are given a 2D integer array `meetings` where `meetings[i] = [starti, endi]` means that a meeting will be held during the **half-closed** time interval `[starti, endi)`. All the values of `starti` are **unique**. Meetings are allocate...
null
87% TC easy python solution
meeting-rooms-iii
0
1
```\ndef mostBooked(self, n: int, meet: List[List[int]]) -> int:\n\tcount = [0] * n\n\tmeet.sort()\n\tavlbl = SortedList([i for i in range(n)])\n\thold = []\n\tfor i, j in meet:\n\t\twhile(hold and hold[0][0] <= i):\n\t\t\t_, room = heappop(hold)\n\t\t\tavlbl.add(room)\n\t\tif(avlbl):\n\t\t\troom = avlbl.pop(0)\n\t\t\t...
2
You are given an integer `n`. There are `n` rooms numbered from `0` to `n - 1`. You are given a 2D integer array `meetings` where `meetings[i] = [starti, endi]` means that a meeting will be held during the **half-closed** time interval `[starti, endi)`. All the values of `starti` are **unique**. Meetings are allocate...
null
Simple and Detailed comments, readable, beats 99%
meeting-rooms-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing Min heap\n\n# Complexity\n- Time complexity: \nO(nlogn)\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def mostBooked(self, num_rooms, meetings):\n # Create a list of available rooms using indic...
7
You are given an integer `n`. There are `n` rooms numbered from `0` to `n - 1`. You are given a 2D integer array `meetings` where `meetings[i] = [starti, endi]` means that a meeting will be held during the **half-closed** time interval `[starti, endi)`. All the values of `starti` are **unique**. Meetings are allocate...
null
Python | More heap extravaganza
meeting-rooms-iii
0
1
We will keep a heap of available rooms and a keep of occupied rooms. * At the beginning the heap of available rooms includes all rooms. It will include only the room numbers * The heap of occupied rooms will include tuples `(endTime, roomNumber)` * For each meeting, we * Check if by the time it starts any meetin...
2
You are given an integer `n`. There are `n` rooms numbered from `0` to `n - 1`. You are given a 2D integer array `meetings` where `meetings[i] = [starti, endi]` means that a meeting will be held during the **half-closed** time interval `[starti, endi)`. All the values of `starti` are **unique**. Meetings are allocate...
null
simple code using dictionary
most-frequent-even-element
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
Given an integer array `nums`, return _the most frequent even element_. If there is a tie, return the **smallest** one. If there is no such element, return `-1`. **Example 1:** **Input:** nums = \[0,1,2,2,4,4,1\] **Output:** 2 **Explanation:** The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. We ...
null
Python Simple Code || 97.6% Beats || HashMap
most-frequent-even-element
0
1
**If you got help from this,... Plz Upvote .. it encourage me**\n\nHashMap Solution:\n# Code\n```\nclass Solution:\n def mostFrequentEven(self, nums: List[int]) -> int:\n d = {}\n for ele in nums:\n if ele%2 == 0:\n d[ele] = d.get(ele,0) + 1\n\n if not d:\n r...
2
Given an integer array `nums`, return _the most frequent even element_. If there is a tie, return the **smallest** one. If there is no such element, return `-1`. **Example 1:** **Input:** nums = \[0,1,2,2,4,4,1\] **Output:** 2 **Explanation:** The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. We ...
null
Python Solution | Easy Understanding
most-frequent-even-element
0
1
```\nfrom collections import Counter\n\nclass Solution:\n def mostFrequentEven(self, nums) -> int:\n counter = Counter([i for i in nums if i % 2 == 0])\n if not counter:\n return -1\n res = {x: count for x, count in counter.items() if count == max(counter.values())}\n return mi...
3
Given an integer array `nums`, return _the most frequent even element_. If there is a tie, return the **smallest** one. If there is no such element, return `-1`. **Example 1:** **Input:** nums = \[0,1,2,2,4,4,1\] **Output:** 2 **Explanation:** The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. We ...
null
Hashmap (Counter) Simple 4 line code
most-frequent-even-element
0
1
```\nclass Solution:\n def mostFrequentEven(self, nums: List[int]) -> int:\n nums.sort()\n a=Counter(nums).most_common()\n a.sort(key=lambda x:-x[1])\n for i in range(len(a)):\n if a[i][0]%2==0:\n return a[i][0]\n return -1\n```
2
Given an integer array `nums`, return _the most frequent even element_. If there is a tie, return the **smallest** one. If there is no such element, return `-1`. **Example 1:** **Input:** nums = \[0,1,2,2,4,4,1\] **Output:** 2 **Explanation:** The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. We ...
null
Hashmap Python3
optimal-partition-of-string
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 a string `s`, partition the string into one or more **substrings** such that the characters in each substring are **unique**. That is, no letter appears in a single substring more than **once**. Return _the **minimum** number of substrings in such a partition._ Note that each character should belong to exactly ...
null
Python Simple Solution O(n)
optimal-partition-of-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$...
1
Given a string `s`, partition the string into one or more **substrings** such that the characters in each substring are **unique**. That is, no letter appears in a single substring more than **once**. Return _the **minimum** number of substrings in such a partition._ Note that each character should belong to exactly ...
null
Very Easy Solution | Python3 | Greedy
optimal-partition-of-string
0
1
# Very easy solution with Greedy\ncreate substring (`ss`).\nIterate through each character `c` in `s` and check whether `c` is in `ss`. \nIf `c` is in `ss`, that means we can\'t add the `c` to `ss`. \nSo increment `t` and make `ss` empty. \n\nFinally, return `t+1` (because we started to count from 0 and we have not cou...
1
Given a string `s`, partition the string into one or more **substrings** such that the characters in each substring are **unique**. That is, no letter appears in a single substring more than **once**. Return _the **minimum** number of substrings in such a partition._ Note that each character should belong to exactly ...
null
Min Heap
divide-intervals-into-minimum-number-of-groups
0
1
We use a min heap to track the rightmost number of each group.\n\nFirst, we sort the intervals. Then, for each interval, we check if the top of the heap is less than **left**.\n\nIf it is, we can add that interval to an existing group: pop from the heap, and push **right**, updating the rightmost number of that group.\...
261
You are given a 2D integer array `intervals` where `intervals[i] = [lefti, righti]` represents the **inclusive** interval `[lefti, righti]`. You have to divide the intervals into one or more **groups** such that each interval is in **exactly** one group, and no two intervals that are in the same group **intersect** ea...
null
[Python 3] Line Sweep - Difference Array
divide-intervals-into-minimum-number-of-groups
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here...
3
You are given a 2D integer array `intervals` where `intervals[i] = [lefti, righti]` represents the **inclusive** interval `[lefti, righti]`. You have to divide the intervals into one or more **groups** such that each interval is in **exactly** one group, and no two intervals that are in the same group **intersect** ea...
null
[Python3/Rust] Max DP Overlap
divide-intervals-into-minimum-number-of-groups
0
1
**Weekly Contest 310 Submission**\n\n**Disclaimer** \nMy contest submission was written in ```Python3```. I attempted submissions after the contest and noticed that this solution will TLE on average (as noted by ```xavier-xia-99``` it seems to be an approximate 10% acceptance chance in ```Python3```). Following the con...
3
You are given a 2D integer array `intervals` where `intervals[i] = [lefti, righti]` represents the **inclusive** interval `[lefti, righti]`. You have to divide the intervals into one or more **groups** such that each interval is in **exactly** one group, and no two intervals that are in the same group **intersect** ea...
null
[Python3] Sort + Heap
divide-intervals-into-minimum-number-of-groups
0
1
```\nclass Solution:\n def minGroups(self, intervals: List[List[int]]) -> int:\n intervals.sort()\n pq = []\n for interval in intervals:\n if not pq or interval[0] <= pq[0]:\n heapq.heappush(pq, interval[1])\n else:\n\t\t\t\theapq.heappop(pq)\n\t\t\t\theapq.h...
3
You are given a 2D integer array `intervals` where `intervals[i] = [lefti, righti]` represents the **inclusive** interval `[lefti, righti]`. You have to divide the intervals into one or more **groups** such that each interval is in **exactly** one group, and no two intervals that are in the same group **intersect** ea...
null
✔ Python3 Solution | O(nlogn)
divide-intervals-into-minimum-number-of-groups
0
1
`Time Complexity` : `O(nlogn)`\n```\nclass Solution:\n def minGroups(self, A):\n A = list(map(sorted, zip(*A)))\n ans, j = 1, 0\n for i in range(1, len(A[0])):\n if A[0][i] > A[1][j]: j += 1\n else: ans += 1\n return ans\n```
1
You are given a 2D integer array `intervals` where `intervals[i] = [lefti, righti]` represents the **inclusive** interval `[lefti, righti]`. You have to divide the intervals into one or more **groups** such that each interval is in **exactly** one group, and no two intervals that are in the same group **intersect** ea...
null
Python Easy Solution Well Explained
longest-increasing-subsequence-ii
0
1
```\n# Iterative Segment Tree\nclass SegmentTree:\n def __init__(self, n, fn):\n self.n = n\n self.fn = fn\n self.tree = [0] * (2 * n)\n \n def query(self, l, r):\n l += self.n\n r += self.n\n res = 0\n while l < r:\n if l & 1:\n res...
6
You are given an integer array `nums` and an integer `k`. Find the longest subsequence of `nums` that meets the following requirements: * The subsequence is **strictly increasing** and * The difference between adjacent elements in the subsequence is **at most** `k`. Return _the length of the **longest** **subseq...
null
[Python3] segment tree
longest-increasing-subsequence-ii
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/b89b2c654a0b8ced9885ecdb433ad5f929a1d4b4) for solutions of weekly 310. \n\n```\nclass SegTree: \n\n def __init__(self, arr: List[int]): \n self.n = len(arr)\n self.tree = [0] * (2*self.n)\n # for i in range(2*self.n-1, 0, -1...
1
You are given an integer array `nums` and an integer `k`. Find the longest subsequence of `nums` that meets the following requirements: * The subsequence is **strictly increasing** and * The difference between adjacent elements in the subsequence is **at most** `k`. Return _the length of the **longest** **subseq...
null
[Python] Segment Tree - Clean & Concise
longest-increasing-subsequence-ii
0
1
# Intuition\n- Use Segment Tree to query maximum of element in range [num-k, num-1], which mean to find the maximum existed Longest Increase Subsequence such that the maximum difference between consecutives element <= k.\n\n# Complexity\n- Time: `O(N * logMAX + MAX)`, where `N <= 10^5` is length of nums array, `MAX <= ...
3
You are given an integer array `nums` and an integer `k`. Find the longest subsequence of `nums` that meets the following requirements: * The subsequence is **strictly increasing** and * The difference between adjacent elements in the subsequence is **at most** `k`. Return _the length of the **longest** **subseq...
null
DP to Segment Tree (Python)
longest-increasing-subsequence-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo make sense of the accepted segment tree approach, we first need to briefly discuss the relevant dynamic programming approach with $$O(nk)$$ time complexity and $$O(n)$$ space complexity.\n\nWe\'re going to traverse our array nums. For ...
1
You are given an integer array `nums` and an integer `k`. Find the longest subsequence of `nums` that meets the following requirements: * The subsequence is **strictly increasing** and * The difference between adjacent elements in the subsequence is **at most** `k`. Return _the length of the **longest** **subseq...
null
Python Elegant & Short | Built-In date
count-days-spent-together
0
1
\tfrom datetime import date\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(1)\n\t\tMemory: O(1)\n\t\t"""\n\n\t\tdef countDaysTogether(self, arrive_alice: str, leave_alice: str, arrive_bob: str, leave_bob: str) -> int:\n\t\t\tstart = max(self.to_date(arrive_alice), self.to_date(arrive_bob))\n\t\t\tend = min(self.to_date...
2
Alice and Bob are traveling to Rome for separate business meetings. You are given 4 strings `arriveAlice`, `leaveAlice`, `arriveBob`, and `leaveBob`. Alice will be in the city from the dates `arriveAlice` to `leaveAlice` (**inclusive**), while Bob will be in the city from the dates `arriveBob` to `leaveBob` (**inclusi...
null
✅ Python simple solution | easy to understand | explained
count-days-spent-together
0
1
#### Understanding\n* Find the minimum date of leave between Alice & Bob.\n* Find the maximum date of arrival between Alice & Bob.\n* The desire date will be between these two limit.\n\n#### Example\n* Let the input be `arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"`\n* The minimum...
23
Alice and Bob are traveling to Rome for separate business meetings. You are given 4 strings `arriveAlice`, `leaveAlice`, `arriveBob`, and `leaveBob`. Alice will be in the city from the dates `arriveAlice` to `leaveAlice` (**inclusive**), while Bob will be in the city from the dates `arriveBob` to `leaveBob` (**inclusi...
null
Beginner Friendly Python Approach
maximum-matching-of-players-with-trainers
0
1
# Intuition\nSimple\n\n# Approach\nTwo pointer approach is the better approach for this question when considering the constraints.\n\n# Complexity\n- Time complexity:\nO(n) to O(n^2)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def matchPlayersAndTrainers(self, players: List[int], trainers: List[in...
2
You are given a **0-indexed** integer array `players`, where `players[i]` represents the **ability** of the `ith` player. You are also given a **0-indexed** integer array `trainers`, where `trainers[j]` represents the **training capacity** of the `jth` trainer. The `ith` player can **match** with the `jth` trainer if ...
null
Python3 Greedy & Two pointers Solution - Beats 100%
maximum-matching-of-players-with-trainers
0
1
![image](https://assets.leetcode.com/users/images/8d22ac22-0037-495f-89c7-e308d54ed4de_1663490515.0716884.png)\n\n```\nclass Solution:\n def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:\n players.sort()\n trainers.sort()\n res = 0\n i, j = 0, 0\n w...
1
You are given a **0-indexed** integer array `players`, where `players[i]` represents the **ability** of the `ith` player. You are also given a **0-indexed** integer array `trainers`, where `trainers[j]` represents the **training capacity** of the `jth` trainer. The `ith` player can **match** with the `jth` trainer if ...
null
Extremely Simple Implementation python3. Faster than 100% solutions
maximum-matching-of-players-with-trainers
0
1
```py\nclass Solution:\n def matchPlayersAndTrainers(self, players: List[int], t: List[int]) -> int:\n \n c = j = i = 0\n players.sort()\n t.sort()\n while i <= len(players) - 1 and j <= len(t) - 1:\n if players[i] <= t[j]:\n \n ...
1
You are given a **0-indexed** integer array `players`, where `players[i]` represents the **ability** of the `ith` player. You are also given a **0-indexed** integer array `trainers`, where `trainers[j]` represents the **training capacity** of the `jth` trainer. The `ith` player can **match** with the `jth` trainer if ...
null
[Secret Python Answer🤫🐍👌😍] Sliding Window with Double Dictionary of Binary Count
smallest-subarrays-with-maximum-bitwise-or
0
1
```\nclass Solution:\n def smallestSubarrays(self, nums: List[int]) -> List[int]:\n\n def create(m):\n t = 0\n for n in m:\n if m[n] > 0:\n t = t | (1 << n)\n return t\n \n def add(a,m):\n ans = bin( a )\n s...
1
You are given a **0-indexed** array `nums` of length `n`, consisting of non-negative integers. For each index `i` from `0` to `n - 1`, you must determine the size of the **minimum sized** non-empty subarray of `nums` starting at `i` (**inclusive**) that has the **maximum** possible **bitwise OR**. * In other words, ...
null
The easiest possible explanation you are looking for
minimum-money-required-before-transactions
0
1
It took me a while to get this through my head. So take your time but make sure you understand this.\n\n**Alse note that this is not the perfect O(N) solution. You can see Lee215 soln for that. This is O(NlogN) solution but this is what was easier for me to understand**\n\n**Now lets start**\n\n1. First, know that ther...
5
You are given a **0-indexed** 2D integer array `transactions`, where `transactions[i] = [costi, cashbacki]`. The array describes transactions, where each transaction must be completed exactly once in **some order**. At any given moment, you have a certain amount of `money`. In order to complete transaction `i`, `money...
null
Python: Follow the Hints
minimum-money-required-before-transactions
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOverall, we want to figure out how much money we need up front to ensure that we have enough money before we try processing any transaction to pay for its cost, regardless of whether we get a big "cashback" or not. And, we want to do thi...
0
You are given a **0-indexed** 2D integer array `transactions`, where `transactions[i] = [costi, cashbacki]`. The array describes transactions, where each transaction must be completed exactly once in **some order**. At any given moment, you have a certain amount of `money`. In order to complete transaction `i`, `money...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
smallest-even-multiple
0
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post. You may also join my [Discord](https://d...
5
Given a **positive** integer `n`, return _the smallest positive integer that is a multiple of **both**_ `2` _and_ `n`. **Example 1:** **Input:** n = 5 **Output:** 10 **Explanation:** The smallest multiple of both 5 and 2 is 10. **Example 2:** **Input:** n = 6 **Output:** 6 **Explanation:** The smallest multiple of ...
null
Solution of smallest even multiple problem
smallest-even-multiple
0
1
# **There are two cases:**\n- if number is even: return number\n- if number is odd(else): return double number value\n\n# Code\n```\nclass Solution:\n def smallestEvenMultiple(self, n: int) -> int:\n if n % 2 == 0:\n return n\n else:\n return n*2\n \n```
1
Given a **positive** integer `n`, return _the smallest positive integer that is a multiple of **both**_ `2` _and_ `n`. **Example 1:** **Input:** n = 5 **Output:** 10 **Explanation:** The smallest multiple of both 5 and 2 is 10. **Example 2:** **Input:** n = 6 **Output:** 6 **Explanation:** The smallest multiple of ...
null
Brute Force and Logic Methods | Python3
smallest-even-multiple
0
1
# Complexity\n- Time complexity:\n***$$O(n)$$ and $$O(1)$$***\n\n- Space complexity:\n***$$O(n)$$ and $$O(1)$$***\n\n# Code:\n#### ***Brute Force:***\n```python [Brute Force]\nclass Solution:\n def smallestEvenMultiple(self, n: int) -> int:\n for i in range(n, n*2+1):\n if i % n == 0 and i % 2 == 0...
1
Given a **positive** integer `n`, return _the smallest positive integer that is a multiple of **both**_ `2` _and_ `n`. **Example 1:** **Input:** n = 5 **Output:** 10 **Explanation:** The smallest multiple of both 5 and 2 is 10. **Example 2:** **Input:** n = 6 **Output:** 6 **Explanation:** The smallest multiple of ...
null
[Short Python Answer🤫🐍👌😍] One Line and 15 Characters
smallest-even-multiple
0
1
```\nclass Solution:\n def smallestEvenMultiple(self, n: int) -> int:\n return lcm(n,2)
2
Given a **positive** integer `n`, return _the smallest positive integer that is a multiple of **both**_ `2` _and_ `n`. **Example 1:** **Input:** n = 5 **Output:** 10 **Explanation:** The smallest multiple of both 5 and 2 is 10. **Example 2:** **Input:** n = 6 **Output:** 6 **Explanation:** The smallest multiple of ...
null
✅ Explained - Simple and Clear Python3 Code✅
length-of-the-longest-alphabetical-continuous-substring
0
1
# Intuition\nThe problem asks us to find the length of the longest alphabetical continuous substring in a given string. To solve this, we can iterate through the string and keep track of the current count of consecutive alphabetical characters. Whenever we encounter a character that breaks the alphabetical sequence, we...
6
An **alphabetical continuous string** is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string `"abcdefghijklmnopqrstuvwxyz "`. * For example, `"abc "` is an alphabetical continuous string, while `"acb "` and `"za "` are not. Given a string `s` consisting of l...
null
Python3 O(n) solution
length-of-the-longest-alphabetical-continuous-substring
0
1
# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def longestContinuousSubstring(self, s: str) -> int:\n m = 0\n curr = 1\n for i in range(len(s)-1):\n if ord(s[i])+1==ord(s[i+1]):\n curr += 1\n else:\n ...
1
An **alphabetical continuous string** is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string `"abcdefghijklmnopqrstuvwxyz "`. * For example, `"abc "` is an alphabetical continuous string, while `"acb "` and `"za "` are not. Given a string `s` consisting of l...
null
Self Understandable solution:
length-of-the-longest-alphabetical-continuous-substring
0
1
```\nclass Solution:\n def longestContinuousSubstring(self, s: str) -> int:\n x=set()\n p=[s[0]]\n for i in s[1:]:\n if ord(p[-1])+1==ord(i):\n p.append(i)\n else:\n x.add("".join(p))\n p=[i]\n x.add("".join(p))\n a...
1
An **alphabetical continuous string** is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string `"abcdefghijklmnopqrstuvwxyz "`. * For example, `"abc "` is an alphabetical continuous string, while `"acb "` and `"za "` are not. Given a string `s` consisting of l...
null
Python3 || Two-Pointer
length-of-the-longest-alphabetical-continuous-substring
0
1
\n# Approach\nInitialize i with index 0 and j with index 1.\nFix the pointer \'i\' and keep on moving pointer \'j\' until the difference between ascii value of s[j] and s[j-1] equals 1. Keep updating the answer with max length obtained till the current step. once the difference between ascii value of s[j] and s[j-1] no...
1
An **alphabetical continuous string** is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string `"abcdefghijklmnopqrstuvwxyz "`. * For example, `"abc "` is an alphabetical continuous string, while `"acb "` and `"za "` are not. Given a string `s` consisting of l...
null
python3 solution using queue beats 100%
reverse-odd-levels-of-binary-tree
0
1
# stats\n<!-- Describe your first thoughts on how to solve this problem. -->\n![Screenshot 2023-07-26 at 10.17.01 PM.png](https://assets.leetcode.com/users/images/d0dd3e9c-d95c-437f-a713-28fd33cde2c8_1690390036.6265955.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe have a queue and we a...
1
Given the `root` of a **perfect** binary tree, reverse the node values at each **odd** level of the tree. * For example, suppose the node values at level 3 are `[2,1,3,4,7,11,29,18]`, then it should become `[18,29,11,7,4,3,1,2]`. Return _the root of the reversed tree_. A binary tree is **perfect** if all parent no...
null
Python3 || Beats 93.89%
reverse-odd-levels-of-binary-tree
0
1
![image.png](https://assets.leetcode.com/users/images/d2cac7b4-f90c-427e-b45c-3c251214da2b_1679723421.6646197.png)\n# Please UPVOTE\uD83D\uDE0A\n\n# Python3\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.le...
16
Given the `root` of a **perfect** binary tree, reverse the node values at each **odd** level of the tree. * For example, suppose the node values at level 3 are `[2,1,3,4,7,11,29,18]`, then it should become `[18,29,11,7,4,3,1,2]`. Return _the root of the reversed tree_. A binary tree is **perfect** if all parent no...
null
Easy Python Solution With Dictionary
sum-of-prefix-scores-of-strings
0
1
```\nclass Solution:\n def sumPrefixScores(self, words: List[str]) -> List[int]:\n d = dict()\n for i in words:\n s=""\n for j in range(len(i)):\n s+=i[j]\n if s in d:\n d[s]+=1\n else:\n d[s]=1\n ...
1
You are given an array `words` of size `n` consisting of **non-empty** strings. We define the **score** of a string `word` as the **number** of strings `words[i]` such that `word` is a **prefix** of `words[i]`. * For example, if `words = [ "a ", "ab ", "abc ", "cab "]`, then the score of `"ab "` is `2`, since `"ab ...
null
Simple Easy to Read trie solution | Python3
sum-of-prefix-scores-of-strings
0
1
```\nclass TrieNode:\n \n def __init__(self, ch: str) -> None:\n self.ch = ch\n self.endOfWord = 0\n self.vstd = 0\n self.children = {}\n\n\nclass Solution:\n # O(n*m) time, n --> len(words), m --> len(words[i]) \n # O(n*m) space,\n # Approach: trie, hashtable\n def sumPref...
1
You are given an array `words` of size `n` consisting of **non-empty** strings. We define the **score** of a string `word` as the **number** of strings `words[i]` such that `word` is a **prefix** of `words[i]`. * For example, if `words = [ "a ", "ab ", "abc ", "cab "]`, then the score of `"ab "` is `2`, since `"ab ...
null
[ Python ] ✅✅ Simple Python Solution Using Dictionary 🥳✌👍
sum-of-prefix-scores-of-strings
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 8638 ms, faster than 9.09% of Python3 online submissions for Sum of Prefix Scores of Strings.\n# Memory Usage: 243.6 MB, less than 9.09% of Python3 online submissions for Sum of Prefix Scores of Strings.\n\n\tcla...
1
You are given an array `words` of size `n` consisting of **non-empty** strings. We define the **score** of a string `word` as the **number** of strings `words[i]` such that `word` is a **prefix** of `words[i]`. * For example, if `words = [ "a ", "ab ", "abc ", "cab "]`, then the score of `"ab "` is `2`, since `"ab ...
null
Solution of sort the people problem
sort-the-people
0
1
# Approach\n- Step one: zip 2 list into one\n- Step two: sort it with function `.sorted()`\n- Step three: return sorted list in descending order by the people\'s heights.\n# Complexity\n- Time complexity:\n$$O(N * log(N))$$ - as sorted function takes O(N * log(N)) time and loop takes linear time -> $$O(N * log(N) + N)$...
1
You are given an array of strings `names`, and an array `heights` that consists of **distinct** positive integers. Both arrays are of length `n`. For each index `i`, `names[i]` and `heights[i]` denote the name and height of the `ith` person. Return `names` _sorted in **descending** order by the people's heights_. **...
null
Sort Names
sort-the-people
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 array of strings `names`, and an array `heights` that consists of **distinct** positive integers. Both arrays are of length `n`. For each index `i`, `names[i]` and `heights[i]` denote the name and height of the `ith` person. Return `names` _sorted in **descending** order by the people's heights_. **...
null
[Java/Python 3] Longest consecutive max subarray.
longest-subarray-with-maximum-bitwise-and
1
1
Max bitwise `AND` subarray must include maximum element(s) **ONLY**. Therefore, we only need to find the longest subarray including max only.\n\n**Method1: Two Pass:**\n\n```java\n public int longestSubarray(int[] nums) {\n int max = 0, longest = 1, cur = 0;\n for (int num : nums) {\n max = ...
28
You are given an integer array `nums` of size `n`. Consider a **non-empty** subarray from `nums` that has the **maximum** possible **bitwise AND**. * In other words, let `k` be the maximum value of the bitwise AND of **any** subarray of `nums`. Then, only subarrays with a bitwise AND equal to `k` should be consider...
null
Group By and One-Pass
longest-subarray-with-maximum-bitwise-and
0
1
The maximum possible bitwise AND should not be less than a largest element.\n\nTherefore, the subarray must only include one or more largest elements.\n\n**Python 3**\n```python\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n max_n = max(nums)\n return max(len(list(it)) for n, i...
10
You are given an integer array `nums` of size `n`. Consider a **non-empty** subarray from `nums` that has the **maximum** possible **bitwise AND**. * In other words, let `k` be the maximum value of the bitwise AND of **any** subarray of `nums`. Then, only subarrays with a bitwise AND equal to `k` should be consider...
null
PYTHON-3, BEATS 100%, UNIQUE SOLUTION, SLIDING- WINDOW, ROLLING-HASH, UNORDERED-SET, ARRAYS
find-all-good-indices
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIf len(nums) == 3, ans will always be [1]. If k == 1, ans will always have all indices from 1 to len(nums) - 2. Instead of using two k-sized loops for every index, we will use two windows of size k to accomplish the goal in ...
1
You are given a **0-indexed** integer array `nums` of size `n` and a positive integer `k`. We call an index `i` in the range `k <= i < n - k` **good** if the following conditions are satisfied: * The `k` elements that are just **before** the index `i` are in **non-increasing** order. * The `k` elements that are j...
null
「Python3」🧼Clean "Two-Sum" Style
find-all-good-indices
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nSimilar to using a $$Hashmap$$ in to store "target num & current num", we store all the length "target INC index & current DEC index".\n\n1. store all `k` length INC index, eg. if `k = 2`, and index[0:1] is INC, store {3: 0} in $$Hashmap$$, because yo...
1
You are given a **0-indexed** integer array `nums` of size `n` and a positive integer `k`. We call an index `i` in the range `k <= i < n - k` **good** if the following conditions are satisfied: * The `k` elements that are just **before** the index `i` are in **non-increasing** order. * The `k` elements that are j...
null
Three Pass Python solution - Easy to Understand
find-all-good-indices
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 size `n` and a positive integer `k`. We call an index `i` in the range `k <= i < n - k` **good** if the following conditions are satisfied: * The `k` elements that are just **before** the index `i` are in **non-increasing** order. * The `k` elements that are j...
null
Simple Python Solution
find-all-good-indices
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 size `n` and a positive integer `k`. We call an index `i` in the range `k <= i < n - k` **good** if the following conditions are satisfied: * The `k` elements that are just **before** the index `i` are in **non-increasing** order. * The `k` elements that are j...
null
[Python3] Two passes O(n) with line by line comments.
find-all-good-indices
0
1
To solve the problem, we will need to traverse the array left to right and then right to left. From left to right, at each index i, we will compute how many elements that are just before the index i are in non-increasing order. To do this, we will use a non-increasing stack to store the elements before i, at each step ...
35
You are given a **0-indexed** integer array `nums` of size `n` and a positive integer `k`. We call an index `i` in the range `k <= i < n - k` **good** if the following conditions are satisfied: * The `k` elements that are just **before** the index `i` are in **non-increasing** order. * The `k` elements that are j...
null
Video Explanation | Easiest Solution using Python
number-of-good-paths
0
1
# Approach\nhttps://youtu.be/EIoHwUL5Efk\n\n# Code\n```\nclass UnionFind:\n def __init__(self, size):\n self.parent = list(range(size))\n self.rank = [0] * size\n\n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent...
1
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node. You are also given a 2D integer array `edges` where `...
null
Python3 🐍 concise solution beats 96.9%
number-of-good-paths
0
1
# Code\n```\nclass Solution:\n def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:\n n = len(vals)\n p = list(range(n))\n count = [Counter({vals[i]:1}) for i in range(n)]\n edges = sorted((max(vals[i],vals[j]),i,j) for i,j in edges)\n res = n\n def f...
5
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node. You are also given a 2D integer array `edges` where `...
null
Python O(n) Solution using Nested `Counter()` (Detailed Comments)
remove-letter-to-equalize-frequency
0
1
```\nclass Solution:\n def equalFrequency(self, word: str) -> bool:\n word_counter = Counter(word)\n # All characters in `word` are the same character, or all characters are different (each only occur once)\n if len(word_counter) == 1 or len(word_counter) == len(word):\n return True\n...
1
You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal. Return `true` _if it is possible to remove one letter so that the frequency of...
null
[Python3] One-Pass Solution O(n), Clean & Concise
longest-uploaded-prefix
0
1
```\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.videos = [False] * (n + 1)\n self.ans = 0\n\n def upload(self, video: int) -> None:\n self.videos[video] = True\n if video == self.ans + 1:\n while video < len(self.videos):\n if not self.videos[video...
2
You are given a stream of `n` videos, each represented by a **distinct** number from `1` to `n` that you need to "upload " to a server. You need to implement a data structure that calculates the length of the **longest uploaded prefix** at various points in the upload process. We consider `i` to be an uploaded prefix ...
null
Python Elegant & Short | Amortized O(1) | Commented
longest-uploaded-prefix
0
1
```\nclass LUPrefix:\n """\n Memory: O(n)\n Time: O(1) per upload call, because adding to the set takes O(1) time, and the prefix\n\t\t\t\t can be increased no more than n times for all n calls to the upload function\n """\n\n def __init__(self, n: int):\n self._longest = 0\n self._nums =...
68
You are given a stream of `n` videos, each represented by a **distinct** number from `1` to `n` that you need to "upload " to a server. You need to implement a data structure that calculates the length of the **longest uploaded prefix** at various points in the upload process. We consider `i` to be an uploaded prefix ...
null
Easy and optimized python3 solution
longest-uploaded-prefix
0
1
class LUPrefix:\n\n def __init__(self, n: int):\n \n self.v = [0]*(n+1)\n self.cur = 1\n \n\n def upload(self, video: int) -> None:\n self.v[video] = 1\n if video == self.cur:\n self.cur+=1\n \n while self.cur<len(self.v) and self.v[self.cur]!=0:\...
1
You are given a stream of `n` videos, each represented by a **distinct** number from `1` to `n` that you need to "upload " to a server. You need to implement a data structure that calculates the length of the **longest uploaded prefix** at various points in the upload process. We consider `i` to be an uploaded prefix ...
null
O(nlogn) using merging lower upper bound intervals
longest-uploaded-prefix
0
1
**Main Idea**:\n+ Managing lower/upper bound intervals\n+ Uploading method:\n + vmin, vmax = video, video\n + Find upper bound interval: video - 1 -> found: vmin = min(interval), delete lower/upper bound intervals corresponding\n + Find lower bound interval: video + 1 -> found: vmax = max(interval), delete lower/upp...
1
You are given a stream of `n` videos, each represented by a **distinct** number from `1` to `n` that you need to "upload " to a server. You need to implement a data structure that calculates the length of the **longest uploaded prefix** at various points in the upload process. We consider `i` to be an uploaded prefix ...
null
Python Elegant & Short | O(n + m)
bitwise-xor-of-all-pairings
0
1
```\nfrom functools import reduce\nfrom operator import xor\n\n\nclass Solution:\n def xorAllNums(self, a: List[int], b: List[int]) -> int:\n return reduce(xor, a * (len(b) & 1) + b * (len(a) & 1), 0)\n```\n\nIf you like this solution remember to **upvote it** to let me know.
3
You are given two **0-indexed** arrays, `nums1` and `nums2`, consisting of non-negative integers. There exists another array, `nums3`, which contains the bitwise XOR of **all pairings** of integers between `nums1` and `nums2` (every integer in `nums1` is paired with every integer in `nums2` **exactly once**). Return _...
null
[python3] math sol for reference
bitwise-xor-of-all-pairings
0
1
# Intuition\nXOR follows identity, associative and commutative rules. \n\n# Approach\n[a,b] [c,d,e] results in the following.\na^c ^ a^d ^ a^e ^ b^c ^ b^d b^e\n\nDepending on the even or odd number of the second array, number of \'a\' can be decided. \n\na^a = 0\na^a^a = a \n\nThe same rule can be applied reverse from ...
1
You are given two **0-indexed** arrays, `nums1` and `nums2`, consisting of non-negative integers. There exists another array, `nums3`, which contains the bitwise XOR of **all pairings** of integers between `nums1` and `nums2` (every integer in `nums1` is paired with every integer in `nums2` **exactly once**). Return _...
null
O(n) using checking odd and even attributes of length array (Examples)
bitwise-xor-of-all-pairings
0
1
***Main Idea***:\n+ XOR attribute: a ^ a = 0, a ^ a ^ a = a\n+ Counting odd and even attributes of the number of occuring every elements in nums1 and nums2\n + nums1[i] occurs n2 times \n + nums2[i] occurs n1 times\n+ Calculating ans as follow:\n + ans1 <- xor(all nums1[i]) if n2%1==1 or 0\n + ans2 <- xor(all nums2...
1
You are given two **0-indexed** arrays, `nums1` and `nums2`, consisting of non-negative integers. There exists another array, `nums3`, which contains the bitwise XOR of **all pairings** of integers between `nums1` and `nums2` (every integer in `nums1` is paired with every integer in `nums2` **exactly once**). Return _...
null
Python3 + In place MergeSort + Explanation
number-of-pairs-satisfying-inequality
0
1
\n\n# Code\n```\nclass Solution:\n def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int:\n # See Merge Sort and 493. Reverse Pairs before this\n # This problem is exactly as 493, but we need to transform the two input\n # arrays to one first\n # nums1[i] - nums1[j...
1
You are given two **0-indexed** integer arrays `nums1` and `nums2`, each of size `n`, and an integer `diff`. Find the number of **pairs** `(i, j)` such that: * `0 <= i < j <= n - 1` **and** * `nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff`. Return _the **number of pairs** that satisfy the conditions._ **Exam...
null
Python3 Segment tree Solution
number-of-pairs-satisfying-inequality
0
1
```\nclass segment_tree:\n \n def __init__(self, arr):\n self.len_ = len(arr)\n \n self.data_ = [0] * (self.len_ * 2)\n \n for t in range(self.len_, self.len_ * 2, 1):\n self.data_[t] = arr[t - self.len_]\n \n for t in range(self.len_-1, -1, -1): \n self.data_[t] = self.data_[t * ...
1
You are given two **0-indexed** integer arrays `nums1` and `nums2`, each of size `n`, and an integer `diff`. Find the number of **pairs** `(i, j)` such that: * `0 <= i < j <= n - 1` **and** * `nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff`. Return _the **number of pairs** that satisfy the conditions._ **Exam...
null
Clean, Fast Python3 | SortedList | O(n log(n))
number-of-pairs-satisfying-inequality
0
1
Please upvote if it helps!\n```\nfrom sortedcontainers import SortedList\nclass Solution:\n def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int:\n n, pairs = len(nums1), 0\n # simplify the problem by rearranging equations: find all pairs of i, j in nums such that nums[i] - num...
1
You are given two **0-indexed** integer arrays `nums1` and `nums2`, each of size `n`, and an integer `diff`. Find the number of **pairs** `(i, j)` such that: * `0 <= i < j <= n - 1` **and** * `nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff`. Return _the **number of pairs** that satisfy the conditions._ **Exam...
null
Beats 45.67% || Number of common factors
number-of-common-factors
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 two positive integers `a` and `b`, return _the number of **common** factors of_ `a` _and_ `b`. An integer `x` is a **common factor** of `a` and `b` if `x` divides both `a` and `b`. **Example 1:** **Input:** a = 12, b = 6 **Output:** 4 **Explanation:** The common factors of 12 and 6 are 1, 2, 3, 6. **Example 2...
null
Python / JS one-liners
number-of-common-factors
0
1
**Python**\n```\nclass Solution:\n def commonFactors(self, a: int, b: int) -> int:\n return sum(a % n == 0 and b % n == 0 for n in range(1, min(a, b) + 1))\n```\n**Javascript**\n```\nconst commonFactors = (a, b) => (\n new Array(Math.min(a, b)+1).fill(0)\n .reduce((total, _, i) => total + (a % i == ...
2
Given two positive integers `a` and `b`, return _the number of **common** factors of_ `a` _and_ `b`. An integer `x` is a **common factor** of `a` and `b` if `x` divides both `a` and `b`. **Example 1:** **Input:** a = 12, b = 6 **Output:** 4 **Explanation:** The common factors of 12 and 6 are 1, 2, 3, 6. **Example 2...
null
Python 100% run time
number-of-common-factors
0
1
```\nclass Solution:\n def commonFactors(self, a: int, b: int) -> int:\n count = 0\n if max(a,b) % min(a,b) == 0:\n count += 1\n for i in range(1,(min(a,b)//2) + 1):\n if a % i == 0 and b % i == 0:\n count += 1\n return count\n```
1
Given two positive integers `a` and `b`, return _the number of **common** factors of_ `a` _and_ `b`. An integer `x` is a **common factor** of `a` and `b` if `x` divides both `a` and `b`. **Example 1:** **Input:** a = 12, b = 6 **Output:** 4 **Explanation:** The common factors of 12 and 6 are 1, 2, 3, 6. **Example 2...
null
Python Elegant & Short
maximum-sum-of-an-hourglass
0
1
```\nfrom typing import List\n\n\nclass Solution:\n """\n Time: O(n*m)\n Memory: O(n*m)\n """\n\n def maxSum(self, grid: List[List[int]]) -> int:\n n, m = len(grid), len(grid[0])\n return max(\n self.get_hourglass(grid, i, j)\n for i in range(1, n - 1)\n f...
2
You are given an `m x n` integer matrix `grid`. We define an **hourglass** as a part of the matrix with the following form: Return _the **maximum** sum of the elements of an hourglass_. **Note** that an hourglass cannot be rotated and must be entirely contained within the matrix. **Example 1:** **Input:** grid = \...
null
Simple Python Solution || O(MxN) beats 83.88%
maximum-sum-of-an-hourglass
0
1
```\nclass Solution:\n def maxSum(self, grid: List[List[int]]) -> int:\n res=0\n cur=0\n \n for i in range(len(grid)-2):\n for j in range(1,len(grid[0])-1):\n \n cur=sum(grid[i][j-1:j+2]) +grid[i+1][j] + sum(grid[i+2][j-1:j+2])\n res ...
1
You are given an `m x n` integer matrix `grid`. We define an **hourglass** as a part of the matrix with the following form: Return _the **maximum** sum of the elements of an hourglass_. **Note** that an hourglass cannot be rotated and must be entirely contained within the matrix. **Example 1:** **Input:** grid = \...
null
Python Solution | NumPy | The Easiest Way
maximum-sum-of-an-hourglass
0
1
```\nimport numpy as np\nclass Solution:\n def maxSum(self, grid) -> int:\n l, r, m, n = 0, 0, len(grid), len(grid[0])\n arr = np.array(grid)\n max_sum = 0\n while l < m - 2:\n while r < n - 2:\n current_sum = np.sum(arr[l:l + 3, r:r + 3]) - (arr[l + 1, r] + arr[...
1
You are given an `m x n` integer matrix `grid`. We define an **hourglass** as a part of the matrix with the following form: Return _the **maximum** sum of the elements of an hourglass_. **Note** that an hourglass cannot be rotated and must be entirely contained within the matrix. **Example 1:** **Input:** grid = \...
null
O(n^2) using sliding window for finding houg-glass matrix 3x3
maximum-sum-of-an-hourglass
0
1
**Main Idea**:\n+ Processing 3x3 by sliding window\n\n**Code**:\n```\nclass Solution:\n def maxSum(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n ans = 0\n for i in range(m-2):\n for j in range(n-2):\n vsum = 0\n for k in range(3)...
1
You are given an `m x n` integer matrix `grid`. We define an **hourglass** as a part of the matrix with the following form: Return _the **maximum** sum of the elements of an hourglass_. **Note** that an hourglass cannot be rotated and must be entirely contained within the matrix. **Example 1:** **Input:** grid = \...
null
🔥[Python 3] Simple brute-force, beats 89%
maximum-sum-of-an-hourglass
0
1
```python3 []\nclass Solution:\n def maxSum(self, grid: List[List[int]]) -> int:\n res = 0\n for i in range(len(grid)-2):\n for j in range(len(grid[0])-2):\n sm = grid[i][j] + grid[i][j+1] + grid[i][j+2] + grid[i+1][j+1] + \\\n grid[i+2][j] + grid[i+2][j+1] + gr...
2
You are given an `m x n` integer matrix `grid`. We define an **hourglass** as a part of the matrix with the following form: Return _the **maximum** sum of the elements of an hourglass_. **Note** that an hourglass cannot be rotated and must be entirely contained within the matrix. **Example 1:** **Input:** grid = \...
null
Easy to understand Python code using bit counting.
minimize-xor
0
1
The approach is simple,\n1. First count the number of 1\'s in num2 and store in c\n2. We want to set c no. of 1\'s in the required num wherever we find a set bit num1(this is because 1^1 = 0. \n3. Remember we go from MSB because we want to use c no.of 1\'s most effectively to reduce more value.\n4. After setting c 1\'s...
6
Given two positive integers `num1` and `num2`, find the positive integer `x` such that: * `x` has the same number of set bits as `num2`, and * The value `x XOR num1` is **minimal**. Note that `XOR` is the bitwise XOR operation. Return _the integer_ `x`. The test cases are generated such that `x` is **uniquely de...
null
O(log(n)) using set and clear bit (examples)
minimize-xor
0
1
**Main Idea**:\n+ Counting the number of bit 1 of num2 (**nbit1**)\n\n+ Clearing bit 1 of num1 using **nbit1** from position high to lower \n + Setting bit 1 to ans for clearing positions \n+ Setting remain nbit 1 to ans for position from low to high excluding clearing positions\n\n**Examples**:\n```\nnum2 = 28 = 1111...
1
Given two positive integers `num1` and `num2`, find the positive integer `x` such that: * `x` has the same number of set bits as `num2`, and * The value `x XOR num1` is **minimal**. Note that `XOR` is the bitwise XOR operation. Return _the integer_ `x`. The test cases are generated such that `x` is **uniquely de...
null
✔ Python3 Solution | DP | Clean & Concise
maximum-deletions-on-a-string
0
1
# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def deleteString(self, S):\n N = len(S)\n if S.count(S[0]) == N: return N\n P = [0] * (N + 1)\n dp = [1] * N\n for i in range(N - 1, -1, -1):\n for j in rang...
1
You are given a string `s` consisting of only lowercase English letters. In one operation, you can: * Delete **the entire string** `s`, or * Delete the **first** `i` letters of `s` if the first `i` letters of `s` are **equal** to the following `i` letters in `s`, for any `i` in the range `1 <= i <= s.length / 2`. ...
null
[✅ Python] DP top-down Clean & Concise
maximum-deletions-on-a-string
0
1
```\n def deleteString(self, s: str) -> int:\n n = len(s)\n if n == 1: return 1\n\t\tif (len(set(s)) == 1): return n\n \n @cache\n def dp(i):\n if i == n - 1: return 1\n res = 0\n l = (n - i) // 2\n temp = ""\n for j in range(1...
3
You are given a string `s` consisting of only lowercase English letters. In one operation, you can: * Delete **the entire string** `s`, or * Delete the **first** `i` letters of `s` if the first `i` letters of `s` are **equal** to the following `i` letters in `s`, for any `i` in the range `1 <= i <= s.length / 2`. ...
null
Python 3, DP bottom-up + Substr Hash
maximum-deletions-on-a-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBrute-force approach runs O(S**3) time, S = s.length().\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo reduce run-time to O(S**2), this comparison (s[i:j] == s[j+k])within DP loops needs to be reduced from line...
1
You are given a string `s` consisting of only lowercase English letters. In one operation, you can: * Delete **the entire string** `s`, or * Delete the **first** `i` letters of `s` if the first `i` letters of `s` are **equal** to the following `i` letters in `s`, for any `i` in the range `1 <= i <= s.length / 2`. ...
null
✅✅✅ 95% faster solution and easy to understand
the-employee-that-worked-on-the-longest-task
0
1
![Screenshot 2022-12-30 at 10.56.58.png](https://assets.leetcode.com/users/images/9c1e8f0a-7694-4484-a3a7-514a16f30326_1672379856.9461722.png)\n\n```\nclass Solution:\n def hardestWorker(self, n: int, logs: List[List[int]]) -> int:\n ans = logs[0]\n for i in range(1, len(logs)):\n d = logs[i...
1
There are `n` employees, each with a unique id from `0` to `n - 1`. You are given a 2D integer array `logs` where `logs[i] = [idi, leaveTimei]` where: * `idi` is the id of the employee that worked on the `ith` task, and * `leaveTimei` is the time at which the employee finished the `ith` task. All the values `leav...
null
Python Elegant & Short | No indexes | 99.32% faster
the-employee-that-worked-on-the-longest-task
0
1
![image](https://assets.leetcode.com/users/images/53cd3bda-8ee8-4cbe-8d7c-6b4eb5ea02da_1665559451.2513933.png)\n\n```\nclass Solution:\n """\n Time: O(n)\n Memory: O(1)\n """\n\n def hardestWorker(self, n: int, logs: List[List[int]]) -> int:\n best_id = best_time = start = 0\n\n for emp_i...
10
There are `n` employees, each with a unique id from `0` to `n - 1`. You are given a 2D integer array `logs` where `logs[i] = [idi, leaveTimei]` where: * `idi` is the id of the employee that worked on the `ith` task, and * `leaveTimei` is the time at which the employee finished the `ith` task. All the values `leav...
null
Python [Explained] | O(n)
the-employee-that-worked-on-the-longest-task
0
1
# Approach\n- We can iterate through the logs while calculating current task-duration as `logs[i][1]-logs[i-1][1]` for each task and largest task duration as `max_time`.\n- Now we will find smallest `id` among all the largest task duration.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\...
4
There are `n` employees, each with a unique id from `0` to `n - 1`. You are given a 2D integer array `logs` where `logs[i] = [idi, leaveTimei]` where: * `idi` is the id of the employee that worked on the `ith` task, and * `leaveTimei` is the time at which the employee finished the `ith` task. All the values `leav...
null
✅ Python Straightforward & Easy to Understand Solution
the-employee-that-worked-on-the-longest-task
0
1
`O(n)` \n1 - change logs by substituting the end and start times\n2 - find the longest one between durations\n```\nlogs = [[log[0], log[1] - logs[idx-1][1] if idx > 0 else log[1]] for idx, log in enumerate(logs)]\nlongest = max(logs, key=lambda x: (x[1], -x[0]))\nreturn longest[0]\n```
3
There are `n` employees, each with a unique id from `0` to `n - 1`. You are given a 2D integer array `logs` where `logs[i] = [idi, leaveTimei]` where: * `idi` is the id of the employee that worked on the `ith` task, and * `leaveTimei` is the time at which the employee finished the `ith` task. All the values `leav...
null
✅ 92.93% One Line XORing
find-the-original-array-of-prefix-xor
1
1
# Intuition\nUpon reading the problem, the first thing that might come to mind is how the XOR operation behaves. Since the prefix XOR array is essentially an accumulation of XOR operations, the inverse process would involve \'undoing\' the XOR operation. We remember that XOR has the following properties:\n\n1. $ a \\op...
29
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
✅ Beats 99.24% 🔥 || 3 Approaches 💡 ||
find-the-original-array-of-prefix-xor
1
1
# Approach 1: Prefix Sum\n\n![Screenshot 2023-10-31 at 8.46.24\u202FAM.png](https://assets.leetcode.com/users/images/3f2f64b9-39f6-4e4e-b7bf-9bc6aabc2153_1698723928.257756.png)\n\n# Intuition:\n\n**If we have an array of prefix sums pref, then the original array arr can be recovered by taking the prefix sum of pref. Th...
2
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
【Video】Give me 5 minutes - How we think about a solution - Python, JavaScript, Java, C++
find-the-original-array-of-prefix-xor
1
1
# Intuition\nThis is similar to prefix sum\n\n---\n\n# Solution Video\n\nhttps://youtu.be/ck4dJURKAlA\n\n\u25A0 Timeline of the video\n`0:05` Solution code with build-in function\n`0:06` quick recap of XOR calculation\n`0:28` Demonstrate how to solve the question\n`1:37` How you keep the original previous number\n`2:29...
50
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
✅☑[C++/Java/Python/JavaScript] || 1 line Code || EXPLAINED🔥
find-the-original-array-of-prefix-xor
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n\n1. It checks if the size of the `pref` vector is less than or equal to 1. If so, it returns the pref vector as it is, as there\'s not enough information to reconstruct an original array in such cases.\n\n1. If the `pref` vector...
2
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
✅Easy Solution🔥Java/C++/C/Python3/Python/JavaScript🔥
find-the-original-array-of-prefix-xor
1
1
![LC Discuss Pic.png](https://assets.leetcode.com/users/images/73ea8fbd-329e-461c-bf5a-942dca401a7f_1698748827.5992491.png)\n\n\n# Code\n```Java []\nclass Solution {\n public int[] findArray(int[] pref) {\n int[] ans = new int[pref.length];\n ans[0] = pref[0];\n for(int i=1; i<ans.length; i++){\...
2
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 Solution
find-the-original-array-of-prefix-xor
0
1
\n```\nclass Solution:\n def findArray(self, pref: List[int]) -> List[int]:\n N=len(pref)\n arr=[pref[0]]\n \n for i in range(1,N):\n arr.append(pref[i-1]^pref[i])\n \n return arr \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