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
📌📌Python3 || 2007 ms, faster than 90.49% of Python3 || Clean and Easy to Understand
single-threaded-cpu
0
1
```\ndef getOrder(self, tasks: List[List[int]]) -> List[int]:\n arr = []\n prev = 0\n output = [] \n tasks= sorted((tasks,i) for i,tasks in enumerate(tasks))\n for (m,n), i in tasks:\n while arr and prev < m:\n p,j,k = heappop(arr)\n prev = ma...
8
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times: * Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it. **Notice** that you can apply the ...
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
Simple python code with explanation
find-xor-sum-of-all-pairs-bitwise-and
0
1
```\nclass Solution:\n #example 1 \n #result =[(1&6)^(1&5)^(2&6)^(2&5)^(3&6)^(3&5)]\n \\ / \\ / \\ /\n # (1&(6^5)) ^ (2&(6^5)) ^ (3&(6^5)) \n \\ | /\n \\ | /\n \\ ...
4
The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element. * For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`. You are given two **0-inde...
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
Simple python code with explanation
find-xor-sum-of-all-pairs-bitwise-and
0
1
```\nclass Solution:\n #example 1 \n #result =[(1&6)^(1&5)^(2&6)^(2&5)^(3&6)^(3&5)]\n \\ / \\ / \\ /\n # (1&(6^5)) ^ (2&(6^5)) ^ (3&(6^5)) \n \\ | /\n \\ | /\n \\ ...
4
You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`. A string is called **balanced** if and only if: * It is the empty string, or * It can be written as `AB`, where both `A` and `B` are **balanced** s...
Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[...
Easy Bit Manipulation [C++] [Js] [Python]
find-xor-sum-of-all-pairs-bitwise-and
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n+m)\n\n- Space complexity:\nO(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int getXORSum(vector<int>& arr1, vector<in...
0
The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element. * For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`. You are given two **0-inde...
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
Easy Bit Manipulation [C++] [Js] [Python]
find-xor-sum-of-all-pairs-bitwise-and
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n+m)\n\n- Space complexity:\nO(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int getXORSum(vector<int>& arr1, vector<in...
0
You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`. A string is called **balanced** if and only if: * It is the empty string, or * It can be written as `AB`, where both `A` and `B` are **balanced** s...
Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[...
An Easy Solution with Explanation
find-xor-sum-of-all-pairs-bitwise-and
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncollect xor of each arry separately and then return the AND of both collections.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O...
0
The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element. * For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`. You are given two **0-inde...
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
An Easy Solution with Explanation
find-xor-sum-of-all-pairs-bitwise-and
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncollect xor of each arry separately and then return the AND of both collections.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O...
0
You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`. A string is called **balanced** if and only if: * It is the empty string, or * It can be written as `AB`, where both `A` and `B` are **balanced** s...
Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[...
Python - one line
find-xor-sum-of-all-pairs-bitwise-and
0
1
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n return reduce(xor, arr1) & reduce(xor, arr2)\n```
0
The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element. * For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`. You are given two **0-inde...
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
Python - one line
find-xor-sum-of-all-pairs-bitwise-and
0
1
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n return reduce(xor, arr1) & reduce(xor, arr2)\n```
0
You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`. A string is called **balanced** if and only if: * It is the empty string, or * It can be written as `AB`, where both `A` and `B` are **balanced** s...
Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[...
3 Line Solution
sum-of-digits-in-base-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
✅✅✅99.81% faster and 97.35% on memory
sum-of-digits-in-base-k
0
1
# Intuition\n![Screenshot 2022-12-14 at 12.43.45.png](https://assets.leetcode.com/users/images/101a32e1-ac14-45e4-852f-4f4df683c937_1671004000.5153394.png)\n\n# Code\n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n a = 0\n while n!=0:\n if n//k:\n a+=n%k\n ...
1
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
[Python] - Divmod Solution
sum-of-digits-in-base-k
0
1
My thought process was:\n1) For base conversion we always need to use repeated divmod\n2) The result ist the leftover number and the residual is the current digit\n\n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n result = 0\n \n # make repeated divmods to get the digits and\n...
2
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
{Python3} easy solution
sum-of-digits-in-base-k
0
1
```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n output_sum = 0\n while (n > 0) :\n rem = n % k\n output_sum = output_sum + rem \n n = int(n / k)\n return output_sum\n```
5
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
[Python3] self-explained
sum-of-digits-in-base-k
0
1
\n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n ans = 0\n while n: \n n, x = divmod(n, k)\n ans += x\n return ans \n```
13
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
3-Lines Python Solution || 95% Faster || Memory less than 75%
sum-of-digits-in-base-k
0
1
```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n ans=0\n while n>0: ans+=n%k ; n//=k\n return ans\n```\n-----------------\n### ***Another 1-Line Solution***\n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n return (x:=lambda y: 0 if not y else y%k + ...
3
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
Easy solution || PYTHON
sum-of-digits-in-base-k
0
1
```\n```class Solution:\n def sumBase(self, n: int, k: int) -> int:\n stri = ""\n while True:\n if n < k:\n break\n div = int(n // k)\n stri += str(n % k)\n n = div\n stri += str(n)\n stri = stri[::-1]\n lst = [int(x) for x...
1
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
python solution fastest and efficient
sum-of-digits-in-base-k
0
1
```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n x=[]\n while n!=0:\n x.append(n%k)\n n=n//k\n \n return sum(x)\n \n```
3
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
Python 100% Solution
frequency-of-the-most-frequent-element
0
1
# Typical Solution\n\n* 1043 ms\n\n```python\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n return max(iter_frequency(nums, k))\n\ndef iter_frequency(nums, k):\n window = deque()\n pre = 0\n for cur in sorted(nums):\n k -= (cur - pre) * len(window)\n while ...
2
The **frequency** of an element is the number of times it occurs in an array. You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`. Return _the **maximum possible frequency** of an element after performing **at mos...
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
【Video】Give me 10 minutes - How we think about a solution
frequency-of-the-most-frequent-element
1
1
# Intuition\nSorting input array and use slinding window technique.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/MbCFzt4v1uE\n\n\u203B Since I recorded that video last year, there might be parts that could be unclear. If you have any questions, feel free to leave a comment.\n\n\u25A0 Timeline of the video\n\n`0:00` R...
45
The **frequency** of an element is the number of times it occurs in an array. You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`. Return _the **maximum possible frequency** of an element after performing **at mos...
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
✅ Python3 | Sliding Window | Beats 97% ✅
frequency-of-the-most-frequent-element
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe initial idea is that we need to calculate, for every number in the array, how many numbers we can get to match that number after at most $k$ operations.\n\nThe next idea that comes to mind is that in order to use the $k$ operations ...
1
The **frequency** of an element is the number of times it occurs in an array. You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`. Return _the **maximum possible frequency** of an element after performing **at mos...
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
Easiest Solution
frequency-of-the-most-frequent-element
0
1
\nThis algorithm uses a sliding window approach to efficiently find the maximum frequency while considering the constraints on the number of operations.\n\n# Approach\nTo solve this problem, you can follow these steps:\n\n1. Sort the input array `nums` in ascending order.\n2. Initialize a variable `left` to 0 to repres...
7
The **frequency** of an element is the number of times it occurs in an array. You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`. Return _the **maximum possible frequency** of an element after performing **at mos...
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || EXPLAINED🔥
frequency-of-the-most-frequent-element
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Sliding Window)***\n1. Sort the `nums` array in ascending order to ensure that the elements are in non-decreasing order.\n\n1. Initialize two pointers, `left` and `right`, both starting at the beginning (0) of ...
6
The **frequency** of an element is the number of times it occurs in an array. You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`. Return _the **maximum possible frequency** of an element after performing **at mos...
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
[Python3] greedy
longest-substring-of-all-vowels-in-order
0
1
\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = "aeiou"\n ans = 0\n cnt = prev = -1 \n for i, x in enumerate(word): \n curr = vowels.index(x)\n if cnt >= 0: # in the middle of counting \n if 0 <= curr - prev <...
10
A string is considered **beautiful** if it satisfies the following conditions: * Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. * The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). For example...
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
[Python3] greedy
longest-substring-of-all-vowels-in-order
0
1
\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = "aeiou"\n ans = 0\n cnt = prev = -1 \n for i, x in enumerate(word): \n curr = vowels.index(x)\n if cnt >= 0: # in the middle of counting \n if 0 <= curr - prev <...
10
Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc " **Output:**...
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
Straightforward Python3 O(n) stack solution with explanations
longest-substring-of-all-vowels-in-order
0
1
```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n d = {}\n d[\'a\'] = {\'a\', \'e\'}\n d[\'e\'] = {\'e\', \'i\'}\n d[\'i\'] = {\'i\', \'o\'}\n d[\'o\'] = {\'o\', \'u\'}\n d[\'u\'] = {\'u\'}\n\t\t\n res, stack = 0, []\n for c in wor...
6
A string is considered **beautiful** if it satisfies the following conditions: * Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. * The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). For example...
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
Straightforward Python3 O(n) stack solution with explanations
longest-substring-of-all-vowels-in-order
0
1
```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n d = {}\n d[\'a\'] = {\'a\', \'e\'}\n d[\'e\'] = {\'e\', \'i\'}\n d[\'i\'] = {\'i\', \'o\'}\n d[\'o\'] = {\'o\', \'u\'}\n d[\'u\'] = {\'u\'}\n\t\t\n res, stack = 0, []\n for c in wor...
6
Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc " **Output:**...
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
[Python3] 98% Fast Solution
longest-substring-of-all-vowels-in-order
0
1
```\nfrom itertools import groupby\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n arr = groupby(word)\n \n ans = []\n \n count = 0\n \n for i , j in arr:\n ans.append([i , list(j)])\n \n for i in range(le...
9
A string is considered **beautiful** if it satisfies the following conditions: * Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. * The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). For example...
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
[Python3] 98% Fast Solution
longest-substring-of-all-vowels-in-order
0
1
```\nfrom itertools import groupby\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n arr = groupby(word)\n \n ans = []\n \n count = 0\n \n for i , j in arr:\n ans.append([i , list(j)])\n \n for i in range(le...
9
Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc " **Output:**...
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
Python soln
longest-substring-of-all-vowels-in-order
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
A string is considered **beautiful** if it satisfies the following conditions: * Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. * The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). For example...
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
Python soln
longest-substring-of-all-vowels-in-order
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc " **Output:**...
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
O(n) without SET or HASMAP
longest-substring-of-all-vowels-in-order
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
A string is considered **beautiful** if it satisfies the following conditions: * Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. * The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). For example...
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
O(n) without SET or HASMAP
longest-substring-of-all-vowels-in-order
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc " **Output:**...
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
Sorting and Two Passes in Python
maximum-building-height
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe first step is to sort the restrictions according to their positions. \nThe first pass begins from the rightmost to the leftmost for setting new height restriction of i according to the height restriction of its right parter (i+1).\nThe second pass...
0
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * ...
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
Sorting and Two Passes in Python
maximum-building-height
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe first step is to sort the restrictions according to their positions. \nThe first pass begins from the rightmost to the leftmost for setting new height restriction of i according to the height restriction of its right parter (i+1).\nThe second pass...
0
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1...
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
Python || sort, greedy || O(m log m)
maximum-building-height
0
1
1. Add `[1,0]` to `restrictions`, then sort `restrictions` by index in ascending order.\n2. We will do the same procedure twice, forward and backward. The procedure is as following:\n2-1. Move to `(idx_2, res_2)` and check previous `(idx_1, res_1)`. \n2-2. Let `steps = abs(idx_1-idx_2)`. Starting from `idx_1`, the maxi...
0
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * ...
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
Python || sort, greedy || O(m log m)
maximum-building-height
0
1
1. Add `[1,0]` to `restrictions`, then sort `restrictions` by index in ascending order.\n2. We will do the same procedure twice, forward and backward. The procedure is as following:\n2-1. Move to `(idx_2, res_2)` and check previous `(idx_1, res_1)`. \n2-2. Let `steps = abs(idx_1-idx_2)`. Starting from `idx_1`, the maxi...
0
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1...
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
BS ON ANSWER
maximum-building-height
0
1
\n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, rt: List[List[int]]) -> int:\n rt.append([0,-1])\n rt.append([n,float("inf")])\n rt.sort()\n n=len(rt)\n for i in range(1,n):\n rt[i][1]=min(rt[i][0]-rt[i-1][0]+rt[i-1][1],rt[i][1])\n for i in range(...
0
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * ...
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
BS ON ANSWER
maximum-building-height
0
1
\n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, rt: List[List[int]]) -> int:\n rt.append([0,-1])\n rt.append([n,float("inf")])\n rt.sort()\n n=len(rt)\n for i in range(1,n):\n rt[i][1]=min(rt[i][0]-rt[i-1][0]+rt[i-1][1],rt[i][1])\n for i in range(...
0
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1...
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
Python (Simple Maths)
maximum-building-height
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 want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * ...
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
Python (Simple Maths)
maximum-building-height
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1...
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
Python 6-lines
maximum-building-height
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst, sort restrictions with respect to first limiting the height of buildings when we traverse line from left to right.\n\nThen, traverse through array and store rightmost restriction in every point. In every comparison, leftmost and ...
0
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * ...
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
Python 6-lines
maximum-building-height
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst, sort restrictions with respect to first limiting the height of buildings when we traverse line from left to right.\n\nThen, traverse through array and store rightmost restriction in every point. In every comparison, leftmost and ...
0
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1...
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
[Python3] greedy
maximum-building-height
0
1
\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions.extend([[1, 0], [n, n-1]])\n restrictions.sort()\n \n for i in reversed(range(len(restrictions)-1)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1]...
4
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * ...
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
[Python3] greedy
maximum-building-height
0
1
\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions.extend([[1, 0], [n, n-1]])\n restrictions.sort()\n \n for i in reversed(range(len(restrictions)-1)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1]...
4
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1...
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
TC: O(N) SC: O(1) Greedy Approach Explained Python
maximum-building-height
0
1
For each building you want to find the most constraining height either on left or right\nm = len(restrictions) <= 10^5 so O(m^2) is too slow\nBut we can find biggest restriction on left for each element is one loop, and\nfind the biggest restriction on right for each element in one loop aswell\n\nlet curr biggest restr...
0
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * ...
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
TC: O(N) SC: O(1) Greedy Approach Explained Python
maximum-building-height
0
1
For each building you want to find the most constraining height either on left or right\nm = len(restrictions) <= 10^5 so O(m^2) is too slow\nBut we can find biggest restriction on left for each element is one loop, and\nfind the biggest restriction on right for each element in one loop aswell\n\nlet curr biggest restr...
0
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1...
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
[Python] Beats 100%, sort + one pass solution, O(nlog(n))
maximum-building-height
0
1
I have I think a pretty unique solution, using a single-pass approach to find the max height.\n\nThe main idea of the solution is to "follow the path" of maximum building heights by iterating over the most restrictive restrictions along the indexes.\n\nIf we are at a given restriction `i1, h1`, then we can look at all ...
0
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`. However, there are city restrictions on the heights of the new buildings: * The height of each building must be a non-negative integer. * The height of the first building **must** be `0`. * ...
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
[Python] Beats 100%, sort + one pass solution, O(nlog(n))
maximum-building-height
0
1
I have I think a pretty unique solution, using a single-pass approach to find the max height.\n\nThe main idea of the solution is to "follow the path" of maximum building heights by iterating over the most restrictive restrictions along the indexes.\n\nIf we are at a given restriction `i1, h1`, then we can look at all ...
0
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1...
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
Python Very Easy Solution
replace-all-digits-with-characters
0
1
# Code\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n new=""\n for i in range(len(s)):\n if i%2==0:\n new+=s[i]\n else:\n new+=chr(ord(s[i-1])+int(s[i]))\n return new\n```
2
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python Very Easy Solution
replace-all-digits-with-characters
0
1
# Code\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n new=""\n for i in range(len(s)):\n if i%2==0:\n new+=s[i]\n else:\n new+=chr(ord(s[i-1])+int(s[i]))\n return new\n```
2
In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it. You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`. Given an integer `neededAppl...
We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position
Python Solution
replace-all-digits-with-characters
0
1
# Code\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n l=list(s)\n for i,j in enumerate(l):\n if j.isdigit():\n l[i]=chr(ord(l[i-1])+int(j))\n return \'\'.join(l)\n```\nDo hit the like button if you find useful!
3
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python Solution
replace-all-digits-with-characters
0
1
# Code\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n l=list(s)\n for i,j in enumerate(l):\n if j.isdigit():\n l[i]=chr(ord(l[i-1])+int(j))\n return \'\'.join(l)\n```\nDo hit the like button if you find useful!
3
In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it. You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`. Given an integer `neededAppl...
We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position
Python O(n) solution
replace-all-digits-with-characters
0
1
\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# Python / Python3\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n ans = \'\'\n for i in range(...
2
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python O(n) solution
replace-all-digits-with-characters
0
1
\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# Python / Python3\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n ans = \'\'\n for i in range(...
2
In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it. You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`. Given an integer `neededAppl...
We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position
【Video】Give me 5 minutes - Bests 98.79% - How we think about a solution
seat-reservation-manager
1
1
# Intuition\nUse min heap\n\n---\n\n# Solution Video\n\nhttps://youtu.be/rgdtMOI5AKA\n\n\u25A0 Timeline of the video\n\n`0:04` Difficulty of Seat Reservation Manager\n`0:52` Two key points to solve Seat Reservation Manager\n`3:25` Coding\n`5:18` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'...
23
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **sm...
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
【Video】Give me 5 minutes - Bests 98.79% - How we think about a solution
seat-reservation-manager
1
1
# Intuition\nUse min heap\n\n---\n\n# Solution Video\n\nhttps://youtu.be/rgdtMOI5AKA\n\n\u25A0 Timeline of the video\n\n`0:04` Difficulty of Seat Reservation Manager\n`0:52` Two key points to solve Seat Reservation Manager\n`3:25` Coding\n`5:18` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'...
23
A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s. * For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special. * In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special. Given an array `nums` (consisting of...
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme...
✅ 98.78% Counter and Min-Heap
seat-reservation-manager
1
1
# Intuition\nWhen we think about reserving and unreserving seats, our first thought is that we need to keep track of the available seats in an ordered fashion. We should be able to reserve the smallest available seat quickly and also be able to unreserve any seat efficiently. This leads us to think of data structures l...
90
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **sm...
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
✅ 98.78% Counter and Min-Heap
seat-reservation-manager
1
1
# Intuition\nWhen we think about reserving and unreserving seats, our first thought is that we need to keep track of the available seats in an ordered fashion. We should be able to reserve the smallest available seat quickly and also be able to unreserve any seat efficiently. This leads us to think of data structures l...
90
A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s. * For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special. * In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special. Given an array `nums` (consisting of...
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme...
Beats 94.24% (runtime) and 100% (memory) of users with Python3 (using Counter and MinHeap)
seat-reservation-manager
0
1
# Using Counter and MinHeap\n- Instead of pre-initialization `1` to `n` array, use counter\n- Whenever we unreserve the seat, push that element in heap. Note that all the elements in heap will smaller than the counter.\n- So while reserving the seat, extract min element from heap and if heap is empty, get the value fro...
2
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **sm...
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
Beats 94.24% (runtime) and 100% (memory) of users with Python3 (using Counter and MinHeap)
seat-reservation-manager
0
1
# Using Counter and MinHeap\n- Instead of pre-initialization `1` to `n` array, use counter\n- Whenever we unreserve the seat, push that element in heap. Note that all the elements in heap will smaller than the counter.\n- So while reserving the seat, extract min element from heap and if heap is empty, get the value fro...
2
A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s. * For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special. * In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special. Given an array `nums` (consisting of...
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme...
Python | Optimized Min Heap | O(log n) | 99% T 98% S
seat-reservation-manager
0
1
**Optimized Priority Queue Solution**\n\nOur objective is to reserve and unreserve seats with a set of commands. Ideally we would iterate from 1 to n in order to reserve the inital set of n unreserved seats, and our biggest challenge is reserving seats after a series of seats have been unreserved. We need a way to stor...
1
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **sm...
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
Python | Optimized Min Heap | O(log n) | 99% T 98% S
seat-reservation-manager
0
1
**Optimized Priority Queue Solution**\n\nOur objective is to reserve and unreserve seats with a set of commands. Ideally we would iterate from 1 to n in order to reserve the inital set of n unreserved seats, and our biggest challenge is reserving seats after a series of seats have been unreserved. We need a way to stor...
1
A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s. * For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special. * In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special. Given an array `nums` (consisting of...
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme...
🦅🦀🎃 Efficient Seat Reservation Management: Binary Search vs. Binary Heap
seat-reservation-manager
0
1
# Intuition\n\nIn my first glance, I thought this is a `Binary Search` problem.\nBut after submitting an AC solution, I discovered other methods that use `Binary Heap`.\n\n# Approach\n\n1. Binary Search\n2. Binary Heap\n3. Binary Heap with checkpoint\n\n# Complexity\n\nM: the maximum number of calls made.\nN: value of ...
1
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **sm...
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
🦅🦀🎃 Efficient Seat Reservation Management: Binary Search vs. Binary Heap
seat-reservation-manager
0
1
# Intuition\n\nIn my first glance, I thought this is a `Binary Search` problem.\nBut after submitting an AC solution, I discovered other methods that use `Binary Heap`.\n\n# Approach\n\n1. Binary Search\n2. Binary Heap\n3. Binary Heap with checkpoint\n\n# Complexity\n\nM: the maximum number of calls made.\nN: value of ...
1
A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s. * For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special. * In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special. Given an array `nums` (consisting of...
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme...
【Video】Give me 5 minutes - How we think about a solution
maximum-element-after-decreasing-and-rearranging
1
1
# Intuition\nSort input array at first.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/1XhaQo-cDVg\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`0:19` Important condition\n`0:56` Demonstrate how it works\n`3:08` What if we have a lot of the same numbers in input array?\n`4:10` Coding\n...
44
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
【Video】Give me 5 minutes - How we think about a solution
maximum-element-after-decreasing-and-rearranging
1
1
# Intuition\nSort input array at first.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/1XhaQo-cDVg\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`0:19` Important condition\n`0:56` Demonstrate how it works\n`3:08` What if we have a lot of the same numbers in input array?\n`4:10` Coding\n...
44
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
easy C++/Python sort & loop vs freq count O(n)||30ms beats 100%
maximum-element-after-decreasing-and-rearranging
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSort the `arr` at once.\nSet `arr[0]=1`. Then iterate the `arr`.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInside of the loop just do one thing\n```\nif (arr[i]-arr[i-1]>1)\n arr[i]=arr[i-1]+1;\n```\nAt fina...
14
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
easy C++/Python sort & loop vs freq count O(n)||30ms beats 100%
maximum-element-after-decreasing-and-rearranging
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSort the `arr` at once.\nSet `arr[0]=1`. Then iterate the `arr`.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInside of the loop just do one thing\n```\nif (arr[i]-arr[i-1]>1)\n arr[i]=arr[i-1]+1;\n```\nAt fina...
14
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || EXPLAINED🔥
maximum-element-after-decreasing-and-rearranging
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Greedy)***\n1. **Function Signature:**\n\n - The `maximumElementAfterDecrementingAndRearranging` function takes a reference to a vector of integers as its input argument.\n - It\'s a public member functi...
4
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || EXPLAINED🔥
maximum-element-after-decreasing-and-rearranging
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Greedy)***\n1. **Function Signature:**\n\n - The `maximumElementAfterDecrementingAndRearranging` function takes a reference to a vector of integers as its input argument.\n - It\'s a public member functi...
4
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
🥇 C++ | PYTHON | JAVA || EXPLAINED || ; ] ✅
maximum-element-after-decreasing-and-rearranging
1
1
\n**UPVOTE IF HELPFuuL**\n\n# Key Points\n- First element is always ```1```\n- Array is always ascending [ increasing order ]\n- Element equal or greater than ```1``` is possible in final array from previous element.\n\n\n# Approach\nIt is defined that the first element always remains one and array is sorted in ascendi...
29
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
🥇 C++ | PYTHON | JAVA || EXPLAINED || ; ] ✅
maximum-element-after-decreasing-and-rearranging
1
1
\n**UPVOTE IF HELPFuuL**\n\n# Key Points\n- First element is always ```1```\n- Array is always ascending [ increasing order ]\n- Element equal or greater than ```1``` is possible in final array from previous element.\n\n\n# Approach\nIt is defined that the first element always remains one and array is sorted in ascendi...
29
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
✅ One Line Solution
maximum-element-after-decreasing-and-rearranging
0
1
# Complexity\n- Time complexity: $$O(n*log(n))$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code #1 - Oneliner\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n return reduce(lambda r, n: min(r + 1, n), sorted(arr)[1:], 1)\n```\n# Code #2 - Oneliner\n```\ncl...
2
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
✅ One Line Solution
maximum-element-after-decreasing-and-rearranging
0
1
# Complexity\n- Time complexity: $$O(n*log(n))$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code #1 - Oneliner\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n return reduce(lambda r, n: min(r + 1, n), sorted(arr)[1:], 1)\n```\n# Code #2 - Oneliner\n```\ncl...
2
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
Intuitive sorting approach with comments!😸
maximum-element-after-decreasing-and-rearranging
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)$$ --> O(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$...
2
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
Intuitive sorting approach with comments!😸
maximum-element-after-decreasing-and-rearranging
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)$$ --> O(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$...
2
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
A somewhat elegant approach
maximum-element-after-decreasing-and-rearranging
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach can be broken down in a few steps:\n>sort the array\n>make the first element 1(in some edge cases it might not be)\n>run a for loop that will change the...
1
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
A somewhat elegant approach
maximum-element-after-decreasing-and-rearranging
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach can be broken down in a few steps:\n>sort the array\n>make the first element 1(in some edge cases it might not be)\n>run a for loop that will change the...
1
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
Easy-Sort.py
maximum-element-after-decreasing-and-rearranging
0
1
# Complexity\n- Time complexity:\n $$O(N\'logN )$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n arr[0]=1\n for i in range(1,len(arr)):\n if arr[i]-arr[i-1]>1:arr[i]=a...
8
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
Easy-Sort.py
maximum-element-after-decreasing-and-rearranging
0
1
# Complexity\n- Time complexity:\n $$O(N\'logN )$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n arr[0]=1\n for i in range(1,len(arr)):\n if arr[i]-arr[i-1]>1:arr[i]=a...
8
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
Python || Beats 100% || beginner friendly
maximum-element-after-decreasing-and-rearranging
0
1
\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n max_val = 1\n\n for i in range(1, len(arr)):\n if arr[i] > max_val:\n max_val += 1\n\n return max_val\n```
1
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
Python || Beats 100% || beginner friendly
maximum-element-after-decreasing-and-rearranging
0
1
\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n max_val = 1\n\n for i in range(1, len(arr)):\n if arr[i] > max_val:\n max_val += 1\n\n return max_val\n```
1
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
Simple Solution Beats 100% Runtime
maximum-element-after-decreasing-and-rearranging
0
1
# Intuition\n\nMy first thought was to return the lesser of the length of the array and the maximum value in the array:\n\n`return (maxx if (maxx:=max(arr)) < (l:=len(arr)) else l)`\n\nHowever, this approach fails because the case where most of the elements of an array are small, and only a single or few rare elements ...
1
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs...
null
Simple Solution Beats 100% Runtime
maximum-element-after-decreasing-and-rearranging
0
1
# Intuition\n\nMy first thought was to return the lesser of the length of the array and the maximum value in the array:\n\n`return (maxx if (maxx:=max(arr)) < (l:=len(arr)) else l)`\n\nHowever, this approach fails because the case where most of the elements of an array are small, and only a single or few rare elements ...
1
There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point. Every day, each cell infected with a viru...
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
Best Solution Explained
closest-room
1
1
\n```\nclass Solution {\n public int[] closestRoom(int[][] rooms, int[][] queries) {\n int n = rooms.length, k = queries.length;\n Integer[] indexes = new Integer[k];\n for (int i = 0; i < k; i++) indexes[i] = i;\n Arrays.sort(rooms, (a, b) -> Integer.compare(b[1], a[1])); //Sort by decre...
0
There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where `rooms[i] = [roomIdi, sizei]` denotes that there is a room with room number `roomIdi` and size equal to `sizei`. Each `roomIdi` is guaranteed to be **unique**. You are also given `k` queries in a 2D array `queries` where `qu...
Search for the largest integer in the range [0, n - k] This integer is the first element in the subarray. You should take it with the k - 1 elements after it.
Best Solution Explained
closest-room
1
1
\n```\nclass Solution {\n public int[] closestRoom(int[][] rooms, int[][] queries) {\n int n = rooms.length, k = queries.length;\n Integer[] indexes = new Integer[k];\n for (int i = 0; i < k; i++) indexes[i] = i;\n Arrays.sort(rooms, (a, b) -> Integer.compare(b[1], a[1])); //Sort by decre...
0
A **fancy string** is a string where no **three** **consecutive** characters are equal. Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**. Return _the final string after the deletion_. It can be shown that the answer will always be **unique**. **Example 1:** **In...
Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time.
Straightforward
minimum-distance-to-the-target-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` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
Straightforward
minimum-distance-to-the-target-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
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Python easy solution .
minimum-distance-to-the-target-element
0
1
\n# Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n x = []\n for i in range(len(nums)):\n if nums[i] == target:\n x.append(abs(i- start))\n return min(x)\n```
1
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
Python easy solution .
minimum-distance-to-the-target-element
0
1
\n# Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n x = []\n for i in range(len(nums)):\n if nums[i] == target:\n x.append(abs(i- start))\n return min(x)\n```
1
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
minimum-distance-to-the-target-element
minimum-distance-to-the-target-element
0
1
# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @param {number} start\n * @return {number}\n */\nvar getMinDistance = function(nums, t, s) {\n let o = Number.POSITIVE_INFINITY;\n for(let i = 0; i<nums.length;i++){\n if(nums[i]==t){\n o = Math.min(o,Math.ab...
1
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
minimum-distance-to-the-target-element
minimum-distance-to-the-target-element
0
1
# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @param {number} start\n * @return {number}\n */\nvar getMinDistance = function(nums, t, s) {\n let o = Number.POSITIVE_INFINITY;\n for(let i = 0; i<nums.length;i++){\n if(nums[i]==t){\n o = Math.min(o,Math.ab...
1
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Python Easy Solution
minimum-distance-to-the-target-element
0
1
# Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n curVal=len(nums)\n for i in range(start,len(nums)):\n if nums[i]==target:\n curVal=min(curVal,abs(i-start))\n break\n j=start\n while(j>=0):...
1
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
Python Easy Solution
minimum-distance-to-the-target-element
0
1
# Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n curVal=len(nums)\n for i in range(start,len(nums)):\n if nums[i]==target:\n curVal=min(curVal,abs(i-start))\n break\n j=start\n while(j>=0):...
1
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
[Python3] linear sweep
minimum-distance-to-the-target-element
0
1
\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n ans = inf\n for i, x in enumerate(nums): \n if x == target: \n ans = min(ans, abs(i - start))\n return ans \n```
13
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
[Python3] linear sweep
minimum-distance-to-the-target-element
0
1
\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n ans = inf\n for i, x in enumerate(nums): \n if x == target: \n ans = min(ans, abs(i - start))\n return ans \n```
13
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
1-liner py3
minimum-distance-to-the-target-element
0
1
# Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n return min(abs(i - start) for i, v in enumerate(nums) if v == target)\n```
0
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
1-liner py3
minimum-distance-to-the-target-element
0
1
# Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n return min(abs(i - start) for i, v in enumerate(nums) if v == target)\n```
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Easy Solution
minimum-distance-to-the-target-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)$$ --...
0
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
Easy Solution
minimum-distance-to-the-target-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)$$ --...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).