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 (Simple Hashmap)
triples-with-bitwise-and-equal-to-zero
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 number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
Python (Simple Hashmap)
triples-with-bitwise-and-equal-to-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
Something like 3sum
triples-with-bitwise-and-equal-to-zero
0
1
# Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n res = 0\n freq = {}\n n = len(nums)\n for i in range(n):\n for j in range(n):\n t = nums[i]&nums[j]\n if t not in freq:\n freq[t] = 0\n ...
1
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
Something like 3sum
triples-with-bitwise-and-equal-to-zero
0
1
# Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n res = 0\n freq = {}\n n = len(nums)\n for i in range(n):\n for j in range(n):\n t = nums[i]&nums[j]\n if t not in freq:\n freq[t] = 0\n ...
1
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
Python 3: Galaxy Brain: Walsh-Hadamard-Like Transform, O(max*log(max) + N) Time, O(max) Space
triples-with-bitwise-and-equal-to-zero
0
1
# Intro\n\nI read [this solution](https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/) by @basselbakr and was amazed, but also completely mystified by how it works.\n\nA couple of sources have some insights, but were VERY dense and IMO could be explained much better. For example, they discuss FFTs (Fa...
1
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
Python 3: Galaxy Brain: Walsh-Hadamard-Like Transform, O(max*log(max) + N) Time, O(max) Space
triples-with-bitwise-and-equal-to-zero
0
1
# Intro\n\nI read [this solution](https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/) by @basselbakr and was amazed, but also completely mystified by how it works.\n\nA couple of sources have some insights, but were VERY dense and IMO could be explained much better. For example, they discuss FFTs (Fa...
1
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
[Python3] hash table
triples-with-bitwise-and-equal-to-zero
0
1
\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ...
4
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
[Python3] hash table
triples-with-bitwise-and-equal-to-zero
0
1
\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ...
4
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
Trie based approach
triples-with-bitwise-and-equal-to-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nUse trie to count the value values effectively.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nTrie carries and extra variable "count" to count the number of values are under it.\n\n\ncountTriplets Method:\nme...
0
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
Trie based approach
triples-with-bitwise-and-equal-to-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nUse trie to count the value values effectively.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nTrie carries and extra variable "count" to count the number of values are under it.\n\n\ncountTriplets Method:\nme...
0
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
[Python3] 5 LOC; 3 sum variation, O(N**2)
triples-with-bitwise-and-equal-to-zero
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
[Python3] 5 LOC; 3 sum variation, O(N**2)
triples-with-bitwise-and-equal-to-zero
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
python dp top down
triples-with-bitwise-and-equal-to-zero
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, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
python dp top down
triples-with-bitwise-and-equal-to-zero
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 series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
Linear Algebra and Dimensional Reduction | Commented and Explained | O(N) time and space
triples-with-bitwise-and-equal-to-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo get this problem would really suck if you don\'t have linear algebra background. This is because you can take the problem, which naively runs in O(N^3), and reduce to O(N) if you are clever about it. To pull this off we need to realize...
0
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
Linear Algebra and Dimensional Reduction | Commented and Explained | O(N) time and space
triples-with-bitwise-and-equal-to-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo get this problem would really suck if you don\'t have linear algebra background. This is because you can take the problem, which naively runs in O(N^3), and reduce to O(N) if you are clever about it. To pull this off we need to realize...
0
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
Python - 5 lines, 3 sum variation, O(N**2)
triples-with-bitwise-and-equal-to-zero
0
1
# Intuition\nStore pairs of indices AND results and then compare each index value with stored values, storing should record number of repeats per AND value\n\n# Approach\nNested loop everything with everything (quadratic), count how many times each and sum repeats, then run again loop for every value check if there is ...
0
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
Python - 5 lines, 3 sum variation, O(N**2)
triples-with-bitwise-and-equal-to-zero
0
1
# Intuition\nStore pairs of indices AND results and then compare each index value with stored values, storing should record number of repeats per AND value\n\n# Approach\nNested loop everything with everything (quadratic), count how many times each and sum repeats, then run again loop for every value check if there is ...
0
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
Python3 🐍 concise solution beats 99%
triples-with-bitwise-and-equal-to-zero
0
1
# Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ...
0
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** ...
null
Python3 🐍 concise solution beats 99%
triples-with-bitwise-and-equal-to-zero
0
1
# Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ...
0
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. ...
null
Python Top Down/ Bottom Up Solution for reference
minimum-cost-for-tickets
0
1
1. Top Down method\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n # Variable definitions\n # dp: stores results from index , key till len(n)\n # idx: starting index from which we are calculating\n # res: storing the final results\n # t...
1
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold...
null
Python Top Down/ Bottom Up Solution for reference
minimum-cost-for-tickets
0
1
1. Top Down method\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n # Variable definitions\n # dp: stores results from index , key till len(n)\n # idx: starting index from which we are calculating\n # res: storing the final results\n # t...
1
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. * Replacing the number `n` on the chalkboard with `n - x`. Also, if a player...
null
Python
minimum-cost-for-tickets
0
1
# Complexity\n- Time complexity: 38*n\n\n\n# Code\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp = {}\n\n def dfs(i):\n if i==len(days):\n return 0\n if i in dp:\n return dp[i]\n dp[i] = flo...
1
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold...
null
Python
minimum-cost-for-tickets
0
1
# Complexity\n- Time complexity: 38*n\n\n\n# Code\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp = {}\n\n def dfs(i):\n if i==len(days):\n return 0\n if i in dp:\n return dp[i]\n dp[i] = flo...
1
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. * Replacing the number `n` on the chalkboard with `n - x`. Also, if a player...
null
40MS || 87% BEATS||SIMPLE SOLUTION USING DP|| PYTHON
minimum-cost-for-tickets
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 have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold...
null
40MS || 87% BEATS||SIMPLE SOLUTION USING DP|| PYTHON
minimum-cost-for-tickets
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
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. * Replacing the number `n` on the chalkboard with `n - x`. Also, if a player...
null
python3 Solution
minimum-cost-for-tickets
0
1
\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp7=deque()\n dp30=deque()\n cost=0\n \n for d in days:\n while dp7 and dp7[0][0]<=d-7:\n dp7.popleft()\n \n while dp30 and dp30[0][0]<...
1
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold...
null
python3 Solution
minimum-cost-for-tickets
0
1
\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp7=deque()\n dp30=deque()\n cost=0\n \n for d in days:\n while dp7 and dp7[0][0]<=d-7:\n dp7.popleft()\n \n while dp30 and dp30[0][0]<...
1
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. * Replacing the number `n` on the chalkboard with `n - x`. Also, if a player...
null
Solution
minimum-cost-for-tickets
1
1
```C++ []\nclass Solution {\npublic:\n int mincostTickets(vector<int>& days, vector<int>& costs) {\n sort(days.begin(), days.end());\n int n=days.size();\n vector<int> dp(n+1, 0);\n dp[n] = 0;\n\n for(int i=n-1; i>=0; i--) {\n int t1 = 0, t2 = 0, t3 = 0;\n t1 ...
1
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold...
null
Solution
minimum-cost-for-tickets
1
1
```C++ []\nclass Solution {\npublic:\n int mincostTickets(vector<int>& days, vector<int>& costs) {\n sort(days.begin(), days.end());\n int n=days.size();\n vector<int> dp(n+1, 0);\n dp[n] = 0;\n\n for(int i=n-1; i>=0; i--) {\n int t1 = 0, t2 = 0, t3 = 0;\n t1 ...
1
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. * Replacing the number `n` on the chalkboard with `n - x`. Also, if a player...
null
Python3 || 39 ms || Beats 91.51 % (DP)
minimum-cost-for-tickets
0
1
The mincostTickets function takes in two arguments: days, a list of integers representing the days on which you want to travel, and costs, a list of integers representing the costs for a 1-day, 7-day, and 30-day travel pass, respectively.\n\nThe function initializes the cost to zero and two deques last7 and last30, whi...
41
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold...
null
Python3 || 39 ms || Beats 91.51 % (DP)
minimum-cost-for-tickets
0
1
The mincostTickets function takes in two arguments: days, a list of integers representing the days on which you want to travel, and costs, a list of integers representing the costs for a 1-day, 7-day, and 30-day travel pass, respectively.\n\nThe function initializes the cost to zero and two deques last7 and last30, whi...
41
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. * Replacing the number `n` on the chalkboard with `n - x`. Also, if a player...
null
Python3 🐍 concise solution beats 99%
string-without-aaa-or-bbb
0
1
# Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[-2:] == [\'a\', \'a\']:\n res.append(\'b\')\n b-=1\n elif len(res) >= 2 and res[-2:] == [\'b\', \'b\']:\n ...
1
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:...
null
Python3 🐍 concise solution beats 99%
string-without-aaa-or-bbb
0
1
# Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[-2:] == [\'a\', \'a\']:\n res.append(\'b\')\n b-=1\n elif len(res) >= 2 and res[-2:] == [\'b\', \'b\']:\n ...
1
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. **Example 1:** **Input...
null
Solution
string-without-aaa-or-bbb
1
1
```C++ []\nclass Solution {\npublic:\n void generator(string &arr,int &a,int &b){\n if (a<=0 && b<=0){\n return;\n }\n if(a>b){\n if(a>=2){\n arr=arr+"aa";\n a-=2;\n }\n else{\n arr=arr+\'a\';\n ...
1
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:...
null
Solution
string-without-aaa-or-bbb
1
1
```C++ []\nclass Solution {\npublic:\n void generator(string &arr,int &a,int &b){\n if (a<=0 && b<=0){\n return;\n }\n if(a>b){\n if(a>=2){\n arr=arr+"aa";\n a-=2;\n }\n else{\n arr=arr+\'a\';\n ...
1
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. **Example 1:** **Input...
null
[Python]: O(a+b) solution with explanation: build a string based on sub-string patterns
string-without-aaa-or-bbb
0
1
# Intuition\n1. every substring will be based on the following building blocks\n - "aab" or "ab" (assume a > b, else swap a and b)\n2. there is a special case when a > 2xb (e.g. a = 3, b = 1). In this case, add the difference in a and 2xb in as at the end. This number will be either 1 or 2, otherwise the input would...
0
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:...
null
[Python]: O(a+b) solution with explanation: build a string based on sub-string patterns
string-without-aaa-or-bbb
0
1
# Intuition\n1. every substring will be based on the following building blocks\n - "aab" or "ab" (assume a > b, else swap a and b)\n2. there is a special case when a > 2xb (e.g. a = 3, b = 1). In this case, add the difference in a and 2xb in as at the end. This number will be either 1 or 2, otherwise the input would...
0
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. **Example 1:** **Input...
null
✅conditioonal code || pytthon
string-without-aaa-or-bbb
0
1
\n\n# Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if(a==0 and b==0):return ""\n ans=""\n n=a+b\n i=0\n while(i<n):\n if(len(ans)<2):\n if(a>b):\n ans+="a"\n a-=1\n els...
0
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:...
null
✅conditioonal code || pytthon
string-without-aaa-or-bbb
0
1
\n\n# Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if(a==0 and b==0):return ""\n ans=""\n n=a+b\n i=0\n while(i<n):\n if(len(ans)<2):\n if(a>b):\n ans+="a"\n a-=1\n els...
0
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. **Example 1:** **Input...
null
Python Sol without loop, beats 100%
string-without-aaa-or-bbb
0
1
\n# Code\n```\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n if A >= 2*B:\n return \'aab\'* B + \'a\'* (A-2*B)\n elif A >= B:\n return \'aab\' * (A-B) + \'ab\' * (2*B - A)\n ...
0
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:...
null
Python Sol without loop, beats 100%
string-without-aaa-or-bbb
0
1
\n# Code\n```\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n if A >= 2*B:\n return \'aab\'* B + \'a\'* (A-2*B)\n elif A >= B:\n return \'aab\' * (A-B) + \'ab\' * (2*B - A)\n ...
0
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`. **Example 1:** **Input...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
sum-of-even-numbers-after-queries
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R...
58
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Exam...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
sum-of-even-numbers-after-queries
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R...
58
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `s...
null
Solution
sum-of-even-numbers-after-queries
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n int S = 0;\n for (int x: nums)\n if (x % 2 == 0)\n S += x;\n\n vector<int> ans(queries.size());\n\n for (int i = 0; i < queries.size(); ++i...
1
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Exam...
null
Solution
sum-of-even-numbers-after-queries
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n int S = 0;\n for (int x: nums)\n if (x % 2 == 0)\n S += x;\n\n vector<int> ans(queries.size());\n\n for (int i = 0; i < queries.size(); ++i...
1
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `s...
null
Easy python solution
sum-of-even-numbers-after-queries
0
1
```\nclass Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n sm=0\n for i in range(len(nums)):\n if nums[i]%2==0:\n sm+=nums[i]\n lst=[]\n for i in range(len(queries)):\n prev=nums[queries[i][1]]\n ...
5
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Exam...
null
Easy python solution
sum-of-even-numbers-after-queries
0
1
```\nclass Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n sm=0\n for i in range(len(nums)):\n if nums[i]%2==0:\n sm+=nums[i]\n lst=[]\n for i in range(len(queries)):\n prev=nums[queries[i][1]]\n ...
5
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `s...
null
[Python3] Memory Usage beats 99.49% Space O(1) (no extra array)
sum-of-even-numbers-after-queries
0
1
The solution is straight-forward. First we get the sum of all even numbers in **nums** and call it **s**. \nDuring each query **q**, if nums[q[0]] is even, we subtract it from our current **s**, otherwise we do nothing. \nThen we update `nums[q[0]] += q[1]`. If THIS **nums[q[0]]** is even, we add it to **s** again. Aft...
2
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Exam...
null
[Python3] Memory Usage beats 99.49% Space O(1) (no extra array)
sum-of-even-numbers-after-queries
0
1
The solution is straight-forward. First we get the sum of all even numbers in **nums** and call it **s**. \nDuring each query **q**, if nums[q[0]] is even, we subtract it from our current **s**, otherwise we do nothing. \nThen we update `nums[q[0]] += q[1]`. If THIS **nums[q[0]]** is even, we add it to **s** again. Aft...
2
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `s...
null
Python Segment Tree Approach + Query Traversal Approach
sum-of-even-numbers-after-queries
0
1
```\nclass SegmentTree:\n def __init__(self, arr, function):\n self.tree = [None for _ in range(len(arr))] + arr\n self.n = len(arr)\n self.fn = function\n self.build_tree()\n\n def build_tree(self):\n for i in range(self.n - 1, 0, -1):\n self.tree[i] = self.fn(self.t...
2
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Exam...
null
Python Segment Tree Approach + Query Traversal Approach
sum-of-even-numbers-after-queries
0
1
```\nclass SegmentTree:\n def __init__(self, arr, function):\n self.tree = [None for _ in range(len(arr))] + arr\n self.n = len(arr)\n self.fn = function\n self.build_tree()\n\n def build_tree(self):\n for i in range(self.n - 1, 0, -1):\n self.tree[i] = self.fn(self.t...
2
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `s...
null
Python Solution || With Explanation || Easy to understand
sum-of-even-numbers-after-queries
0
1
# APPROACH:-\n* Store Intial sum of even and odd values present in the array.\n* Initiatize output array/list and start traversing the queries\n* if value at provided index is even then subtract it from even count. if it\'s odd leave it.\n* Update the nums array as ` nums[idx] = nums[idx] + val` . where idx is the inde...
1
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Exam...
null
Python Solution || With Explanation || Easy to understand
sum-of-even-numbers-after-queries
0
1
# APPROACH:-\n* Store Intial sum of even and odd values present in the array.\n* Initiatize output array/list and start traversing the queries\n* if value at provided index is even then subtract it from even count. if it\'s odd leave it.\n* Update the nums array as ` nums[idx] = nums[idx] + val` . where idx is the inde...
1
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `s...
null
Solution recursive in python
interval-list-intersections
0
1
# Code\n```\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n n1, n2 = len(firstList), len(secondList)\n if n1==0 or n2==0:\n return []\n e1, e2 = firstList[0], secondList[0]\n startPoint = e1[0]\n ...
3
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a...
null
Solution recursive in python
interval-list-intersections
0
1
# Code\n```\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n n1, n2 = len(firstList), len(secondList)\n if n1==0 or n2==0:\n return []\n e1, e2 = firstList[0], secondList[0]\n startPoint = e1[0]\n ...
3
We run a preorder depth-first search (DFS) on the `root` of a binary tree. At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`. ...
null
Python two pointers solution
interval-list-intersections
0
1
**Python :**\n\n```\ndef intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n\tif firstList == [] or secondList == []:\n\t\treturn []\n\n\tres = []\n\ti, j = 0, 0\n\n\twhile i < len(firstList) and j < len(secondList):\n\t\tl = max(firstList[i][0], secondList[j][0])\n...
17
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a...
null
Python two pointers solution
interval-list-intersections
0
1
**Python :**\n\n```\ndef intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n\tif firstList == [] or secondList == []:\n\t\treturn []\n\n\tres = []\n\ti, j = 0, 0\n\n\twhile i < len(firstList) and j < len(secondList):\n\t\tl = max(firstList[i][0], secondList[j][0])\n...
17
We run a preorder depth-first search (DFS) on the `root` of a binary tree. At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`. ...
null
78% TC and 84% SC easy python solution
interval-list-intersections
0
1
```\ndef intervalIntersection(self, fir: List[List[int]], sec: List[List[int]]) -> List[List[int]]:\n\tans = []\n\tl1 = len(fir)\n\tl2 = len(sec)\n\ti = j = 0\n\twhile(i < l1 and j < l2):\n\t\tif(fir[i][1] < sec[j][0]): i += 1\n\t\telif(sec[j][1] < fir[i][0]): j += 1\n\t\telif(fir[i][0] <= sec[j][0] and sec[j][1] <= fi...
1
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a...
null
78% TC and 84% SC easy python solution
interval-list-intersections
0
1
```\ndef intervalIntersection(self, fir: List[List[int]], sec: List[List[int]]) -> List[List[int]]:\n\tans = []\n\tl1 = len(fir)\n\tl2 = len(sec)\n\ti = j = 0\n\twhile(i < l1 and j < l2):\n\t\tif(fir[i][1] < sec[j][0]): i += 1\n\t\telif(sec[j][1] < fir[i][0]): j += 1\n\t\telif(fir[i][0] <= sec[j][0] and sec[j][1] <= fi...
1
We run a preorder depth-first search (DFS) on the `root` of a binary tree. At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`. ...
null
As easy as it comes(plain English), python3 solution with complexity analysis
interval-list-intersections
0
1
```\nclass Solution:\n # O(n + m) time,\n # O(n + m) space,\n # Approach: two pointers\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n ans = []\n n = len(firstList)\n m = len(secondList)\n \n def findIntersect...
1
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a...
null
As easy as it comes(plain English), python3 solution with complexity analysis
interval-list-intersections
0
1
```\nclass Solution:\n # O(n + m) time,\n # O(n + m) space,\n # Approach: two pointers\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n ans = []\n n = len(firstList)\n m = len(secondList)\n \n def findIntersect...
1
We run a preorder depth-first search (DFS) on the `root` of a binary tree. At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`. ...
null
Python3, easy to understand. Not too pythonic
interval-list-intersections
0
1
Let me know if you have any questions! I feel like the comments are self-explantory. There are ways to make this code less, but I was lazy and didn\'t feel like doing it. i.e. we could get rid of the min function and do a manual if-else condition.\n\nHope this helps :)\n\n```\nclass Solution:\n def intervalIntersect...
1
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a...
null
Python3, easy to understand. Not too pythonic
interval-list-intersections
0
1
Let me know if you have any questions! I feel like the comments are self-explantory. There are ways to make this code less, but I was lazy and didn\'t feel like doing it. i.e. we could get rid of the min function and do a manual if-else condition.\n\nHope this helps :)\n\n```\nclass Solution:\n def intervalIntersect...
1
We run a preorder depth-first search (DFS) on the `root` of a binary tree. At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`. ...
null
Solution in python using comparator class || Simple Traversal || hashmap
vertical-order-traversal-of-a-binary-tree
0
1
```\nfrom functools import cmp_to_key\n\n# comparator class for compare two elements in sorting to handle the cases which have same y but differ x\n# for eg self -> [(1,2), [3,4,..]] where (1,2) pair is (x,y) and [3,4,...] are the values of node that have same (x,y)\nclass Compare:\n def main(self,elm):\n\t\t# compa...
1
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** o...
null
Solution in python using comparator class || Simple Traversal || hashmap
vertical-order-traversal-of-a-binary-tree
0
1
```\nfrom functools import cmp_to_key\n\n# comparator class for compare two elements in sorting to handle the cases which have same y but differ x\n# for eg self -> [(1,2), [3,4,..]] where (1,2) pair is (x,y) and [3,4,...] are the values of node that have same (x,y)\nclass Compare:\n def main(self,elm):\n\t\t# compa...
1
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people...
null
Python BFS + Hashmap
vertical-order-traversal-of-a-binary-tree
0
1
```\nclass Solution:\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n results = defaultdict(list)\n \n queue = [ (root, 0, 0) ]\n \n while queue:\n node, pos, depth = queue.pop(0)\n if not node: continue\n results[(pos,d...
17
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** o...
null
Python BFS + Hashmap
vertical-order-traversal-of-a-binary-tree
0
1
```\nclass Solution:\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n results = defaultdict(list)\n \n queue = [ (root, 0, 0) ]\n \n while queue:\n node, pos, depth = queue.pop(0)\n if not node: continue\n results[(pos,d...
17
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people...
null
Python3 || 31 ms, faster than 96.95% of Python3 || Clean and Easy to Understand
vertical-order-traversal-of-a-binary-tree
0
1
```\ndef verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n d=defaultdict(list)\n q=deque()\n q.append([root,0,0])\n while(q):\n node,row,col=q.popleft()\n d[col].append([node.val,row])\n if node.left:\n q.append([node.left...
2
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** o...
null
Python3 || 31 ms, faster than 96.95% of Python3 || Clean and Easy to Understand
vertical-order-traversal-of-a-binary-tree
0
1
```\ndef verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n d=defaultdict(list)\n q=deque()\n q.append([root,0,0])\n while(q):\n node,row,col=q.popleft()\n d[col].append([node.val,row])\n if node.left:\n q.append([node.left...
2
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people...
null
Solution
smallest-string-starting-from-leaf
1
1
```C++ []\nclass Solution {\npublic:\n void post(TreeNode* root,string s,set<string> &st)\n {\n if(root==NULL)\n return;\n \n s+=char(root->val+\'a\');\n if(root->left==NULL && root->right==NULL)\n {\n string temp=s;\n reverse(temp.begin(...
1
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller...
null
Solution
smallest-string-starting-from-leaf
1
1
```C++ []\nclass Solution {\npublic:\n void post(TreeNode* root,string s,set<string> &st)\n {\n if(root==NULL)\n return;\n \n s+=char(root->val+\'a\');\n if(root->left==NULL && root->right==NULL)\n {\n string temp=s;\n reverse(temp.begin(...
1
You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`. Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest ...
null
[Python] Simple and efficient recursive solution - 98%
smallest-string-starting-from-leaf
0
1
\n# Approach\n- We traverse the the tree and pass path to the node till now as parameter of recursive function\n- When we encounter a leaf node - compare it with lowestPath\n- if we encounter null we end recursive branch\n- for normal node we add value to path and pass on/ call recursive function for it\'s left and rig...
1
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller...
null
[Python] Simple and efficient recursive solution - 98%
smallest-string-starting-from-leaf
0
1
\n# Approach\n- We traverse the the tree and pass path to the node till now as parameter of recursive function\n- When we encounter a leaf node - compare it with lowestPath\n- if we encounter null we end recursive branch\n- for normal node we add value to path and pass on/ call recursive function for it\'s left and rig...
1
You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`. Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest ...
null
Python3 🐍 concise solution beats 99%
smallest-string-starting-from-leaf
0
1
\n# Code\n```\nclass Solution:\n res = \'z\' * 13 # init max result, tree depth, 12< log2(8000) < 13\n \n def smallestFromLeaf(self, root: TreeNode) -> str:\n \n def helper(node: TreeNode, prev):\n prev = chr(97 + node.val) + prev\n \n if not node.left ...
1
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller...
null
Python3 🐍 concise solution beats 99%
smallest-string-starting-from-leaf
0
1
\n# Code\n```\nclass Solution:\n res = \'z\' * 13 # init max result, tree depth, 12< log2(8000) < 13\n \n def smallestFromLeaf(self, root: TreeNode) -> str:\n \n def helper(node: TreeNode, prev):\n prev = chr(97 + node.val) + prev\n \n if not node.left ...
1
You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`. Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest ...
null
[Python3] | DFS +Sorting
smallest-string-starting-from-leaf
0
1
```\nclass Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n ans=[]\n def dfs(root,ds):\n ds.append(chr(97+root.val))\n if not root.left and not root.right:\n ans.append("".join(ds[:]))\n return\n if root.left:\n ...
1
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller...
null
[Python3] | DFS +Sorting
smallest-string-starting-from-leaf
0
1
```\nclass Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n ans=[]\n def dfs(root,ds):\n ds.append(chr(97+root.val))\n if not root.left and not root.right:\n ans.append("".join(ds[:]))\n return\n if root.left:\n ...
1
You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`. Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest ...
null
Pythonic Solution
smallest-string-starting-from-leaf
0
1
# Code\n```python\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode], pre: str = \'\') -> str:\n ...
0
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller...
null
Pythonic Solution
smallest-string-starting-from-leaf
0
1
# Code\n```python\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode], pre: str = \'\') -> str:\n ...
0
You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`. Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest ...
null
Python 95% beats || 2 Approach || Simple Code
add-to-array-form-of-integer
0
1
**If you got help from this,... Plz Upvote .. it encourage me**\n# Code\n# Approach 1 Array\n```\nclass Solution(object):\n def addToArrayForm(self, A, K):\n A[-1] += K\n for i in range(len(A) - 1, -1, -1):\n carry, A[i] = divmod(A[i], 10)\n if i: A[i-1] += carry\n if carry...
1
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
Python 95% beats || 2 Approach || Simple Code
add-to-array-form-of-integer
0
1
**If you got help from this,... Plz Upvote .. it encourage me**\n# Code\n# Approach 1 Array\n```\nclass Solution(object):\n def addToArrayForm(self, A, K):\n A[-1] += K\n for i in range(len(A) - 1, -1, -1):\n carry, A[i] = divmod(A[i], 10)\n if i: A[i-1] += carry\n if carry...
1
Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`. The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlap...
null
Two simple approaches in python.
add-to-array-form-of-integer
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach - 1\n<!-- Describe your approach to solving the problem. -->\nThe implementation first concatenates the digits in $$num$$ into a single string using $$map$$ and $$join$$, then converts the resulting string to an integer using...
1
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
Two simple approaches in python.
add-to-array-form-of-integer
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach - 1\n<!-- Describe your approach to solving the problem. -->\nThe implementation first concatenates the digits in $$num$$ into a single string using $$map$$ and $$join$$, then converts the resulting string to an integer using...
1
Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`. The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlap...
null
Python3 👍||⚡ 83/86 T/M beats,only 1 line 🔥|| clean solution ||
add-to-array-form-of-integer
0
1
![image.png](https://assets.leetcode.com/users/images/b84c6966-85ac-4be2-9516-79f2544be0b3_1676430257.517687.png)\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:...
1
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
Python3 👍||⚡ 83/86 T/M beats,only 1 line 🔥|| clean solution ||
add-to-array-form-of-integer
0
1
![image.png](https://assets.leetcode.com/users/images/b84c6966-85ac-4be2-9516-79f2544be0b3_1676430257.517687.png)\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:...
1
Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`. The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlap...
null
🔥🚀Simplest Solution🚀||🔥Full Explanation||🔥C++🔥|| Python3 || Java
add-to-array-form-of-integer
1
1
# Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n# Intuition\nWe are taking `k` as carry.\nWe start from the last or lowest digit in array `num` add `k`.\nThen **update** `k` and move untill the highest digit.\nAfter traversing array if carry is **>** `0` then we add it to be...
301
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
🔥🚀Simplest Solution🚀||🔥Full Explanation||🔥C++🔥|| Python3 || Java
add-to-array-form-of-integer
1
1
# Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n# Intuition\nWe are taking `k` as carry.\nWe start from the last or lowest digit in array `num` add `k`.\nThen **update** `k` and move untill the highest digit.\nAfter traversing array if carry is **>** `0` then we add it to be...
301
Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`. The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlap...
null
Python short and clean.
add-to-array-form-of-integer
0
1
# Approach\n1. Convert `k` to reversed iterable of digits using `rdigits`.\n\n2. Add backwards, digit by digit with carry, of `num` and `rdigits(k)`\n\n3. Push the results into a queue to un-reverse the sum, and return.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\nwhere, `n is the max...
2
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
Python short and clean.
add-to-array-form-of-integer
0
1
# Approach\n1. Convert `k` to reversed iterable of digits using `rdigits`.\n\n2. Add backwards, digit by digit with carry, of `num` and `rdigits(k)`\n\n3. Push the results into a queue to un-reverse the sum, and return.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\nwhere, `n is the max...
2
Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`. The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlap...
null
PYTHON SOLUTION USING DISJOINT SET
satisfiability-of-equality-equations
0
1
# Intuition\nWE WOULD MAKE ALL alphabet that are equal in same component. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUNION DISJOINT\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --...
1
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names. ...
null
PYTHON SOLUTION USING DISJOINT SET
satisfiability-of-equality-equations
0
1
# Intuition\nWE WOULD MAKE ALL alphabet that are equal in same component. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUNION DISJOINT\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --...
1
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`. For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suf...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
satisfiability-of-equality-equations
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R...
95
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names. ...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
satisfiability-of-equality-equations
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R...
95
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`. For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suf...
null
Solution
satisfiability-of-equality-equations
1
1
```C++ []\nclass DisjointSet{\npublic:\n vector<int>size;\n vector<int>parent;\n DisjointSet(int n){\n size.resize(n,1);\n parent.resize(n);\n for(int i=0;i<n;i++){\n parent[i]=i;\n }\n }\n int findUPar(int node){\n if(parent[node]==node)return node;\n ...
2
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names. ...
null
Solution
satisfiability-of-equality-equations
1
1
```C++ []\nclass DisjointSet{\npublic:\n vector<int>size;\n vector<int>parent;\n DisjointSet(int n){\n size.resize(n,1);\n parent.resize(n);\n for(int i=0;i<n;i++){\n parent[i]=i;\n }\n }\n int findUPar(int node){\n if(parent[node]==node)return node;\n ...
2
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`. For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suf...
null
python3 || 13 lines, sets || 1 T/M: 89%/67%
satisfiability-of-equality-equations
0
1
```\nclass Solution: # Here\'s the plan:\n # 1) We make an undirected graph in which the nodes are integers\n # (as lower-case letters) and each edge connects integers\n # that are equal.\n # 2) We use a union-find process to ...
28
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names. ...
null
python3 || 13 lines, sets || 1 T/M: 89%/67%
satisfiability-of-equality-equations
0
1
```\nclass Solution: # Here\'s the plan:\n # 1) We make an undirected graph in which the nodes are integers\n # (as lower-case letters) and each edge connects integers\n # that are equal.\n # 2) We use a union-find process to ...
28
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`. For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suf...
null
Solution
broken-calculator
1
1
```C++ []\nclass Solution {\n public:\n int brokenCalc(int X, int Y) {\n int ops = 0;\n\n while (X < Y) {\n if (Y % 2 == 0)\n Y /= 2;\n else\n Y += 1;\n ++ops;\n }\n return ops + X - Y;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def brokenCalc(self, startValue: int, t...
1
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: * multiply the number on display by `2`, or * subtract `1` from the number on display. Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `targ...
null
Solution
broken-calculator
1
1
```C++ []\nclass Solution {\n public:\n int brokenCalc(int X, int Y) {\n int ops = 0;\n\n while (X < Y) {\n if (Y % 2 == 0)\n Y /= 2;\n else\n Y += 1;\n ++ops;\n }\n return ops + X - Y;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def brokenCalc(self, startValue: int, t...
1
There are three stones in different positions on the X-axis. You are given three integers `a`, `b`, and `c`, the positions of the stones. In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's s...
null