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 Solution with 92% better Time Complexity
di-string-match
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
Solution
di-string-match
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> diStringMatch(string s) {\n int n = s.length();\n vector<int>v;\n int j = n;\n int k = 0;\n for(int i = 0;i<n+1;i++){\n if(s[i]==\'I\'){\n v.push_back(k);\n k++;\n }\n else ...
2
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null
Solution
di-string-match
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> diStringMatch(string s) {\n int n = s.length();\n vector<int>v;\n int j = n;\n int k = 0;\n for(int i = 0;i<n+1;i++){\n if(s[i]==\'I\'){\n v.push_back(k);\n k++;\n }\n else ...
2
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
[Python3] Simple And Readable Solution
di-string-match
0
1
```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans = []\n a , b = 0 , len(s)\n \n for i in s:\n if(i == \'I\'):\n ans.append(a)\n a += 1\n else:\n ans.append(b)\n b -= 1\n \n ...
7
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null
[Python3] Simple And Readable Solution
di-string-match
0
1
```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans = []\n a , b = 0 , len(s)\n \n for i in s:\n if(i == \'I\'):\n ans.append(a)\n a += 1\n else:\n ans.append(b)\n b -= 1\n \n ...
7
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
DI String Match (simple solution)
di-string-match
0
1
# class Solution:\n def diStringMatch(self, s: str) -> List[int]:\n l=len(s)\n a=-1\n b=l+1\n c=0\n v=[]\n for i in s:\n if i==\'I\':\n a+=1\n c+=1\n v.append(a)\n else:\n b-=1\n ...
1
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null
DI String Match (simple solution)
di-string-match
0
1
# class Solution:\n def diStringMatch(self, s: str) -> List[int]:\n l=len(s)\n a=-1\n b=l+1\n c=0\n v=[]\n for i in s:\n if i==\'I\':\n a+=1\n c+=1\n v.append(a)\n else:\n b-=1\n ...
1
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
Very simple solution in python, with explanations
di-string-match
0
1
the solution can be achieved with a combination of two steps:\n\n=> proceeding forward from s (s=0)\n=> proceeding backwards from l (l = length of string)\nthe code explains the rest. \n\nafter the loop breaks, you still have one more number to append, which that should be?\nEasy! after the loop terminates, s==l, so ap...
14
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null
Very simple solution in python, with explanations
di-string-match
0
1
the solution can be achieved with a combination of two steps:\n\n=> proceeding forward from s (s=0)\n=> proceeding backwards from l (l = length of string)\nthe code explains the rest. \n\nafter the loop breaks, you still have one more number to append, which that should be?\nEasy! after the loop terminates, s==l, so ap...
14
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
Solution
find-the-shortest-superstring
1
1
```C++ []\nclass Solution {\npublic:\n string shortestSuperstring(vector<string>& A) {\n int dp[4096][12] = {0};\n int failure[12][20] = {0};\n int cost[12][12] = {0};\n int trace_table[4096][12] = {0};\n const int sz = A.size();\n const int dp_sz = 1 << sz;\n \n ...
1
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** wo...
null
Solution
find-the-shortest-superstring
1
1
```C++ []\nclass Solution {\npublic:\n string shortestSuperstring(vector<string>& A) {\n int dp[4096][12] = {0};\n int failure[12][20] = {0};\n int cost[12][12] = {0};\n int trace_table[4096][12] = {0};\n const int sz = A.size();\n const int dp_sz = 1 << sz;\n \n ...
1
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles tha...
null
Easy to understand TSP implementation (Top-Down/Bottom-Up)[python]
find-the-shortest-superstring
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nConsider this problem as a graph problem where we need to visit every single node with the minimal overall cost. The words will be our nodes and the nonOverlapping substring between two words will be our cost.\n\n# Complexity\n- Time complexity:\n<!--...
0
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** wo...
null
Easy to understand TSP implementation (Top-Down/Bottom-Up)[python]
find-the-shortest-superstring
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nConsider this problem as a graph problem where we need to visit every single node with the minimal overall cost. The words will be our nodes and the nonOverlapping substring between two words will be our cost.\n\n# Complexity\n- Time complexity:\n<!--...
0
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles tha...
null
Shortest Solution
find-the-shortest-superstring
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 `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** wo...
null
Shortest Solution
find-the-shortest-superstring
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 `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles tha...
null
Smallest Solution
find-the-shortest-superstring
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 `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** wo...
null
Smallest Solution
find-the-shortest-superstring
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 `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles tha...
null
Traveling Salesman Problem Dynamic Programming Held-Karp + Video
find-the-shortest-superstring
0
1
# Intuition\nBefore going on solution please see this video:\n\n[Traveling Salesman Problem Dynamic Programming Held-Karp\n](https://www.youtube.com/watch?v=-JjA4BLQyqE)\n# Code\n```\nclass Solution:\n def get_cost(self, copy_set, prev_vertex, dp):\n copy_set.remove(prev_vertex)\n cost = dp[(prev_verte...
0
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** wo...
null
Traveling Salesman Problem Dynamic Programming Held-Karp + Video
find-the-shortest-superstring
0
1
# Intuition\nBefore going on solution please see this video:\n\n[Traveling Salesman Problem Dynamic Programming Held-Karp\n](https://www.youtube.com/watch?v=-JjA4BLQyqE)\n# Code\n```\nclass Solution:\n def get_cost(self, copy_set, prev_vertex, dp):\n copy_set.remove(prev_vertex)\n cost = dp[(prev_verte...
0
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles tha...
null
Python | DP with memo to solve TSP, fully explained~
find-the-shortest-superstring
0
1
# FIRST THING FIRST\r\nVote me if you like this solution~\r\n\r\n# Intuition\r\nThis is actually a "Traveling Salesman Problem" if we consider each word as a city\r\nAnd the `ticket price` (or `cost`, more generalized) from city to city is the `number of chars` we need to add if we append that word\r\n\r\n# DP analysis...
0
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** wo...
null
Python | DP with memo to solve TSP, fully explained~
find-the-shortest-superstring
0
1
# FIRST THING FIRST\r\nVote me if you like this solution~\r\n\r\n# Intuition\r\nThis is actually a "Traveling Salesman Problem" if we consider each word as a city\r\nAnd the `ticket price` (or `cost`, more generalized) from city to city is the `number of chars` we need to add if we append that word\r\n\r\n# DP analysis...
0
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles tha...
null
Solution
minimum-increment-to-make-array-unique
1
1
```C++ []\n#define rep(i,m,n) for(int i=m;i<n;i++)\n#define all(x) x.begin(),x.end()\n\nclass Solution {\npublic:\n int minIncrementForUnique(vector<int>& a) {\n int mx=*max_element(all(a));\n vector<int> cnt(mx+1,0);\n\n for(auto i:a)\n cnt[i]++;\n \n long ans=0;\n\n ...
1
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input...
null
Solution
minimum-increment-to-make-array-unique
1
1
```C++ []\n#define rep(i,m,n) for(int i=m;i<n;i++)\n#define all(x) x.begin(),x.end()\n\nclass Solution {\npublic:\n int minIncrementForUnique(vector<int>& a) {\n int mx=*max_element(all(a));\n vector<int> cnt(mx+1,0);\n\n for(auto i:a)\n cnt[i]++;\n \n long ans=0;\n\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
PYTHON SOL || WELL EXPLAINED || SORTING ||GREEDY|| APPROACH EXPLAINED || SIMPLE || O(n*log(n))||
minimum-increment-to-make-array-unique
0
1
# EXPLANATION\n```\nWe need to make every number unique :\n Now for a number let\'s say 10 \n We can make it unique by incrementing the number only means we can\'t look below 10\n So the idea here is everytime we are making a number unique we can only go forward\n This gives the idea of sorting \n \n Because if we...
24
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input...
null
PYTHON SOL || WELL EXPLAINED || SORTING ||GREEDY|| APPROACH EXPLAINED || SIMPLE || O(n*log(n))||
minimum-increment-to-make-array-unique
0
1
# EXPLANATION\n```\nWe need to make every number unique :\n Now for a number let\'s say 10 \n We can make it unique by incrementing the number only means we can\'t look below 10\n So the idea here is everytime we are making a number unique we can only go forward\n This gives the idea of sorting \n \n Because if we...
24
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 Solution beats > 85.00%, keep track of next closest unique number
minimum-increment-to-make-array-unique
0
1
# Intuition\n1. Sort the array\n2. Once the array has been sorted, combined with the fact we can **only ** increment numbers, we can keep track of the "next unqiue number"\n3. After sorting, loop through array.\n4. If num[i] is unique (aka not in the set), add number to set and set next_closest_unique_number to nums[i]...
0
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input...
null
Python3 Solution beats > 85.00%, keep track of next closest unique number
minimum-increment-to-make-array-unique
0
1
# Intuition\n1. Sort the array\n2. Once the array has been sorted, combined with the fact we can **only ** increment numbers, we can keep track of the "next unqiue number"\n3. After sorting, loop through array.\n4. If num[i] is unique (aka not in the set), add number to set and set next_closest_unique_number to nums[i]...
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
valid_stack().py
validate-stack-sequences
0
1
SIMPLE STACK LIST\n# Code\n```\nclass Solution:\n def validateStackSequences(self, p: List[int], o: List[int]) -> bool:\n st=[]\n x=0\n for i in p:\n st.append(i)\n if len(st)>0 and st[len(st)-1]==o[x]:\n while len(st)>0 and st[len(st)-1]==o[x]:\n ...
4
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explana...
null
valid_stack().py
validate-stack-sequences
0
1
SIMPLE STACK LIST\n# Code\n```\nclass Solution:\n def validateStackSequences(self, p: List[int], o: List[int]) -> bool:\n st=[]\n x=0\n for i in p:\n st.append(i)\n if len(st)>0 and st[len(st)-1]==o[x]:\n while len(st)>0 and st[len(st)-1]==o[x]:\n ...
4
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
3 ways to solve in python. Each improving on the other
validate-stack-sequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthree approaches to solve this problem\n1) Use an explicit data structure\n2) Use two while loops\n3) Use a while loop nested in a for each loop\n\n# Approach-1\n<!-- Describe your approach to solving the problem. -->\nuse an explicit sta...
2
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explana...
null
3 ways to solve in python. Each improving on the other
validate-stack-sequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthree approaches to solve this problem\n1) Use an explicit data structure\n2) Use two while loops\n3) Use a while loop nested in a for each loop\n\n# Approach-1\n<!-- Describe your approach to solving the problem. -->\nuse an explicit sta...
2
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
Simple stack solution. Python/C++
validate-stack-sequences
0
1
\nUsing deque in Python\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n a = deque([])\n j = 0\n for i in range(len(pushed)):\n a.appendleft(pushed[i])\n while(a and a[0] == popped[j]):\n a.popl...
2
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explana...
null
Simple stack solution. Python/C++
validate-stack-sequences
0
1
\nUsing deque in Python\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n a = deque([])\n j = 0\n for i in range(len(pushed)):\n a.appendleft(pushed[i])\n while(a and a[0] == popped[j]):\n a.popl...
2
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
🔥🔥BEATS 99.2%🔥🔥||EASY SOLUTION
validate-stack-sequences
0
1
\n\n# Approach\nStack :if top element of stack is equal to popped element index then pop the element\n\n# Complexity\n\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack=[]\n j=0\n for i in pushed...
1
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explana...
null
🔥🔥BEATS 99.2%🔥🔥||EASY SOLUTION
validate-stack-sequences
0
1
\n\n# Approach\nStack :if top element of stack is equal to popped element index then pop the element\n\n# Complexity\n\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack=[]\n j=0\n for i in pushed...
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
easy stack python solution
validate-stack-sequences
0
1
```\nclass Solution:\n \n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack = []\n j = 0\n for i in range(len(pushed)):\n stack.append(pushed[i])\n # moving on the popped list with another pointer and updating the stack\n ...
1
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explana...
null
easy stack python solution
validate-stack-sequences
0
1
```\nclass Solution:\n \n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack = []\n j = 0\n for i in range(len(pushed)):\n stack.append(pushed[i])\n # moving on the popped list with another pointer and updating the stack\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
PYTHON || STACK || beats(70%)
validate-stack-sequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nstack problem \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n- iterate through pushed array using stack with it \n- use pointer (idx) with popped array\n- use while loop with condition that (last element in stack...
1
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explana...
null
PYTHON || STACK || beats(70%)
validate-stack-sequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nstack problem \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n- iterate through pushed array using stack with it \n- use pointer (idx) with popped array\n- use while loop with condition that (last element in stack...
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
most-stones-removed-with-same-row-or-column
1
1
```C++ []\nclass Solution {\n static constexpr int K = 10001;\n int* ranks;\n int* repr;\n\n inline int dsuFind(int x) {\n if (x != repr[x]) {\n repr[x] = dsuFind(repr[x]);\n }\n return repr[x];\n }\n inline int dsuUnion(int x, int y) {\n x = dsuFind(x);\n ...
1
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represen...
null
Solution
most-stones-removed-with-same-row-or-column
1
1
```C++ []\nclass Solution {\n static constexpr int K = 10001;\n int* ranks;\n int* repr;\n\n inline int dsuFind(int x) {\n if (x != repr[x]) {\n repr[x] = dsuFind(repr[x]);\n }\n return repr[x];\n }\n inline int dsuUnion(int x, int y) {\n x = dsuFind(x);\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
Python || Easy || Union Find || Explained
most-stones-removed-with-same-row-or-column
0
1
**We can say that if a stone is in the same row or in same column then it is a part of one component and no. of stones that can be removed from one component is n1(no. of stones in component 1)-1. So, total no. of stones that can be removed is n(given no. of stones) - c(no. of components)**\n\n```\nclass Solution:\n ...
2
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represen...
null
Python || Easy || Union Find || Explained
most-stones-removed-with-same-row-or-column
0
1
**We can say that if a stone is in the same row or in same column then it is a part of one component and no. of stones that can be removed from one component is n1(no. of stones in component 1)-1. So, total no. of stones that can be removed is n(given no. of stones) - c(no. of components)**\n\n```\nclass Solution:\n ...
2
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
📌📌 For Beginners || Count Number of Connected Graphs O(N) || 94% Faster 🐍
most-stones-removed-with-same-row-or-column
0
1
## IDEA :\n\n*If you see the whole description with focus you will find that we have to find total number of distinguish connected points. So, We move this problem to a graph domain. When two stones row or column is same, we can say the they are connected.*\n\nAfter construcing the graph, we get a collection of one or ...
29
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represen...
null
📌📌 For Beginners || Count Number of Connected Graphs O(N) || 94% Faster 🐍
most-stones-removed-with-same-row-or-column
0
1
## IDEA :\n\n*If you see the whole description with focus you will find that we have to find total number of distinguish connected points. So, We move this problem to a graph domain. When two stones row or column is same, we can say the they are connected.*\n\nAfter construcing the graph, we get a collection of one or ...
29
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
bag-of-tokens
1
1
```C++ []\nclass Solution {\npublic:\n int bagOfTokensScore(vector<int>& nums, int power) {\n sort(nums.begin(),nums.end());\n int i=0,j=nums.size()-1,score=0,ans=0;\n while(i<=j && i<nums.size()){\n if(score<=0&&power<nums[i])break;\n if(power>=nums[i]){\n ...
2
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may...
null
Solution
bag-of-tokens
1
1
```C++ []\nclass Solution {\npublic:\n int bagOfTokensScore(vector<int>& nums, int power) {\n sort(nums.begin(),nums.end());\n int i=0,j=nums.size()-1,score=0,ans=0;\n while(i<=j && i<nums.size()){\n if(score<=0&&power<nums[i])break;\n if(power>=nums[i]){\n ...
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
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
bag-of-tokens
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...
45
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
bag-of-tokens
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...
45
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 | O(n logn) | Two-Pointer approach | Well-explained
bag-of-tokens
0
1
we need to check for two conditions \n1. `power >= tokens[i]`. Here, we lose power and gain score.\n2. `score >= 1`. Here, we lose score to gain power.\n\nKeeping `ans` variable to keep counter of max score we can achieve.\n\n* Sort the array in increasing order\n* Keep two pointers at extreme ends ```i = 0``` and ``...
4
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may...
null
Python | O(n logn) | Two-Pointer approach | Well-explained
bag-of-tokens
0
1
we need to check for two conditions \n1. `power >= tokens[i]`. Here, we lose power and gain score.\n2. `score >= 1`. Here, we lose score to gain power.\n\nKeeping `ans` variable to keep counter of max score we can achieve.\n\n* Sort the array in increasing order\n* Keep two pointers at extreme ends ```i = 0``` and ``...
4
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. || 12 lines, iterative, deque || T/M: 92%/40%
bag-of-tokens
0
1
It pretty much explains itself.\n```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n \n tokens, ans, score = deque(sorted(tokens)), 0, 0\n \n while tokens:\n if tokens[0] <= power:\n power -= tokens.popleft()\n sc...
3
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may...
null
Python3. || 12 lines, iterative, deque || T/M: 92%/40%
bag-of-tokens
0
1
It pretty much explains itself.\n```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n \n tokens, ans, score = deque(sorted(tokens)), 0, 0\n \n while tokens:\n if tokens[0] <= power:\n power -= tokens.popleft()\n sc...
3
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] Runtime: 55 ms, faster than 98.92% | Memory: 13.9 MB, less than 97.17%
bag-of-tokens
0
1
```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n i,j = 0,len(tokens)-1\n points = maxPoints = 0\n while i<=j:\n if power>=tokens[i]:\n power-=tokens[i]\n points+=1\n maxPoints...
2
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may...
null
[Python3] Runtime: 55 ms, faster than 98.92% | Memory: 13.9 MB, less than 97.17%
bag-of-tokens
0
1
```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n i,j = 0,len(tokens)-1\n points = maxPoints = 0\n while i<=j:\n if power>=tokens[i]:\n power-=tokens[i]\n points+=1\n maxPoints...
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
Easy Python Solution || Two Pointer approach
bag-of-tokens
0
1
```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n l,r = 0, len(tokens)-1\n curr_score = 0\n max_score = 0\n while l <= r:\n if(tokens[l] <= power):\n power -= tokens[l]\n curr_score +=...
2
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may...
null
Easy Python Solution || Two Pointer approach
bag-of-tokens
0
1
```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n l,r = 0, len(tokens)-1\n curr_score = 0\n max_score = 0\n while l <= r:\n if(tokens[l] <= power):\n power -= tokens[l]\n curr_score +=...
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
Greedy || Single Loop solution || Python 3
bag-of-tokens
0
1
# Intuition\nIts a greedy problem where for addition of more score you have to choose min of token or for addition of power max token.\n\n# Approach\nSort your array (as you can choose in any order) and checkfew base cases :-\n`1. Is your token bag empty`\n`2. Is the power given is too less to even perform one head up ...
1
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may...
null
Greedy || Single Loop solution || Python 3
bag-of-tokens
0
1
# Intuition\nIts a greedy problem where for addition of more score you have to choose min of token or for addition of power max token.\n\n# Approach\nSort your array (as you can choose in any order) and checkfew base cases :-\n`1. Is your token bag empty`\n`2. Is the power given is too less to even perform one head up ...
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
Easy | Python Solution | Strings | Permutations
largest-time-for-given-digits
0
1
# Code\n```\nfrom itertools import permutations\n\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n\n x = permutations(arr)\n ans = []\n currTime = ""\n for i in x:\n h, m = "", ""\n for j in i[:2]:\n h += str(j)\n ...
1
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Easy | Python Solution | Strings | Permutations
largest-time-for-given-digits
0
1
# Code\n```\nfrom itertools import permutations\n\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n\n x = permutations(arr)\n ans = []\n currTime = ""\n for i in x:\n h, m = "", ""\n for j in i[:2]:\n h += str(j)\n ...
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
Solution
largest-time-for-given-digits
1
1
```C++ []\nclass Solution {\npublic:\n string largestTimeFromDigits(vector<int>& arr) {\n sort(arr.begin(), arr.end(), greater<int>());\n do{\n int hours = arr[0] * 10 + arr[1];\n int minutes = arr[2] * 10 + arr[3];\n \n if(hours<24 && minutes<60){\n ...
3
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Solution
largest-time-for-given-digits
1
1
```C++ []\nclass Solution {\npublic:\n string largestTimeFromDigits(vector<int>& arr) {\n sort(arr.begin(), arr.end(), greater<int>());\n do{\n int hours = arr[0] * 10 + arr[1];\n int minutes = arr[2] * 10 + arr[3];\n \n if(hours<24 && minutes<60){\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
Python simple Solution Explained (video + code)
largest-time-for-given-digits
0
1
[](https://www.youtube.com/watch?v=QJeI-gBTp1k)\nhttps://www.youtube.com/watch?v=QJeI-gBTp1k\n```\nfrom itertools import permutations\nclass Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n arr = list(permutations(sorted(A, reverse=True)))\n \n for h1, h2, m1, m2 in arr:\n ...
9
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Python simple Solution Explained (video + code)
largest-time-for-given-digits
0
1
[](https://www.youtube.com/watch?v=QJeI-gBTp1k)\nhttps://www.youtube.com/watch?v=QJeI-gBTp1k\n```\nfrom itertools import permutations\nclass Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n arr = list(permutations(sorted(A, reverse=True)))\n \n for h1, h2, m1, m2 in arr:\n ...
9
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 understanding (With explanation)
largest-time-for-given-digits
0
1
```\nclass Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n# From 23:59 to 00:00 go over every minute of 24 hours. If A meets this requirement, then totaly 24 * 60 minutes. Since using sort during the ongoing judegment process, so the time complexity is low.\n A.sort()\n for h in ran...
10
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Python3 - Easy understanding (With explanation)
largest-time-for-given-digits
0
1
```\nclass Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n# From 23:59 to 00:00 go over every minute of 24 hours. If A meets this requirement, then totaly 24 * 60 minutes. Since using sort during the ongoing judegment process, so the time complexity is low.\n A.sort()\n for h in ran...
10
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 Solution using itertools.permutations()
largest-time-for-given-digits
0
1
# Code\n```\nfrom itertools import permutations \nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n time=[]\n for i in permutations(arr):\n if str(i[0])+str(i[1])<"24" and str(i[2])+str(i[3])<"60":\n time.append(str(i[0])+str(i[1])+":"+str(i[2])+str(i...
1
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Python3 Solution using itertools.permutations()
largest-time-for-given-digits
0
1
# Code\n```\nfrom itertools import permutations \nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n time=[]\n for i in permutations(arr):\n if str(i[0])+str(i[1])<"24" and str(i[2])+str(i[3])<"60":\n time.append(str(i[0])+str(i[1])+":"+str(i[2])+str(i...
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
Simple solution in Python
largest-time-for-given-digits
0
1
\n\n# Approach 1\nBy using simple iteration through loop and by using pointers.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: 41 ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.2 MB\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->...
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Simple solution in Python
largest-time-for-given-digits
0
1
\n\n# Approach 1\nBy using simple iteration through loop and by using pointers.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: 41 ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.2 MB\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->...
0
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
O(1) Brute force approach using itertools.permutations()
largest-time-for-given-digits
0
1
\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n max_time = -1\n\n for h1, h2, m1, m2 in permutations(arr):\n hours = h1 * 10 + h2\n minutes = m1 * 10 + m2\n\n curr_time = hours * 100 + minutes\n\n if 0 <= hours <= ...
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
O(1) Brute force approach using itertools.permutations()
largest-time-for-given-digits
0
1
\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n max_time = -1\n\n for h1, h2, m1, m2 in permutations(arr):\n hours = h1 * 10 + h2\n minutes = m1 * 10 + m2\n\n curr_time = hours * 100 + minutes\n\n if 0 <= hours <= ...
0
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 with itertools.permutations method
largest-time-for-given-digits
0
1
# Complexity\n- Time complexity: `O(1)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSee coments for explanation ^\n\n# Code\n```\n# Clarification:\n\n# Test cases:\n\n# Notes:\n# earliest 00:00 and latest 23:59\n# hh < 24 ...
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Solution with itertools.permutations method
largest-time-for-given-digits
0
1
# Complexity\n- Time complexity: `O(1)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSee coments for explanation ^\n\n# Code\n```\n# Clarification:\n\n# Test cases:\n\n# Notes:\n# earliest 00:00 and latest 23:59\n# hh < 24 ...
0
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
Simple verbose python solution
largest-time-for-given-digits
0
1
\n# Complexity\n- Time complexity: since len(arr) is a constant the time compexity of this slution is O(1)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n \n \n hours = []\n # find all posible valid hour permutations ...
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Simple verbose python solution
largest-time-for-given-digits
0
1
\n# Complexity\n- Time complexity: since len(arr) is a constant the time compexity of this slution is O(1)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n \n \n hours = []\n # find all posible valid hour permutations ...
0
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
Most Intuitive Approach
largest-time-for-given-digits
0
1
# Complexity\n- Time complexity: $$O(1)$$.\n\n- Space complexity: $$O(1)$$.\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n time = []\n\n for dig in (2, 1, 0) if sum(1 for dig in arr if dig > 5) < 2 else (1, 0):\n if dig in arr:\n ti...
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-h...
null
Most Intuitive Approach
largest-time-for-given-digits
0
1
# Complexity\n- Time complexity: $$O(1)$$.\n\n- Space complexity: $$O(1)$$.\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n time = []\n\n for dig in (2, 1, 0) if sum(1 for dig in arr if dig > 5) < 2 else (1, 0):\n if dig in arr:\n ti...
0
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
Simple Approach
reveal-cards-in-increasing-order
0
1
# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n def reveal(n):\n lst = list(range(n))\n ans = []\n i = 0\n while lst:\n if not i&1: ans.append(lst.pop(0))\n else: lst.append(lst.pop(0))\n...
1
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards...
null
Simple Approach
reveal-cards-in-increasing-order
0
1
# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n def reveal(n):\n lst = list(range(n))\n ans = []\n i = 0\n while lst:\n if not i&1: ans.append(lst.pop(0))\n else: lst.append(lst.pop(0))\n...
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
reveal-cards-in-increasing-order
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int>q;\n int n=deck.size();\n sort(deck.begin(),deck.end());;\n for(int i=0;i<n;i++)\n q.push(i);\n vector<int>res(n,0);\n int i=0;\n while(!q.empty() && i<n)...
3
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards...
null
Solution
reveal-cards-in-increasing-order
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int>q;\n int n=deck.size();\n sort(deck.begin(),deck.end());;\n for(int i=0;i<n;i++)\n q.push(i);\n vector<int>res(n,0);\n int i=0;\n while(!q.empty() && i<n)...
3
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, Using Deque, O(n) time complexity
reveal-cards-in-increasing-order
0
1
```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n d=deque(sorted(deck))\n res = deque()\n l = len(d)\n while l != len(res):\n t = d.pop()\n if len(res)>0:\n r = res.pop()\n res.appendleft(r)\n ...
2
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards...
null
Python, Using Deque, O(n) time complexity
reveal-cards-in-increasing-order
0
1
```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n d=deque(sorted(deck))\n res = deque()\n l = len(d)\n while l != len(res):\n t = d.pop()\n if len(res)>0:\n r = res.pop()\n res.appendleft(r)\n ...
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
Solution
flip-equivalent-binary-trees
1
1
```C++ []\nclass Solution {\npublic:\n bool flipEquiv(TreeNode* root1, TreeNode* root2) {\n if(!root1&&!root2){\n return 1;\n }\n if(!root1||!root2)\n {\n return 0;\n }\n return root1->val==root2->val&&(flipEquiv(root1->right,root2->right)&&flipEquiv(ro...
3
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees...
null
Solution
flip-equivalent-binary-trees
1
1
```C++ []\nclass Solution {\npublic:\n bool flipEquiv(TreeNode* root1, TreeNode* root2) {\n if(!root1&&!root2){\n return 1;\n }\n if(!root1||!root2)\n {\n return 0;\n }\n return root1->val==root2->val&&(flipEquiv(root1->right,root2->right)&&flipEquiv(ro...
3
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
Easy approach to solve this problem :)
flip-equivalent-binary-trees
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
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees...
null
Easy approach to solve this problem :)
flip-equivalent-binary-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given 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
98% Tc and 80% Sc easy python solution
flip-equivalent-binary-trees
0
1
```\ndef flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n\tlru_cache(None)\n\tdef dfs(n1, n2):\n\t\tif not(n1 or n2):\n\t\t\treturn True\n\t\tif not(n1 and n2) or n1.val != n2.val:\n\t\t\treturn False\n\t\tif((n1.left and n2.left) or (n1.right and n2.right)):\n\t\t\treturn (dfs(n1.left, ...
1
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees...
null
98% Tc and 80% Sc easy python solution
flip-equivalent-binary-trees
0
1
```\ndef flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n\tlru_cache(None)\n\tdef dfs(n1, n2):\n\t\tif not(n1 or n2):\n\t\t\treturn True\n\t\tif not(n1 and n2) or n1.val != n2.val:\n\t\t\treturn False\n\t\tif((n1.left and n2.left) or (n1.right and n2.right)):\n\t\t\treturn (dfs(n1.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
Python || 4-line 93%
flip-equivalent-binary-trees
0
1
```\nclass Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n if not root1 or not root2:\n return not root1 and not root2\n if root1.val != root2.val: return False\n return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.r...
3
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees...
null
Python || 4-line 93%
flip-equivalent-binary-trees
0
1
```\nclass Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n if not root1 or not root2:\n return not root1 and not root2\n if root1.val != root2.val: return False\n return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.r...
3
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 recursive DFS solution with comments
flip-equivalent-binary-trees
0
1
```\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 flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:\n \n \'\'\'\n ...
7
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees...
null
Python recursive DFS solution with comments
flip-equivalent-binary-trees
0
1
```\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 flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:\n \n \'\'\'\n ...
7
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
simple approach + python
flip-equivalent-binary-trees
0
1
## Intuition\nThe intuition behind your solution is to compare the nodes of two binary trees recursively. Two trees are flip equivalent if the roots are the same and the left and right children of one tree are the flip equivalent of the right and left children of the other tree, respectively.\n\n## Approach\nrecursive ...
0
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees...
null
simple approach + python
flip-equivalent-binary-trees
0
1
## Intuition\nThe intuition behind your solution is to compare the nodes of two binary trees recursively. Two trees are flip equivalent if the roots are the same and the left and right children of one tree are the flip equivalent of the right and left children of the other tree, respectively.\n\n## Approach\nrecursive ...
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
Solution
largest-component-size-by-common-factor
1
1
```C++ []\nclass Solution {\npublic:\n int arr[(int)(1e5+5)];\n int visit[(int)(1e5+5)]={0};\n int member[(int)(1e5+5)];\n constexpr void build(vector<int>& primes, pair<int,int>* sp, int N){\n if(primes.empty()){\n visit[0] = visit[1] = 1;\n sp[1].first = sp[1].second = 1;\n ...
2
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _t...
null
Solution
largest-component-size-by-common-factor
1
1
```C++ []\nclass Solution {\npublic:\n int arr[(int)(1e5+5)];\n int visit[(int)(1e5+5)]={0};\n int member[(int)(1e5+5)];\n constexpr void build(vector<int>& primes, pair<int,int>* sp, int N){\n if(primes.empty()){\n visit[0] = visit[1] = 1;\n sp[1].first = sp[1].second = 1;\n ...
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
[Python3] union-find
largest-component-size-by-common-factor
0
1
\n`O(MlogM)` using sieve\n```\nclass UnionFind: \n \n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [1]*n\n \n def find(self, p): \n if p != self.parent[p]: \n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n \n def u...
4
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _t...
null