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 3 | Clean, Simple Stack | Explanation
exclusive-time-of-functions
0
1
### Explanation\n- Split a function call to 2 different type of states\n\t- Before nested call was made\n\t- After nested call was made\n- Record time spent on these 2 types of states\n- e.g. for `n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]`\n\t- Initially stack is empty, then it will record `[[0, 0]]` ...
18
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
very very simple solution | stacks
exclusive-time-of-functions
0
1
```\nclass Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n\n result = [0]*n\n stack = []\n \n for i, log in enumerate(logs):\n curr_fid, curr_event, curr_time = log.split(":")\n if curr_event == "start":\n stack.append(log)...
4
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
Python, simple solution with stack using defaultdict
exclusive-time-of-functions
0
1
Please upvote!!!\n\nTime: O(n), since you need to travel the entire list of logs\nSpace: O(n/2) so O(n), if you have n/2 start processes, then you would have n/2 end processes too. So at most you have n/2 processes in stack. \n\n```\nclass Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n ...
2
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
Python stack easy to understand
exclusive-time-of-functions
0
1
\n```\ndef exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n \n stack = []\n prev_time = 0\n ans = [0 for i in range(n)]\n \n for i in range(0,len(logs)):\n fid, state, time = logs[i].split(\':\')\n fid, time = int(fid), int(time)\n \...
8
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
Solution
exclusive-time-of-functions
1
1
```C++ []\nclass Solution {\n enum Event {kStart, kEnd};\n vector<int> ans;\n tuple<int, enum Event, int> parseLog(const string &log)\n {\n tuple<int, enum Event, int> ret;\n int pos = log.find(\':\');\n get<0>(ret) = stoi(log.substr(0, pos));\n int prev = pos; pos = log.find(\':...
1
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
python | stack | easy | O(n)
exclusive-time-of-functions
0
1
```\nclass Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n \n \n f = [0]*(n)\n \n \n stack=[]\n \n \n for i in logs:\n \n ID,pos,time = i.split(\':\')\n \n ID= int(ID)\n ...
5
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
O(n) Python, Faster than 99.39%, easy to understand
exclusive-time-of-functions
0
1
The easy is easy to build if we understand the boundry conditions. \n1. The function that starts or ends claims the time stamp\n2. if a new method is starting we claim the duration of previous method as it has run till that time\n\nwe can build a simple timeline as \n0,0,1,1,1,...\nwhere 0, 1 represent the function id ...
2
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
[Python] Simple solution with comments
exclusive-time-of-functions
0
1
```\nclass Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n ## RC ##\n\t\t## APPROACH : STACK ##\n stack, res = [], [0] * n\n for log in logs:\n id, func, curr_time = log.split(":")\n id, curr_time = int(id), int(curr_time)\n if func =...
11
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
Python intuitive approach with comments
exclusive-time-of-functions
0
1
```\nclass Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n \n result = [0] * n\n p_num, _, p_timestamp = logs[0].split(\':\')\n stack = [[int(p_num), int(p_timestamp)]]\n \n i = 1\n while i < len(logs):\n # c_ variables are current ...
2
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its I...
null
Store node's level, bfs through and track sums
average-of-levels-in-binary-tree
0
1
\nIf you know what a BFS is, and that a queue stores a tree\'s nodes level by level, the only thing to think about in this problem is the edge cases and making sure we\'re updating our array in the right places.\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, lef...
0
Given the `root` of a binary tree, return _the average value of the nodes on each level in the form of an array_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[3.00000,14.50000,11.00000\] Explanation: The average value of nodes on...
null
15 lines of code very easy approach
average-of-levels-in-binary-tree
0
1
# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:\n if not root...
1
Given the `root` of a binary tree, return _the average value of the nodes on each level in the form of an array_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[3.00000,14.50000,11.00000\] Explanation: The average value of nodes on...
null
Solution
shopping-offers
1
1
```C++ []\nbool operator >= (const vector<int>& a, const vector<int>& b)\n{\n for (int i = 0; i < a.size(); ++i)\n {\n if (a[i] < b[i]) return false;\n }\n return true;\n}\nint operator* (const vector<int>& a, const vector<int>& b)\n{\n int res = 0;\n for (int i = 0; i < a.size(); ++i)\n {\n...
1
In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array `price` where `price[i]` is the price of the `ith` item, and an integer array `needs` whe...
null
Easy Solution|| Beats 98%|| Easy to Understand💯🔥
shopping-offers
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
In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array `price` where `price[i]` is the price of the `ith` item, and an integer array `needs` whe...
null
Cleanest, easiest, fastest [Memoization]
shopping-offers
0
1
# Intuition\nTry all ways.\n\n# Approach\n1. There are 2 ways of purchasing.\n - special offers: we need to check if we can purchase an offer by checking do we need the number of items the offer is offering.\n - just buy at direct price\n2. **(Base case)** Once the needs becomes 0, we stop.\n3. We also memoize th...
1
In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array `price` where `price[i]` is the price of the `ith` item, and an integer array `needs` whe...
null
✅✔️Easy implementation using dfs with memorziable dictionary || Python Fast Solution✈️✈️✈️✈️✈️
shopping-offers
0
1
## 638. Shopping Offers\n\nIn LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.\n\nYou are given an integer array price where price[i] is the price of the ith item, and an inte...
1
In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array `price` where `price[i]` is the price of the `ith` item, and an integer array `needs` whe...
null
Python 3 || 10 lines, dfs, w/ comments || T/M: 75% / 34%
shopping-offers
0
1
```\nclass Solution:\n def shoppingOffers(self, price: List[int], specials: List[List[int]], needs: List[int]) -> int:\n\n @lru_cache(None)\n def dfs(needs):\n\n cost = sum(map(mul, needs, price)) # cost with no specials applied\n\n for special in specials:\n ...
3
In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array `price` where `price[i]` is the price of the `ith` item, and an integer array `needs` whe...
null
python3 dfs
shopping-offers
0
1
\n# Code\n```\nclass Solution:\n def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:\n freq = {}\n for offer in special:\n a = tuple(offer[:-1])\n if a not in freq:\n freq[a] = float(\'inf\')\n freq[a] = min(freq...
0
In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price. You are given an integer array `price` where `price[i]` is the price of the `ith` item, and an integer array `needs` whe...
null
Simple and precise Top-down DP approach (Memoization)
decode-ways-ii
0
1
# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def numDecodings(self, s: str) -> int:\n M = 10**9 + 7\n \n def dp(s, i, memo):\n if i == len(s):\n return 1\n\n if memo[i] is not None:\n ret...
2
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For examp...
null
Solution
decode-ways-ii
1
1
```C++ []\nclass Solution {\npublic:\n int numDecodings(string s) {\n long long MOD = 1e9+7;\n int n=s.length();\n long long dp[n+1];\n if(s[0]==\'0\')\n return 0;\n dp[0]=1;\n dp[1]=s[0]==\'*\'?9:1;\n for(int i=2;i<=n;i++){\n dp[i]=0;\n if(s[i-1]==\'*\...
1
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For examp...
null
Python 3 || 11 lines, dp, defaultdict || T/M: 97% / 31%
decode-ways-ii
0
1
```\nclass Solution:\n def numDecodings(self, s: str) -> int:\n \n d = defaultdict(int)\n for i in range(1,27): d[str(i)] = 1\n for i in range(10): d["*"+str(i)] = 1 + (i< 7)\n d[\'*\'], d[\'**\'], d[\'1*\'], d[\'2*\'] = 9,15,9,6\n\n n, M = len(s)-1, 10**9+7\n dp = [d[s[...
3
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For examp...
null
Solution to 639. Decode Ways II
decode-ways-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves decoding a string that contains digits and `*` characters. We aim to count the possible ways to interpret the string. `*` can represent any digit from `1` to `9`, and the task is to determine the total number of valid...
0
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For examp...
null
Solution to 639. Decode Ways II
decode-ways-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves counting the number of ways to decode a given string. We need to handle the presence of `*` as a wildcard character, which can represent any digit from `1` to `9`. The goal is to return the count of possible decodings...
0
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For examp...
null
Soln
decode-ways-ii
0
1
# Intuition/Approach\n<!-- Describe your approach to solving the problem. -->\n$ Let ,\n\\newline\\quad \n\\left. \n \\begin{matrix*}[l]\n ways(pattern) & {\n size( \n \\underbrace{n}_{\n\n \\left\\{\n \\begin{matrix*}[l]\n\n ...
0
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For examp...
null
Solution
solve-the-equation
1
1
```C++ []\nclass Solution {\n public:\n string solveEquation(string equation) {\n const string lhsEquation = equation.substr(0, equation.find(\'=\'));\n const string rhsEquation = equation.substr(equation.find(\'=\') + 1);\n const auto& [lhsCoefficient, lhsConstant] = calculate(lhsEquation);\n const auto& ...
2
Solve a given equation and return the value of `'x'` in the form of a string `"x=#value "`. The equation contains only `'+'`, `'-'` operation, the variable `'x'` and its coefficient. You should return `"No solution "` if there is no solution for the equation, or `"Infinite solutions "` if there are infinite solutions f...
null
Basic simulation (R-95%+, M-70%+)
solve-the-equation
0
1
# Complexity\n- Time complexity: **O(n)**\nn - length of input string `equation`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def solveEquation(self, equation: str) -> str:\n lef...
0
Solve a given equation and return the value of `'x'` in the form of a string `"x=#value "`. The equation contains only `'+'`, `'-'` operation, the variable `'x'` and its coefficient. You should return `"No solution "` if there is no solution for the equation, or `"Infinite solutions "` if there are infinite solutions f...
null
python3 , tokenize expression and pass over tokens.
solve-the-equation
0
1
# Intuition\nparse input into tokens, and one pass over tokens. Gather the sum of the factors of X and the sum of the constants, solve it.\n\n\n# Complexity\n- Time complexity:\nO(n) - pass once over the input to parse the tokens, second pass over the tokens (number of tokens is usually smaller than n, but close to n)\...
0
Solve a given equation and return the value of `'x'` in the form of a string `"x=#value "`. The equation contains only `'+'`, `'-'` operation, the variable `'x'` and its coefficient. You should return `"No solution "` if there is no solution for the equation, or `"Infinite solutions "` if there are infinite solutions f...
null
Python Solution || Easy to Understand
solve-the-equation
0
1
* **Time Complexity: *O(n)***\n# Methodology:\nI have framed different equations for x-coefficients and constants on both sides\nSay equation: *3x-2-2x=5x+3*,\nthen x1 = 3-2 (**3x**-2 **-2x**)\n\t\tx2 = 5 ( **5x**+3x)\n\t\tn1 = -2 ( 3x **-2**-2x)\n\t\tn2 = 3 (5x **+3x**)\n\ttotal (x) = (3-2)-(5) => -4 (coefficient of ...
0
Solve a given equation and return the value of `'x'` in the form of a string `"x=#value "`. The equation contains only `'+'`, `'-'` operation, the variable `'x'` and its coefficient. You should return `"No solution "` if there is no solution for the equation, or `"Infinite solutions "` if there are infinite solutions f...
null
Simple python3 solution
solve-the-equation
0
1
```\nclass Solution:\n def solveEquation(self, equation: str) -> str:\n def parse(expr):\n zero = False\n sign, curr = 1, 0\n coeff, val = 0, 0\n \n for i in range(len(expr)):\n if expr[i] == \'+\' or expr[i] == \'-\':\n ...
0
Solve a given equation and return the value of `'x'` in the form of a string `"x=#value "`. The equation contains only `'+'`, `'-'` operation, the variable `'x'` and its coefficient. You should return `"No solution "` if there is no solution for the equation, or `"Infinite solutions "` if there are infinite solutions f...
null
Python Solution Using RE
solve-the-equation
0
1
\n# Code\n```\nclass Solution:\n def solveEquation(self, equation: str) -> str:\n coef = [0, 0] # coefficient of x and constant\n left = 1\n for item in re.findall("=|[\\+-]?[0-9x]+", equation):\n if item == "=":\n left = -1\n elif "x" in item:\n ...
0
Solve a given equation and return the value of `'x'` in the form of a string `"x=#value "`. The equation contains only `'+'`, `'-'` operation, the variable `'x'` and its coefficient. You should return `"No solution "` if there is no solution for the equation, or `"Infinite solutions "` if there are infinite solutions f...
null
Simple regexp solution
solve-the-equation
0
1
# Intuition\n\nUsing the regexp `(^|[+-=])([0-9]*)(x|)` one can split the string into token triples. Each consists of an `op` a coefficient and optionally `x`. Then we can compute the total constant on both side and the coefficient of `x`. \n \n\n# Code\n```\nimport re\nclass Solution:\n def solveEquation(self, equa...
0
Solve a given equation and return the value of `'x'` in the form of a string `"x=#value "`. The equation contains only `'+'`, `'-'` operation, the variable `'x'` and its coefficient. You should return `"No solution "` if there is no solution for the equation, or `"Infinite solutions "` if there are infinite solutions f...
null
✔Beats 97.6% TC || Python Solution
design-circular-deque
0
1
# Complexity\n- Time complexity:\n97.6%\n- Space complexity:\n88.24%\n# Code\n```\nclass MyCircularDeque:\n\n def __init__(self, k: int):\n self.deque = []\n self.k = k\n\n def insertFront(self, value: int) -> bool:\n if len(self.deque) < self.k:\n self.deque = [value] + self.deque...
1
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwi...
null
✔Beats 97.6% TC || Python Solution
design-circular-deque
0
1
# Complexity\n- Time complexity:\n97.6%\n- Space complexity:\n88.24%\n# Code\n```\nclass MyCircularDeque:\n\n def __init__(self, k: int):\n self.deque = []\n self.k = k\n\n def insertFront(self, value: int) -> bool:\n if len(self.deque) < self.k:\n self.deque = [value] + self.deque...
1
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
Python || 92.92% Faster || Explained with comments
design-circular-deque
0
1
```\nclass MyCircularDeque:\n\n def __init__(self, k: int):\n self.size=k\n self.q=[0]*self.size\n self.front=-1\n self.rear=-1\n\n def insertFront(self, value: int) -> bool:\n if self.isFull():\n return False\n if self.isEmpty():\n self.front=self.r...
1
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwi...
null
Python || 92.92% Faster || Explained with comments
design-circular-deque
0
1
```\nclass MyCircularDeque:\n\n def __init__(self, k: int):\n self.size=k\n self.q=[0]*self.size\n self.front=-1\n self.rear=-1\n\n def insertFront(self, value: int) -> bool:\n if self.isFull():\n return False\n if self.isEmpty():\n self.front=self.r...
1
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
Using List Simple || Python3
design-circular-deque
0
1
# Intuition\nYou can perform all operations as same as using a normal deque just for pushing an element from front\ndeque uses -> appendleft\nfor list -> [value] + arr\n\n# Code\n```\nclass MyCircularDeque:\n\n def __init__(self, k: int):\n self.q = []\n self.k = k\n \n def insertFront(self, ...
1
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwi...
null
Using List Simple || Python3
design-circular-deque
0
1
# Intuition\nYou can perform all operations as same as using a normal deque just for pushing an element from front\ndeque uses -> appendleft\nfor list -> [value] + arr\n\n# Code\n```\nclass MyCircularDeque:\n\n def __init__(self, k: int):\n self.q = []\n self.k = k\n \n def insertFront(self, ...
1
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
python3-solution using list
design-circular-deque
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
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwi...
null
python3-solution using list
design-circular-deque
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 two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
Solution
design-circular-deque
1
1
```C++ []\nclass MyCircularDeque {\n public:\n MyCircularDeque(int k) : k(k), q(k), rear(k - 1) {}\n bool insertFront(int value) {\n if (isFull())\n return false;\n\n front = (--front + k) % k;\n q[front] = value;\n ++size;\n return true;\n }\n bool insertLast(int value) {\n if (isFull())\n ...
2
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwi...
null
Solution
design-circular-deque
1
1
```C++ []\nclass MyCircularDeque {\n public:\n MyCircularDeque(int k) : k(k), q(k), rear(k - 1) {}\n bool insertFront(int value) {\n if (isFull())\n return false;\n\n front = (--front + k) % k;\n q[front] = value;\n ++size;\n return true;\n }\n bool insertLast(int value) {\n if (isFull())\n ...
2
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
641: Solution with step by step explanation
design-circular-deque
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize an array with size k, set the head and tail pointers to 0, and set the size to 0.\n2. Implement insertFront by checking if the deque is full, if not, decrement the head pointer (using modular arithmetic to wrap...
4
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwi...
null
641: Solution with step by step explanation
design-circular-deque
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize an array with size k, set the head and tail pointers to 0, and set the size to 0.\n2. Implement insertFront by checking if the deque is full, if not, decrement the head pointer (using modular arithmetic to wrap...
4
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
89% TC easy python solution
design-circular-deque
0
1
```\nclass Node:\n def __init__(self, val, p=None, n=None):\n self.val = val\n self.prev = p\n self.next = n\nclass MyCircularDeque:\n def __init__(self, k: int):\n self.k = k\n self.l = 0\n self.head = self.tail = None\n\n def insertFront(self, value: int) -> bool:\n ...
3
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwi...
null
89% TC easy python solution
design-circular-deque
0
1
```\nclass Node:\n def __init__(self, val, p=None, n=None):\n self.val = val\n self.prev = p\n self.next = n\nclass MyCircularDeque:\n def __init__(self, k: int):\n self.k = k\n self.l = 0\n self.head = self.tail = None\n\n def insertFront(self, value: int) -> bool:\n ...
3
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
Ring Buffer - ArrayLen + 1 - O(1)
design-circular-deque
0
1
## Approach\n```haskell\n f\nempty: [#,#,#,#,#], when f == b\n b\n```\n```haskell\n f\nfull: [#,#,#,#,#], when f == b + 1\n b\n```\n\n## Complexity\n```haskell\nTime complexity (all ops): O(1)\nSpace complexity: O(n)\n```\n\n# Code\n```\nclass MyCircularDeque:\n\n def __init__(s...
0
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwi...
null
Ring Buffer - ArrayLen + 1 - O(1)
design-circular-deque
0
1
## Approach\n```haskell\n f\nempty: [#,#,#,#,#], when f == b\n b\n```\n```haskell\n f\nfull: [#,#,#,#,#], when f == b + 1\n b\n```\n\n## Complexity\n```haskell\nTime complexity (all ops): O(1)\nSpace complexity: O(n)\n```\n\n# Code\n```\nclass MyCircularDeque:\n\n def __init__(s...
0
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
Py3 | Beginner friendly with details and explanation
maximum-average-subarray-i
0
1
# Approach\n\nThis problem uses sliding window concept.\nYou can solve this problem using two loops in $O(n^2)$ time complexity. However, with sliding window approach, you can easily resolve this in O(n) time.\n\n\nFollow the images below to look at how this works:\n1. Our given input\n![Given input nums and k value](h...
55
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,...
null
The solution is easy to understand complexity O(n)
maximum-average-subarray-i
0
1
# Approach\nThe simplest idea is to slightly optimize the most obvious approach with iterating under an array and just move forward element by element. \n\n# Complexity\n- Time complexity:\nComplexity of the algorithm O(n)\n\n\n# Code\n```\nclass Solution:\n def findMaxAverage(self, nums: List[int], k: int) -> float...
4
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,...
null
Python|| Easiest Solution || Leetcode 75
maximum-average-subarray-i
0
1
\n# Approach\nWe calculate the sum of first k elements and for with k+1 th element we keep on adding elements and subtracting i-kth elements ( basically keeping the window between i+1 to k+1)\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def findMaxAverage(...
2
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,...
null
✅Python | Sliding Window : Explained | Easy & Fast 🔥🔥
maximum-average-subarray-i
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs we are given we need to find k elements average which is contigious i thought we make a window and move it till end.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- first we find sum of first k elements and make...
15
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,...
null
Python O(n) solution | beats 99%
maximum-average-subarray-i
0
1
# Approach\nSliding sum of k elements.\n\n# Code\n```\nclass Solution:\n def findMaxAverage(self, nums: List[int], k: int) -> float:\n n = len(nums)\n s = sum(nums[:k])\n answer = s\n for i in range(k, n):\n s += nums[i]\n s -= nums[i-k]\n answer = max(ans...
7
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,...
null
Sliding Window
maximum-average-subarray-i
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)$$ --...
3
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,...
null
Both Brute force and Sliding Window Approaches
maximum-average-subarray-i
0
1
# Approach\n###### Sliding Window Approach\n\n# Complexity\n\n##### Brute force Approach\n\n- Time complexity: O((n-k+1) * k)\n\n- Space complexity: O(1)\n\n\n##### Sliding Window Approach\n\n- Time complexity: O(n-k+1)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def findMaxAverage(self, nums: List...
2
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,...
null
Simple Sliding Window Approach, O(n)
maximum-average-subarray-i
0
1
# Approach\nHere\'s a breakdown of how the function works:\n\n1. Calculate the sum of the first `k` elements in the `nums` list and assign it to the variable `windowSum`. This represents the sum of the elements in the initial window of size `k`.\n\n2. Calculate the initial maximum average by dividing `windowSum` by `k`...
4
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,...
null
Easy Python Solution
set-mismatch
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDeclare a Counter before the for loop, so that you don\'t need to use the count() function inside of the for loop, that would have the raised the complexity of the function form $$O(n)$$ to $$O(n^2)$$. Now initilaize an arra...
20
You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number. You are given an integer array `nums` represe...
null
Python 3 || 7 lines, w/ explanation || T/M: 100% / 90%
maximum-length-of-pair-chain
0
1
Here\'s the plan:\n\n- We initialize two variables: `ans` to store the length of the longest chain; and `chainEnd` to keep track of the ending value of the current chain.\n\n- We sort `pairs` based on the second element of each pair and then iterate through the sorted pairs using a loop.\n\n- If `l` is greater than `ch...
5
You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`. A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion. Return _the length longest chain which can be formed_. You do not need to use up all the given int...
null
Python || Greedy || Easy || key || 99%
maximum-length-of-pair-chain
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key observation here is that for a chain of pairs to be formed, the second element of each pair should be strictly smaller than the first element of the next pair. This way, you can keep selecting pairs in such a way that they form a ...
2
You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`. A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion. Return _the length longest chain which can be formed_. You do not need to use up all the given int...
null
SELF SOLVED 95%🤩. Therefore The simplest explanation with THOUGHT PROCESS .
maximum-length-of-pair-chain
0
1
# Intuition\nI swear\uD83E\uDD1E I didnt look the solution.The only intution that came to my mind was I might have to sort the elements . So I sorted them by their x values . Each pair is represented by (x,y) or (X,Y)\n\n\nAnd I started dry running them on the first testcase,\nand then some more and then some more . Th...
2
You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`. A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion. Return _the length longest chain which can be formed_. You do not need to use up all the given int...
null
🌟 Python Simple Solution | Greedy Approach ⚡
maximum-length-of-pair-chain
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nclass Solution:\n def findLongestChain(self, pairs: List[List[int]]) -> int:\n pairs.sort(key = lambda x: x[1])\n res = 1\n end = pairs[0][1]\n \n for i in range(1, len(pairs)):\n \n ...
2
You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`. A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion. Return _the length longest chain which can be formed_. You do not need to use up all the given int...
null
【Video】Ex-Amazon explains a solution with Python, JavaScript, Java and C++
maximum-length-of-pair-chain
1
1
# Intuition\nSorting pairs with the seocond element.\n\n# Solution Video\n\n### Please subscribe to my channel from here. I have 248 videos as of August 26th.\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nhttps://youtu.be/agYDE4CcKNc\n\n## In the video, the s...
20
You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`. A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion. Return _the length longest chain which can be formed_. You do not need to use up all the given int...
null
Greedy approach using "championship interval"
maximum-length-of-pair-chain
0
1
# Intuition\nThe first thought: can we find a start interval in advance to be sure **THIS can be the first in the chain?**\nThe second thought is: we\'ve found a start interval, assume that we can choose **any interval NEXT** to the starting **if it MEET the conditions**:\n```\nfor [A,B] and [C, D] \n=> B must be less ...
1
You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`. A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion. Return _the length longest chain which can be formed_. You do not need to use up all the given int...
null
Simplest easy to understand Python solution O(n^2) time.
palindromic-substrings
0
1
# Approach\nFirst time I made a solution that was way better than the other answers. I can\'t believe all of the other complicated ones are getting so many views/upvotes. Time complexity is O(n^2) which if I am not mistaken is the best you can do in a timely manner.\n\nTrust me, no explanation for the code needed. The ...
0
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - en...
Simplest easy to understand Python solution O(n^2) time.
palindromic-substrings
0
1
# Approach\nFirst time I made a solution that was way better than the other answers. I can\'t believe all of the other complicated ones are getting so many views/upvotes. Time complexity is O(n^2) which if I am not mistaken is the best you can do in a timely manner.\n\nTrust me, no explanation for the code needed. The ...
0
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end...
Easy Python solution
palindromic-substrings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - en...
Easy Python solution
palindromic-substrings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end...
Python Easy approach Beats ~97%
palindromic-substrings
0
1
#### Expand around Center\n\nThe main idea is **to pick a center and then extend towards the bounds** of the input string. With this approach, we count all valid pallindrome substrings which are based on the specified center. \n\nThere are **two valid cases of centers** for finding pallindrome substrings:\n1. If it\'s ...
39
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - en...
Python Easy approach Beats ~97%
palindromic-substrings
0
1
#### Expand around Center\n\nThe main idea is **to pick a center and then extend towards the bounds** of the input string. With this approach, we count all valid pallindrome substrings which are based on the specified center. \n\nThere are **two valid cases of centers** for finding pallindrome substrings:\n1. If it\'s ...
39
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end...
python simple solution with explanation, 95% fast
palindromic-substrings
0
1
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def countSubstrings(self, s: str) -> int:\n #helper fxn to expand from centre and count palindr...
1
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - en...
python simple solution with explanation, 95% fast
palindromic-substrings
0
1
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def countSubstrings(self, s: str) -> int:\n #helper fxn to expand from centre and count palindr...
1
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end...
Solution in Python 3 (beats ~94%) (six lines) (With Detaiiled Explanation)
palindromic-substrings
0
1
_Explanation:_\n\nThis method uses an expand around center approach. The program iterates through each central point of a potential palindrome. moving left to right in the original input string. It then expands outward (left and right) from the center point and checks if the two characters match. This is done by moving...
76
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - en...
Solution in Python 3 (beats ~94%) (six lines) (With Detaiiled Explanation)
palindromic-substrings
0
1
_Explanation:_\n\nThis method uses an expand around center approach. The program iterates through each central point of a potential palindrome. moving left to right in the original input string. It then expands outward (left and right) from the center point and checks if the two characters match. This is done by moving...
76
Given a string `s`, return _the number of **palindromic substrings** in it_. A string is a **palindrome** when it reads the same backward as forward. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** s = "abc " **Output:** 3 **Explanation:** Three palindromic strin...
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” and palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end...
Python3 brute force solution
replace-words
0
1
\n\n# Code\n```\nclass Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n \n \n words = sentence.split()\n dic_set = set(dictionary)\n ans=[]\n \n for word in words:\n flag=False\n for i in range(len(word)):\n ...
1
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
Easy and Simple Python Solution using Trie
replace-words
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
4
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
Python, easy solution with explanation
replace-words
0
1
\n\n```\n# The TNode class represents node for our Trie \n# We will store all the children for each node and a state\n# All the \'is_complete\' state does is marks it to show where the inserted \'root\' finished\n# E.g if we insert ABC as root we will end up with 3 nodes: \n# A -> B -> C\n# Where B is a child of A and ...
1
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
[Python] - Trie Implementation
replace-words
0
1
```\nclass TrieNode:\n def __init__(self):\n self.children = collections.defaultdict(TrieNode)\n self.isWord = False\n \nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n \n def insert(self, word):\n node = self.root\n for w in word:\n node = n...
11
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
Fast solution beats 97% submissions
replace-words
0
1
```\nclass Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n d = {w:len(w) for w in dictionary}\n mini, maxi = min(d.values()), max(d.values())\n wd = sentence.split()\n rt = []\n for s in wd:\n c = s \n for k in range(mini,min...
4
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
Python 3 | Trie Variation | Explanation
replace-words
0
1
### Explanation\n- Replace `word` with the shortest `root` of it in `dictionary`\n- Add every `root` from `dictionary` to a `trie`\n- Search prefix for each `word` in `sentence` \n\t- If a `root` is found, return `root` (this guarantees the shortest)\n\t- Else, return `word` itself\n### Implementation\n```\nclass TrieN...
4
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
97% speed, Trie Python3
replace-words
0
1
```\nclass Trie:\n def __init__(self):\n self.root = {}\n \n def insert(self, word):\n p = self.root\n for char in word:\n if char not in p:\n p[char] = {}\n p = p[char]\n p[\'#\'] = True\n \n def search(self, word):\n p = self.r...
8
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
Remember its a sentence not an array. Trie solution with python
replace-words
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
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
Python easy solution, clean code
replace-words
0
1
\n\n# Code\n```\nclass Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n dictionary = sorted(dictionary,key = lambda x : len(x))\n words = sentence.split(" ")\n stack = []\n for word in words:\n stack.append(word)\n for keyword in dic...
0
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many...
null
Simple Diagram Explanation
dota2-senate
1
1
# Idea\n- **We will use a two queue approach.**\n- Recall, each senator has a position to exercise their right. \n- The ones to the left have an earlier turn than the ones to the right. \n- `rad` is queue that holds all positions of **active** senators in "Radiant"\n- `dir` is queue that holds all positions of **active...
450
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights:...
null
Python 3 solution with approach and time complexity analysis
dota2-senate
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirstly noticeable thing is that there are only two types of parties in here Radiant and Dire. We can make use of this property and we just need to keep count of who is coming early and who is banned already. \n\n\n# Approach\n<!-- Descri...
2
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights:...
null
Python Without Queues
dota2-senate
0
1
\n```\nclass Solution:\n def predictPartyVictory(self, senate: str) -> str:\n\n # The main observation is that we have to remove the\n # senators of the remaning bans from the begining\n # of the remaning list and so we can also use queue\'s here\n\n n = len(senate)\n bans,arr = [0...
2
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights:...
null
Easy to understand, Simulation with nicely written comments. Step by step method.
dota2-senate
0
1
# Intuition\n- Initially we count the number of Ds and number of Rs\n- Then we loop until we see that all of Ds or all of Rs are banned.\n- If we encounter a D, and we see that there are bans on D, then we enforce that. Similarly with R.\n- Finally, whichever team got banned, we return the other.\n\n# Code\n```\nclass ...
1
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights:...
null
Solutions in C++, Python, and Java
dota2-senate
1
1
# Code\n<iframe src="https://leetcode.com/playground/7gyLhdmK/shared" frameBorder="0" width="700" height="400"></iframe>\n
52
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights:...
null
Top-down Memoization [Python3]
2-keys-keyboard
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI think top down is more intuitive, and easier to understand.\nFor every operation, we either copy all or paste the current result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHowever, we cannot let the user to...
1
There is only one character `'A'` on the screen of a notepad. You can perform one of two operations on this notepad for each step: * Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). * Paste: You can paste the characters which are copied last time. Given an integer `...
How many characters may be there in the clipboard at the last step if n = 3? n = 7? n = 10? n = 24?
[Python] Simple Recursion + Memoization Solution with Explanation
2-keys-keyboard
0
1
* We start with 1 A on screen and with an empty clipboard, \n* In every iteration we have two options either we paste previously copied data or copy the current data and then paste it\n* Now, keep in mind that we can only paste if we have something in clipboard, if clipboard is empty we cannot paste\n* For base case, s...
20
There is only one character `'A'` on the screen of a notepad. You can perform one of two operations on this notepad for each step: * Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). * Paste: You can paste the characters which are copied last time. Given an integer `...
How many characters may be there in the clipboard at the last step if n = 3? n = 7? n = 10? n = 24?
📌📌Python3 || ⚡42 ms, faster than 97.10% of Python3
find-duplicate-subtrees
0
1
![image](https://assets.leetcode.com/users/images/e71a4150-2520-4a25-9696-b9220352f313_1677593807.5801833.png)\n```\nclass Solution:\n def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n map = {}\n res = set()\n def check(node):\n if not node:\n ...
3
Given the `root` of a binary tree, return all **duplicate subtrees**. For each kind of duplicate subtrees, you only need to return the root node of any **one** of them. Two trees are **duplicate** if they have the **same structure** with the **same node values**. **Example 1:** **Input:** root = \[1,2,3,4,null,2,4,...
null
Solution
find-duplicate-subtrees
1
1
```C++ []\nclass Solution {\npublic:\n unordered_map<string,int> m;\n string generate(TreeNode *root,vector<TreeNode*> &res){\n if(!root) return "#";\n string s=generate(root->left,res) +\',\'+generate(root->right,res)+\',\'+to_string(root->val);\n m[s]++;\n if(m[s]==2) res.push_back(r...
1
Given the `root` of a binary tree, return all **duplicate subtrees**. For each kind of duplicate subtrees, you only need to return the root node of any **one** of them. Two trees are **duplicate** if they have the **same structure** with the **same node values**. **Example 1:** **Input:** root = \[1,2,3,4,null,2,4,...
null
Python || Easy Solution
find-duplicate-subtrees
0
1
\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def __init__(self):\n self.hash = defaultdict(bool)\n self.ans = []\n ...
1
Given the `root` of a binary tree, return all **duplicate subtrees**. For each kind of duplicate subtrees, you only need to return the root node of any **one** of them. Two trees are **duplicate** if they have the **same structure** with the **same node values**. **Example 1:** **Input:** root = \[1,2,3,4,null,2,4,...
null
[Python] Hash map with serialization; Explained
find-duplicate-subtrees
0
1
We can recursively traverse the tree. However, in order to find duplicated subtrees, we need to maintain a hash map which can easily help us to compare two subtrees with only 1 traverse.\n\nThe key of the hashmap is the serialization of the visited subtree. Whenever we have a new serialization string, we just add it in...
1
Given the `root` of a binary tree, return all **duplicate subtrees**. For each kind of duplicate subtrees, you only need to return the root node of any **one** of them. Two trees are **duplicate** if they have the **same structure** with the **same node values**. **Example 1:** **Input:** root = \[1,2,3,4,null,2,4,...
null
Clean Codes🔥🔥|| Full Explanation✅|| Depth First Search✅|| C++|| Java|| Python3
find-duplicate-subtrees
1
1
# Intuition :\n- Here we have to find all the subtrees in a binary tree that occur more than once and return their roots.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Detail Explanation to Approach :\n- Here we are using a `depth-first search` approach to traverse the tree and encode each s...
52
Given the `root` of a binary tree, return all **duplicate subtrees**. For each kind of duplicate subtrees, you only need to return the root node of any **one** of them. Two trees are **duplicate** if they have the **same structure** with the **same node values**. **Example 1:** **Input:** root = \[1,2,3,4,null,2,4,...
null
Beginner-friendly || Construct a Tree with Divide-and-conquer algorithm in Python3
maximum-binary-tree
0
1
# Intuition\nThe problem description is the following:\n- given the integer list of `nums`, that represents **node values** of a tree\n- our goal is to **construct a Binary Tree** using this `nums` list\n\nLet\'s have a look a little closer:\n```\n# Example\nnums = [3,2,1,6,0,5]\n\n# The algorithm to build a tree is:\n...
2
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: 1. Create a root node whose value is the maximum value in `nums`. 2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum val...
null
654: Solution with step by step explanation
maximum-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a stack to store nodes.\n2. Loop through each number in the input array.\n3. Create a new node with the current number as its value.\n4. While the stack is not empty and the current number is greater than the v...
10
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: 1. Create a root node whose value is the maximum value in `nums`. 2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum val...
null
Use Stack (Python, O(n) time/space)
maximum-binary-tree
0
1
Hi everyone. I liked this problem so much that I decided to write this article about my approach to solving this problem. So let us dive into it.\n\nMy first thoughts about a recursive solution were exactly the same as in the official guide:\n1. Find the maximum `max` and make it the `root` of the tree\n1. Divide the a...
42
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: 1. Create a root node whose value is the maximum value in `nums`. 2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum val...
null
Marvellous Code Technique Python3
maximum-binary-tree
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)$$ --...
6
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: 1. Create a root node whose value is the maximum value in `nums`. 2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum val...
null
Solution
print-binary-tree
1
1
```C++ []\nclass Solution {\n public:\n vector<vector<string>> printTree(TreeNode* root) {\n const int m = maxHeight(root);\n const int n = pow(2, m) - 1;\n vector<vector<string>> ans(m, vector<string>(n));\n dfs(root, 0, 0, ans[0].size() - 1, ans);\n return ans;\n }\n private:\n int maxHeight(TreeNod...
1
Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules: * The **height** of the tree is `height` and the number of rows `m` should be equal to `height + 1`...
null
655: Time 94.44%, Solution with step by step explanation
print-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Calculate the height of the given binary tree using the get_height function, which takes a node as input and returns the height of the tree. Here, the height is defined as the length of the longest path from the root to a...
3
Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules: * The **height** of the tree is `height` and the number of rows `m` should be equal to `height + 1`...
null
Python BFS simple
print-binary-tree
0
1
```python\ndef printTree(self, root: TreeNode) -> List[List[str]]:\n \n def getHeight(node=root):\n return 1+max(getHeight(node.left), getHeight(node.right)) if node else 0\n \n height = getHeight()-1\n columns = 2**(height+1)-1\n res = [[""]*columns for _ in range(h...
6
Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules: * The **height** of the tree is `height` and the number of rows `m` should be equal to `height + 1`...
null
Easy O(n) approach for beginner, 73%
print-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nGet height of tree in first traverse.\nCreate matrix.\nAssign value to matrix in second traver.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-...
0
Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules: * The **height** of the tree is `height` and the number of rows `m` should be equal to `height + 1`...
null