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 -> 91.11% faster. 52ms time. Explanation added | how-many-numbers-are-smaller-than-the-current-number | 0 | 1 | **Suggestions to make it better are always welcomed.**\n\n**2 possible solutions:**\n1. For every i element, iterate the list with j as index. If i!=j and nums[j]<nums[i], we can update the count for that number. Time: O(n2). Space: O(1)\n2. This is optimal solution. We can sort the list and store in another temp list.... | 201 | You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet... | Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element. |
Python3 easy solution, Beats 97% | how-many-numbers-are-smaller-than-the-current-number | 0 | 1 | # Intuition\nIf we find a way to not count the duplicates then the index of the numbers when sorted corresponds to the the number of values less than them. so based on this information the solution becomes relatively easy to find\n\n# Approach\nFirst duplicate the array and sort it. then iterate over the sorted duplica... | 4 | Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`.
Return the answer in an array.
**Example 1:**
**Input:** nums = \[8,1,2,2,3\]
**Output:** \[4,... | null |
Python3 easy solution, Beats 97% | how-many-numbers-are-smaller-than-the-current-number | 0 | 1 | # Intuition\nIf we find a way to not count the duplicates then the index of the numbers when sorted corresponds to the the number of values less than them. so based on this information the solution becomes relatively easy to find\n\n# Approach\nFirst duplicate the array and sort it. then iterate over the sorted duplica... | 4 | You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet... | Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element. |
Concise Python solution | how-many-numbers-are-smaller-than-the-current-number | 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 the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`.
Return the answer in an array.
**Example 1:**
**Input:** nums = \[8,1,2,2,3\]
**Output:** \[4,... | null |
Concise Python solution | how-many-numbers-are-smaller-than-the-current-number | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet... | Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element. |
Brute Force Method & Sorting and Dictionary Method | how-many-numbers-are-smaller-than-the-current-number | 0 | 1 | # Brute Force Method: \n\n# Complexity\n- Time complexity:\nO(N^2) - It\'s kind of inefficient with larger inputs!\n\n# Code\n```\nclass Solution:\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n List = []\n for i in range(len(nums)):\n count = 0\n for j in r... | 4 | Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`.
Return the answer in an array.
**Example 1:**
**Input:** nums = \[8,1,2,2,3\]
**Output:** \[4,... | null |
Brute Force Method & Sorting and Dictionary Method | how-many-numbers-are-smaller-than-the-current-number | 0 | 1 | # Brute Force Method: \n\n# Complexity\n- Time complexity:\nO(N^2) - It\'s kind of inefficient with larger inputs!\n\n# Code\n```\nclass Solution:\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n List = []\n for i in range(len(nums)):\n count = 0\n for j in r... | 4 | You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet... | Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element. |
Intuitive Python Solution (>95%) - Full Explanation + Good Variable Names | rank-teams-by-votes | 0 | 1 | # Intuition\n1. Use point vectors to keep track of positional rankings. (stored in a dictionary by team name as key)\n2. Use a decrementing point scale from N -> 0 to track rank of team at particular position (lower is better). N=number of votes.\n3. Sort return team list in ascending order based on primary criteria of... | 14 | In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie a... | Use doubly Linked list with hashmap of pointers to linked list nodes. add unique number to the linked list. When add is called check if the added number is unique then it have to be added to the linked list and if it is repeated remove it from the linked list if exists. When showFirstUnique is called retrieve the head ... |
Intuitive Python Solution (>95%) - Full Explanation + Good Variable Names | rank-teams-by-votes | 0 | 1 | # Intuition\n1. Use point vectors to keep track of positional rankings. (stored in a dictionary by team name as key)\n2. Use a decrementing point scale from N -> 0 to track rank of team at particular position (lower is better). N=number of votes.\n3. Sort return team list in ascending order based on primary criteria of... | 14 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
[python] O(N logN) solution, explained & easy-understanding | rank-teams-by-votes | 0 | 1 | ### Steps\n1. Create a ranking system for each char of each string in the array (hashmap), s.t.:\n\t```python\n\t\td = {\n\t\t\t\'A\': [0, 0, 0], # initialize array of size len(string)\n\t\t\t\'B\': [0, 0, 0],\n\t\t\t...\n\t\t}\n\t```\n2. For each char in the string, we add 1 to the position they are ranked,\n\te.g. `... | 50 | In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie a... | Use doubly Linked list with hashmap of pointers to linked list nodes. add unique number to the linked list. When add is called check if the added number is unique then it have to be added to the linked list and if it is repeated remove it from the linked list if exists. When showFirstUnique is called retrieve the head ... |
[python] O(N logN) solution, explained & easy-understanding | rank-teams-by-votes | 0 | 1 | ### Steps\n1. Create a ranking system for each char of each string in the array (hashmap), s.t.:\n\t```python\n\t\td = {\n\t\t\t\'A\': [0, 0, 0], # initialize array of size len(string)\n\t\t\t\'B\': [0, 0, 0],\n\t\t\t...\n\t\t}\n\t```\n2. For each char in the string, we add 1 to the position they are ranked,\n\te.g. `... | 50 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
python 3 || simple O(n)/O(1) solution | rank-teams-by-votes | 0 | 1 | ```\nclass Solution:\n def rankTeams(self, votes: List[str]) -> str:\n teamVotes = collections.defaultdict(lambda: [0] * 26)\n for vote in votes:\n for pos, team in enumerate(vote):\n teamVotes[team][pos] += 1\n \n return \'\'.join(sorted(teamVotes.keys(), revers... | 5 | In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie a... | Use doubly Linked list with hashmap of pointers to linked list nodes. add unique number to the linked list. When add is called check if the added number is unique then it have to be added to the linked list and if it is repeated remove it from the linked list if exists. When showFirstUnique is called retrieve the head ... |
python 3 || simple O(n)/O(1) solution | rank-teams-by-votes | 0 | 1 | ```\nclass Solution:\n def rankTeams(self, votes: List[str]) -> str:\n teamVotes = collections.defaultdict(lambda: [0] * 26)\n for vote in votes:\n for pos, team in enumerate(vote):\n teamVotes[team][pos] += 1\n \n return \'\'.join(sorted(teamVotes.keys(), revers... | 5 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
[Python3] Very Straightforward Solution | linked-list-in-binary-tree | 0 | 1 | # Code\n```\nclass Solution:\n def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:\n \n self.graph = collections.defaultdict(list)\n self.lst = []\n tmp = head\n while tmp != None:\n self.lst.append(tmp)\n tmp = tmp.next\n\n ... | 1 | Given a binary tree `root` and a linked list with `head` as the first node.
Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes d... | Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest? |
✅ The Easiest Solution | linked-list-in-binary-tree | 0 | 1 | # Approach\nOrdinary DFS traversal is used. Each node of tree is checked to be part of the list - as easy as possible.\n\n# Complexity\n- Time complexity: $$O(n)$$ in most usual cases, $$O(n^2)$$ in the worst case, when the tree and list contain the same value but list is larger then tree height.\n\n- Space complexity:... | 2 | Given a binary tree `root` and a linked list with `head` as the first node.
Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes d... | Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest? |
Python : Fastest Approach | linked-list-in-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)$$ --... | 1 | Given a binary tree `root` and a linked list with `head` as the first node.
Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes d... | Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest? |
🔥[Python 3] BFS + DFS combination | linked-list-in-binary-tree | 0 | 1 | ### Time complexity: \n`O(N) * min(O(H), O(L))`\nwhere N - tree size, H - tree height, L - list length\n```python3 []\nclass Solution:\n def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:\n def isEqual(treeNode, listNode):\n if not listNode: return True\n i... | 3 | Given a binary tree `root` and a linked list with `head` as the first node.
Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes d... | Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest? |
[Python3] 0-1 BFS - Simple Solution | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(M * N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M * N)$$\n<!-- Add your space complex... | 1 | Given an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:
* `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)
* `2` which means go to the cell to the left. (i.e go ... | null |
python bfs with heap | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | 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 an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:
* `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)
* `2` which means go to the cell to the left. (i.e go ... | null |
[Python] O(MN), simple BFS with explanation | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | 0 | 1 | **Idea**\nThis is a typical BFS question on Graph. \nEssentially, we need to track `visited` nodes to eliminate duplicated exploration, which both affect correctness and efficiency.\n\n**Complexity**\nTime: `O(mn)`\nSpace: `O(mn)`\n\n**Python 3, BFS**\n```\nclass Solution:\n def minCost(self, grid: List[List[int]]) ... | 30 | Given an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:
* `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)
* `2` which means go to the cell to the left. (i.e go ... | null |
Python 3 || dfs & bfs, no recursion || T/M: 94% / 98% | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | 0 | 1 | We re-use grid to keep track of `seen`.\n```\nclass Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n\n m, n, cost, queue = len(grid), len(grid[0]), 0, deque()\n M, N = range(m), range(n)\n\n seen = lambda x,y : not x in M or y not in N or not grid[x][y]\n dir = ((),(0,1), (0... | 5 | Given an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:
* `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)
* `2` which means go to the cell to the left. (i.e go ... | null |
63% TC and 78% SC easy python solution | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | 0 | 1 | ```\ndef minCost(self, grid: List[List[int]]) -> int:\n\tm, n = len(grid), len(grid[0])\n\tdir = [(0, 1), (0, -1), (1, 0), (-1, 0)] \n\t# in order of grid value for direction\n\tdis = [[float(\'inf\')] * n for _ in range(m)]\n\tdis[0][0] = 0\n\theap = [(dis[0][0], [0, 0])]\n\twhile(heap):\n\t\td, [i, j] = heappop(heap)... | 1 | Given an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:
* `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)
* `2` which means go to the cell to the left. (i.e go ... | null |
Python | Template | 0-1 BFS vs Dijkstra | Explanation | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | 0 | 1 | * I modelled the graph such that each cell in grid has 4 neighbors and cost to a neighbor is 0 if grid has value pointing to that direction, else cost = 1\n* 0-1 BFS appends to the left if neighbor cost is same as current node cost. Else, it appends to the end. The idea comes from standard BFS and Dijsktra to use a que... | 3 | Given an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:
* `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)
* `2` which means go to the cell to the left. (i.e go ... | null |
Simple Java Solution - Count Array | increasing-decreasing-string | 1 | 1 | # Code\n```\nclass Solution {\n public String sortString(String s) {\n int[] alpha = new int[27];\n for(char ch : s.toCharArray())\n {\n alpha[ch-\'a\']++;\n }\n String result = "";\n boolean flag = false;\n while(flag!=true)\n {\n flag = ... | 2 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot ... | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
Simple solution by Python 3 | increasing-decreasing-string | 0 | 1 | ```\nclass Solution:\n def sortString(self, s: str) -> str:\n s = list(s)\n result = \'\'\n while s:\n for letter in sorted(set(s)):\n s.remove(letter)\n result += letter\n for letter in sorted(set(s), reverse=True):\n s.remove(l... | 64 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot ... | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
Python | Using dict | Beats 95% | increasing-decreasing-string | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a frequency map of s.\n\nIterate over all the letters of s in sorted manner and add that character to result .\n\nRepeat above step but for reversed string.\n \nIf the frequency becomes 0 then we delete the key from dict.\n\n# Code\n```\ncl... | 2 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot ... | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
[Python] Easy-to-understand solution explained | increasing-decreasing-string | 0 | 1 | Steps:\n1. Count the number of occurrences of every letter.\n2. Sort in alphabetic order.\n3. Follow the procedure defined in the problem statement.\n```python\ndef sortString(self, s: str) -> str:\n d = sorted([c, n] for c, n in collections.Counter(s).items())\n r = []\n while len(r) < len(s):\n for i ... | 51 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot ... | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
[Python 3] Using Set and Sort with commentary | increasing-decreasing-string | 0 | 1 | ```\nclass Solution:\n def sortString(self, s: str) -> str:\n s = list(s)\n # Big S: O(n)\n result = []\n \n # Logic is capture distinct char with set\n # Remove found char from initial string\n \n # Big O: O(n)\n while len(s) > 0:\n\n # Big O... | 12 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot ... | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
[Python 3] Simple Clean code, beats >98% speed. | increasing-decreasing-string | 0 | 1 | Strategy : \n1. Maintain a counter/dictionary of all characters\n2. Maintain a list of sorted characters\n3. Everytime a character is chosen from the dictionary its count is reduced, if it becomes zero the dictionary key is removed\n4. Iterate over this list in ascending and descending order alternatively, adding eleme... | 5 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot ... | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
[Python/Python 3] hashmap easy-understand solution!!! Beats 97% | increasing-decreasing-string | 0 | 1 | ```\nclass Solution(object):\n def sortString(self, s):\n dict = {}\n for s1 in s:\n dict[s1] = dict.get(s1, 0)+1\n list1 = sorted(list(set(s)))\n \n result = \'\'\n while len(result) < len(s):\n for l in list1:\n if l in dict and dict[l]... | 1 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot ... | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
[Python] solution in O(n) time and O(1) space explained | find-the-longest-substring-containing-vowels-in-even-counts | 0 | 1 | We can use 5 bits to represent the parity of the number of occurrences of vowels. For example, we can use 0/1 for even/odd numbers, then if we have 4a, 3e, 2i, 1o, 0u, the representation would be 01010. As we scan through the array, we can update the representation in O(1) time by using the XOR operation, and then stor... | 77 | Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
**Example 1:**
**Input:** s = "eleetminicoworoep "
**Output:** 13
**Explanation:** The longest substring is "leetminicowor " which c... | Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way. |
[Python] solution in O(n) time and O(1) space explained | find-the-longest-substring-containing-vowels-in-even-counts | 0 | 1 | We can use 5 bits to represent the parity of the number of occurrences of vowels. For example, we can use 0/1 for even/odd numbers, then if we have 4a, 3e, 2i, 1o, 0u, the representation would be 01010. As we scan through the array, we can update the representation in O(1) time by using the XOR operation, and then stor... | 77 | There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
* For example: `hous... | Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring. |
Python 3 || 8 lines, bit mask, w/example || T/M: 91% / 69% | find-the-longest-substring-containing-vowels-in-even-counts | 0 | 1 | ```\nclass Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n # Example: \'leetcodoe\'\n d = defaultdict(int)\n v = {\'a\':0,\'e\':1,\'i\':2,\'o\':3,\'u\':4,} # i ch n ans d\n n, ans, d[0] = 0, 0, -1 ... | 8 | Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
**Example 1:**
**Input:** s = "eleetminicoworoep "
**Output:** 13
**Explanation:** The longest substring is "leetminicowor " which c... | Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way. |
Python 3 || 8 lines, bit mask, w/example || T/M: 91% / 69% | find-the-longest-substring-containing-vowels-in-even-counts | 0 | 1 | ```\nclass Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n # Example: \'leetcodoe\'\n d = defaultdict(int)\n v = {\'a\':0,\'e\':1,\'i\':2,\'o\':3,\'u\':4,} # i ch n ans d\n n, ans, d[0] = 0, 0, -1 ... | 8 | There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
* For example: `hous... | Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring. |
Prefix Sum Classic Solution | find-the-longest-substring-containing-vowels-in-even-counts | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code\n```\nclass Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n vowels = \'aeiou\'\n pref = {0: -1}\n maxSize = 0\n mask = 0\n for i, ch in enumerate(s):\n if (ind := vowels... | 0 | Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
**Example 1:**
**Input:** s = "eleetminicoworoep "
**Output:** 13
**Explanation:** The longest substring is "leetminicowor " which c... | Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way. |
Prefix Sum Classic Solution | find-the-longest-substring-containing-vowels-in-even-counts | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code\n```\nclass Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n vowels = \'aeiou\'\n pref = {0: -1}\n maxSize = 0\n mask = 0\n for i, ch in enumerate(s):\n if (ind := vowels... | 0 | There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
* For example: `hous... | Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring. |
O(n) python solution | find-the-longest-substring-containing-vowels-in-even-counts | 0 | 1 | # Intuition\ncalculated xor of everything, if xor is 0 then elements upto that index then we have even vowels and length of the substring will be index + 1 , but there is one another way of finding a substring with even vowels (if xor of elements from 0 to a has xor = y and xor from 0 to b has also xor = y, such that a... | 0 | Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
**Example 1:**
**Input:** s = "eleetminicoworoep "
**Output:** 13
**Explanation:** The longest substring is "leetminicowor " which c... | Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way. |
O(n) python solution | find-the-longest-substring-containing-vowels-in-even-counts | 0 | 1 | # Intuition\ncalculated xor of everything, if xor is 0 then elements upto that index then we have even vowels and length of the substring will be index + 1 , but there is one another way of finding a substring with even vowels (if xor of elements from 0 to a has xor = y and xor from 0 to b has also xor = y, such that a... | 0 | There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
* For example: `hous... | Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring. |
Image Explanation🏆- [Easy & Complete Intuition] - C++/Java/Python | longest-zigzag-path-in-a-binary-tree | 1 | 1 | # Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Longest ZigZag Path in a Binary Tree` by `Aryan Mittal`\n\n\n\n# Approach & Intution\n.
* If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
* Change the direction f... | Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma. |
[Python] Efficient and Easy Depth-First Search (DFS) Solution | longest-zigzag-path-in-a-binary-tree | 0 | 1 | # Approach\nTo solve this problem, we can use the DFS (Depth-First Search) approach while keeping track of the previous traversal. When the previous traversal goes to the left, the next traversal to the right can make use of the previous height. However, if the next traversal goes to the left again, its height will sta... | 1 | You are given the `root` of a binary tree.
A ZigZag path for a binary tree is defined as follow:
* Choose **any** node in the binary tree and a direction (right or left).
* If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
* Change the direction f... | Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma. |
[Python] Easy traversal with explanation | maximum-sum-bst-in-binary-tree | 0 | 1 | **Idea**\nFor each subtree, we return 4 elements.\n1. the status of this subtree, `1` means it\'s empty, `2` means it\'s a BST, `0` means it\'s not a BST\n2. size of this subtree (we only care about size of BST though)\n3. the minimal value in this subtree\n4. the maximal value in this subtree\n\nThen we only need to m... | 41 | Given a **binary tree** `root`, return _the maximum sum of all keys of **any** sub-tree which is also a Binary Search Tree (BST)_.
Assume a BST is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with key... | null |
[Python] Easy traversal with explanation | maximum-sum-bst-in-binary-tree | 0 | 1 | **Idea**\nFor each subtree, we return 4 elements.\n1. the status of this subtree, `1` means it\'s empty, `2` means it\'s a BST, `0` means it\'s not a BST\n2. size of this subtree (we only care about size of BST though)\n3. the minimal value in this subtree\n4. the maximal value in this subtree\n\nThen we only need to m... | 41 | You are given an integer array `prices` where `prices[i]` is the price of the `ith` item in a shop.
There is a special discount for items in the shop. If you buy the `ith` item, then you will receive a discount equivalent to `prices[j]` where `j` is the minimum index such that `j > i` and `prices[j] <= prices[i]`. Oth... | Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minLeft). In each node compute theses parameters, following the conditions of a Binary Search Tree. |
Python || Easy || Bottom up approach | maximum-sum-bst-in-binary-tree | 0 | 1 | ```\nclass NodeValue:\n def __init__(self, minNode, maxNode, Sum):\n self.maxNode = maxNode\n self.minNode = minNode\n self.Sum = Sum\n\nclass Solution:\n def largestBstHelper(self, node):\n if not node:\n return NodeValue(float(\'inf\'), float(\'-inf\'), 0)\n\n left ... | 5 | Given a **binary tree** `root`, return _the maximum sum of all keys of **any** sub-tree which is also a Binary Search Tree (BST)_.
Assume a BST is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with key... | null |
Python || Easy || Bottom up approach | maximum-sum-bst-in-binary-tree | 0 | 1 | ```\nclass NodeValue:\n def __init__(self, minNode, maxNode, Sum):\n self.maxNode = maxNode\n self.minNode = minNode\n self.Sum = Sum\n\nclass Solution:\n def largestBstHelper(self, node):\n if not node:\n return NodeValue(float(\'inf\'), float(\'-inf\'), 0)\n\n left ... | 5 | You are given an integer array `prices` where `prices[i]` is the price of the `ith` item in a shop.
There is a special discount for items in the shop. If you buy the `ith` item, then you will receive a discount equivalent to `prices[j]` where `j` is the minimum index such that `j > i` and `prices[j] <= prices[i]`. Oth... | Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minLeft). In each node compute theses parameters, following the conditions of a Binary Search Tree. |
Simple Code $$ Easy to Understand | generate-a-string-with-characters-that-have-odd-counts | 0 | 1 | # Code\n```\nclass Solution:\n def generateTheString(self, n: int) -> str:\n res = ""\n if n%2 != 0:\n return "a"*n\n res = "a"*(n-1)\n return res+"b"\n``` | 1 | Given an integer `n`, _return a string with `n` characters such that each character in such string occurs **an odd number of times**_.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return **any** of them.
**Example 1:**
**Input:** n = 4
**Output:** "pppz "
**... | 1. (Binary Search) For each row do a binary search to find the leftmost one on that row and update the answer. 2. (Optimal Approach) Imagine there is a pointer p(x, y) starting from top right corner. p can only move left or down. If the value at p is 0, move down. If the value at p is 1, move left. Try to figure out th... |
Python one line simple solution | generate-a-string-with-characters-that-have-odd-counts | 0 | 1 | **Python :**\n\n```\ndef generateTheString(self, n: int) -> str:\n\treturn "a" * n if n % 2 else "a" * (n - 1) + "b"\n```\n\n**Like it ? please upvote !** | 9 | Given an integer `n`, _return a string with `n` characters such that each character in such string occurs **an odd number of times**_.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return **any** of them.
**Example 1:**
**Input:** n = 4
**Output:** "pppz "
**... | 1. (Binary Search) For each row do a binary search to find the leftmost one on that row and update the answer. 2. (Optimal Approach) Imagine there is a pointer p(x, y) starting from top right corner. p can only move left or down. If the value at p is 0, move down. If the value at p is 1, move left. Try to figure out th... |
One Liner Python3 | generate-a-string-with-characters-that-have-odd-counts | 0 | 1 | \n\n# 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)$$ -->\n\n# Code\n```\nclass Solution:\n def generateTheString(self, n: int) -> str:\n \n return \'a\' * n if n % 2 != 0 else \'a... | 2 | Given an integer `n`, _return a string with `n` characters such that each character in such string occurs **an odd number of times**_.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return **any** of them.
**Example 1:**
**Input:** n = 4
**Output:** "pppz "
**... | 1. (Binary Search) For each row do a binary search to find the leftmost one on that row and update the answer. 2. (Optimal Approach) Imagine there is a pointer p(x, y) starting from top right corner. p can only move left or down. If the value at p is 0, move down. If the value at p is 1, move left. Try to figure out th... |
Python || Easy || 94.60% Faster ||One Line Solution | generate-a-string-with-characters-that-have-odd-counts | 0 | 1 | ```\nclass Solution:\n def generateTheString(self, n: int) -> str:\n return \'a\'*(n-1)+\'b\' if n%2==0 else \'a\'*n\n```\n\n**An upvote will be encouraging** | 2 | Given an integer `n`, _return a string with `n` characters such that each character in such string occurs **an odd number of times**_.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return **any** of them.
**Example 1:**
**Input:** n = 4
**Output:** "pppz "
**... | 1. (Binary Search) For each row do a binary search to find the leftmost one on that row and update the answer. 2. (Optimal Approach) Imagine there is a pointer p(x, y) starting from top right corner. p can only move left or down. If the value at p is 0, move down. If the value at p is 1, move left. Try to figure out th... |
Keep track of the largest bit | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\nTo solve this problem we need to note one intricacy that will always hold true\n* Each bit only appears in `flips` once. \n* Therefore, if bit x is on (one based), then it is only possible to be "Prefix-Aligned" if we are on flip x (also one based). \n\nWe can now keep track of the largest bit, and the num... | 4 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
Keep track of the largest bit | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\nTo solve this problem we need to note one intricacy that will always hold true\n* Each bit only appears in `flips` once. \n* Therefore, if bit x is on (one based), then it is only possible to be "Prefix-Aligned" if we are on flip x (also one based). \n\nWe can now keep track of the largest bit, and the num... | 4 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Python 3 || 6 lines, w/ explanation || T/M: 90% / 96% | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | Here\'s the plan:\n- The binary string is prefix-aligned if and only if the flips comprise a set of consecutive integers beginning with one (`123` is valid, `234` or `125` is not)\n- The indices will always comprise a set of consecutive integers beginning with zero.\n- The binary string is prefix-aligned after `k` flip... | 5 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
Python 3 || 6 lines, w/ explanation || T/M: 90% / 96% | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | Here\'s the plan:\n- The binary string is prefix-aligned if and only if the flips comprise a set of consecutive integers beginning with one (`123` is valid, `234` or `125` is not)\n- The indices will always comprise a set of consecutive integers beginning with zero.\n- The binary string is prefix-aligned after `k` flip... | 5 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Python3 solution O(n) time and O(1) space complexity | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | ```\nclass Solution:\n def numTimesAllBlue(self, light: List[int]) -> int:\n max = count = 0\n for i in range(len(light)):\n if max < light[i]:\n max = light[i]\n if max == i + 1:\n count += 1\n return count\n```\n**If you like this solution, p... | 4 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
Python3 solution O(n) time and O(1) space complexity | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | ```\nclass Solution:\n def numTimesAllBlue(self, light: List[int]) -> int:\n max = count = 0\n for i in range(len(light)):\n if max < light[i]:\n max = light[i]\n if max == i + 1:\n count += 1\n return count\n```\n**If you like this solution, p... | 4 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Intuitive Math Approach O(N) time, O(1) space | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\nYou basically need to check if the numbers are continuous up until point i. (e.g. 1,2,3,4,5..., i for all i). You don\'t actually need to track the length since as you iterate through x it\'ll always be the same. The only time the function is continuous is if the sum of up to element x is the same as the s... | 0 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
Intuitive Math Approach O(N) time, O(1) space | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\nYou basically need to check if the numbers are continuous up until point i. (e.g. 1,2,3,4,5..., i for all i). You don\'t actually need to track the length since as you iterate through x it\'ll always be the same. The only time the function is continuous is if the sum of up to element x is the same as the s... | 0 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
One-line python solution | number-of-times-binary-string-is-prefix-aligned | 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 have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
One-line python solution | number-of-times-binary-string-is-prefix-aligned | 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 array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Easy O(n) math + prefix sum in python 3 | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck if prefix sum is equal to the range sum from 0 to length of prefix array sum(range(i+2)) -> sum(0, 1, ... i+1). This way there is no need to keep track of which numbers are missing since each range sum is distinct. \n# Approach\n<!-... | 0 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
Easy O(n) math + prefix sum in python 3 | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck if prefix sum is equal to the range sum from 0 to length of prefix array sum(range(i+2)) -> sum(0, 1, ... i+1). This way there is no need to keep track of which numbers are missing since each range sum is distinct. \n# Approach\n<!-... | 0 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
clever O(N) python solution | number-of-times-binary-string-is-prefix-aligned | 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 have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
clever O(N) python solution | number-of-times-binary-string-is-prefix-aligned | 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 array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
O(n) solution | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $... | 0 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
O(n) solution | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $... | 0 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Python3 Concise straight forward solution | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def numTimesAllBlue(self, flips: List[int]) -> int:\n \n n=len(flips)\n ans=mask=curr=0\n \n for i,f in enumerate(flips):\n curr+=(1<<(n-i-1))\n mask=mask^(1<<(n-f))\n if curr==mask:\n ans+=1\n ... | 0 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
Python3 Concise straight forward solution | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def numTimesAllBlue(self, flips: List[int]) -> int:\n \n n=len(flips)\n ans=mask=curr=0\n \n for i,f in enumerate(flips):\n curr+=(1<<(n-i-1))\n mask=mask^(1<<(n-f))\n if curr==mask:\n ans+=1\n ... | 0 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
[Python] Solution Easy to Understand | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Code\n```\nclass Solution:\n def numTimesAllBlue(self, flips: List[int]) -> int:\n n = len(flips)\n l = 1e9\n r = 0\n res = 0\n flipOne = False\n for i in range(n):\n if flips[i] == 1: flipOne = True\n if flips[i] < l:\n l = flips[i]\n ... | 0 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
[Python] Solution Easy to Understand | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Code\n```\nclass Solution:\n def numTimesAllBlue(self, flips: List[int]) -> int:\n n = len(flips)\n l = 1e9\n r = 0\n res = 0\n flipOne = False\n for i in range(n):\n if flips[i] == 1: flipOne = True\n if flips[i] < l:\n l = flips[i]\n ... | 0 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Python - Bitwise | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\nSet bit of flip[i], and check [1, i] are all ones by masking.\n\n# Complexity\n- Time complexity: $$O(n)$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numTimesAllBlu... | 0 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
Python - Bitwise | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Intuition\nSet bit of flip[i], and check [1, i] are all ones by masking.\n\n# Complexity\n- Time complexity: $$O(n)$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numTimesAllBlu... | 0 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
EASY AND COINCISE SOLUTION BEATS 91,37% OF RUNTIME ✅ | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n\n# Code\n```\nclass Solution(object):\n def numTimesAllBlue(self, flips):\n\n pivot = flips[0]\n ans = 1 if pivot == 1 else 0\n left = 0\n \n for i in range(1, len(flips)):\n \n if flips[i... | 0 | You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`... | For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome. |
EASY AND COINCISE SOLUTION BEATS 91,37% OF RUNTIME ✅ | number-of-times-binary-string-is-prefix-aligned | 0 | 1 | # Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n\n# Code\n```\nclass Solution(object):\n def numTimesAllBlue(self, flips):\n\n pivot = flips[0]\n ans = 1 if pivot == 1 else 0\n left = 0\n \n for i in range(1, len(flips)):\n \n if flips[i... | 0 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Simple and optimal python3 solution | time-needed-to-inform-all-employees | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nfrom collections import defaultdict\n\nclass Solution:\n def numOfMinutes(self, n: int, headID: int, mana... | 1 | A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`.
Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that th... | null |
Simple and optimal python3 solution | time-needed-to-inform-all-employees | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nfrom collections import defaultdict\n\nclass Solution:\n def numOfMinutes(self, n: int, headID: int, mana... | 1 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Beating 97.72% Python Easiest Solution | time-needed-to-inform-all-employees | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: \n def calculateTime(n: int) -> int:\n if manage... | 1 | A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`.
Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that th... | null |
Beating 97.72% Python Easiest Solution | time-needed-to-inform-all-employees | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: \n def calculateTime(n: int) -> int:\n if manage... | 1 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
✨🔥 Python: BFS Solution 🔥✨ | time-needed-to-inform-all-employees | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nBFS\n\n# Complexity\n- Time complexity: O(V)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(V)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numOfMinutes(self, n: int,... | 1 | A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`.
Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that th... | null |
✨🔥 Python: BFS Solution 🔥✨ | time-needed-to-inform-all-employees | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nBFS\n\n# Complexity\n- Time complexity: O(V)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(V)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numOfMinutes(self, n: int,... | 1 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
✅ 🔥 Python3 || ⚡easy solution | time-needed-to-inform-all-employees | 0 | 1 | \n```\nclass Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: \n def calculateTime(n: int) -> int:\n if manager[n] != -1:\n informTime[n] += calculateTime(manager[n])\n manager[n] = -1\n return... | 1 | A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`.
Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that th... | null |
✅ 🔥 Python3 || ⚡easy solution | time-needed-to-inform-all-employees | 0 | 1 | \n```\nclass Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: \n def calculateTime(n: int) -> int:\n if manager[n] != -1:\n informTime[n] += calculateTime(manager[n])\n manager[n] = -1\n return... | 1 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Python short and clean. DFS. Functional programming. | time-needed-to-inform-all-employees | 0 | 1 | # Approach\n1. Construct an `WeightedTree` of the form,\n `WeightedTree = (Weight, List of child WeightedTrees)`,\n with managers as parent nodes and employees as child nodes, `inform_time` as `Weight`.\n\n2. Define, `max_path_sum of root = Weight of root + max(max_path_sum of all children)`.\n\n3. Return `max_pa... | 2 | A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`.
Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that th... | null |
Python short and clean. DFS. Functional programming. | time-needed-to-inform-all-employees | 0 | 1 | # Approach\n1. Construct an `WeightedTree` of the form,\n `WeightedTree = (Weight, List of child WeightedTrees)`,\n with managers as parent nodes and employees as child nodes, `inform_time` as `Weight`.\n\n2. Define, `max_path_sum of root = Weight of root + max(max_path_sum of all children)`.\n\n3. Return `max_pa... | 2 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Simple Python Solution using BFS | frog-position-after-t-seconds | 0 | 1 | \n# Code\n```\nfrom queue import Queue\n\nclass Solution:\n def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n if edges == []:\n if target == 1:return 1\n return 0\n\n d = {}\n for i in edges:\n d[i[0]] = d.get(i[0] , []) + [i... | 2 | Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from **vertex 1**. In one second, the frog jumps from its current vertex to another **unvisited** vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to severa... | null |
Simple Python Solution using BFS | frog-position-after-t-seconds | 0 | 1 | \n# Code\n```\nfrom queue import Queue\n\nclass Solution:\n def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n if edges == []:\n if target == 1:return 1\n return 0\n\n d = {}\n for i in edges:\n d[i[0]] = d.get(i[0] , []) + [i... | 2 | Given a binary array `nums`, you should delete one element from it.
Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.
**Example 1:**
**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in pos... | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
[Python] Easy DFS/BFS with explanation | frog-position-after-t-seconds | 0 | 1 | **Idea**\nFirst we build an adjacency list using `edges`.\nWe then DFS through all the nodes. Do note that we can only visited a node once in an undirected graph. There are basically 2 solutions.\n1. Construct a undirected graph and transform it into a directed tree first **(method 1)**\n2. Use set to record all the vi... | 21 | Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from **vertex 1**. In one second, the frog jumps from its current vertex to another **unvisited** vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to severa... | null |
[Python] Easy DFS/BFS with explanation | frog-position-after-t-seconds | 0 | 1 | **Idea**\nFirst we build an adjacency list using `edges`.\nWe then DFS through all the nodes. Do note that we can only visited a node once in an undirected graph. There are basically 2 solutions.\n1. Construct a undirected graph and transform it into a directed tree first **(method 1)**\n2. Use set to record all the vi... | 21 | Given a binary array `nums`, you should delete one element from it.
Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.
**Example 1:**
**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in pos... | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
BFS Based Appraoch that beats 95% of all the entries || Pyhton 3 Solution | frog-position-after-t-seconds | 0 | 1 | # Intuition\nLooking at the question the first thing that strikes is a level order traversal of the graph and based on this the answer will be calculated\n# Approach\nDoing a Normal BFS wont work here\n\nOne of the most important lines is this questions is that whenever our frog reachs to target node and if there is mo... | 0 | Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from **vertex 1**. In one second, the frog jumps from its current vertex to another **unvisited** vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to severa... | null |
BFS Based Appraoch that beats 95% of all the entries || Pyhton 3 Solution | frog-position-after-t-seconds | 0 | 1 | # Intuition\nLooking at the question the first thing that strikes is a level order traversal of the graph and based on this the answer will be calculated\n# Approach\nDoing a Normal BFS wont work here\n\nOne of the most important lines is this questions is that whenever our frog reachs to target node and if there is mo... | 0 | Given a binary array `nums`, you should delete one element from it.
Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.
**Example 1:**
**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in pos... | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
🔥 Pandas Simple 1 Line Solution For Beginners 💯 | replace-employee-id-with-the-unique-identifier | 0 | 1 | **\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nimport pandas as pd\n\ndef replace_employee_id(employees: pd.DataFrame, employee_uni: pd.DataFrame) -> pd.DataFrame:\n \n result = pd.merge(employees, employee_uni, on=\'id\', how=\'left\')\n \n return result[[\'unique_id\', \'n... | 3 | You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation... | null |
Pandas vs SQL | Elegant & Short | All 30 Days of Pandas solutions ✅ | replace-employee-id-with-the-unique-identifier | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef replace_employee_id(employees: pd.DataFrame, employee_uni: pd.DataFrame) -> pd.DataFrame:\n return pd.merge(\n employees, employee_uni, how=\'left\', on=\'id\'\n )[[\'unique_id\', \'name\']]\n```\n```SQL []... | 14 | You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation... | null |
Python3 Iterative and recursive DFS | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | \n\n# Complexity\n- Time complexity: O(n), whenre n is the number of nodes in cloned tree\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(h), where h is the height of the cloned tree\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree no... | 1 | Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.
The `cloned` tree is a **copy of** the `original` tree.
Return _a reference to the same node_ in the `cloned` tree.
**Note** that you are **not allowed** to change any of the two trees or the `target` node a... | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
Python3 Iterative and recursive DFS | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | \n\n# Complexity\n- Time complexity: O(n), whenre n is the number of nodes in cloned tree\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(h), where h is the height of the cloned tree\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree no... | 1 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
Easy to Understand || Beginner Friendly || Python 3 || Beats 100% Easy | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | # Intuition\nThe problem asks us to find a corresponding node in a clone of a binary tree when given the original tree and a target node in the original tree. To solve this, we can perform a depth-first search (DFS) traversal of both trees to find the corresponding node in the cloned tree.\n\n# Approach\nWe use a recur... | 2 | Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.
The `cloned` tree is a **copy of** the `original` tree.
Return _a reference to the same node_ in the `cloned` tree.
**Note** that you are **not allowed** to change any of the two trees or the `target` node a... | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
Easy to Understand || Beginner Friendly || Python 3 || Beats 100% Easy | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | # Intuition\nThe problem asks us to find a corresponding node in a clone of a binary tree when given the original tree and a target node in the original tree. To solve this, we can perform a depth-first search (DFS) traversal of both trees to find the corresponding node in the cloned tree.\n\n# Approach\nWe use a recur... | 2 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
Python Simple 2 approaches - Recursion(3 liner) and Morris | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | I have implemented two approaches for this problem.\n1. #### Recursive Preorder \nThe recursive approach is easier to read and more concise (3 liner). The algorithm is quite straightforward as the second tree in which we need to find the `target` is cloned:\n1. Start a preoder traversal for both the trees simulataneous... | 28 | Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.
The `cloned` tree is a **copy of** the `original` tree.
Return _a reference to the same node_ in the `cloned` tree.
**Note** that you are **not allowed** to change any of the two trees or the `target` node a... | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
Python Simple 2 approaches - Recursion(3 liner) and Morris | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | I have implemented two approaches for this problem.\n1. #### Recursive Preorder \nThe recursive approach is easier to read and more concise (3 liner). The algorithm is quite straightforward as the second tree in which we need to find the `target` is cloned:\n1. Start a preoder traversal for both the trees simulataneous... | 28 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
Python/JS/Java/C++ O(n) by DFS or BFS [w/ Hint] | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 1 | 1 | ---\n**Hint**:\n\nDescription says cloned tree is a full copy of original one.\nIn addtion, it also guarantees target node is selected from original tree.\n\nThat is, the **topology** for both cloned tree and original tree **is the same**.\n\nTherefore, we can develop a paired DFS or BFS traversal algorithm to locate t... | 41 | Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.
The `cloned` tree is a **copy of** the `original` tree.
Return _a reference to the same node_ in the `cloned` tree.
**Note** that you are **not allowed** to change any of the two trees or the `target` node a... | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
Python/JS/Java/C++ O(n) by DFS or BFS [w/ Hint] | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 1 | 1 | ---\n**Hint**:\n\nDescription says cloned tree is a full copy of original one.\nIn addtion, it also guarantees target node is selected from original tree.\n\nThat is, the **topology** for both cloned tree and original tree **is the same**.\n\nTherefore, we can develop a paired DFS or BFS traversal algorithm to locate t... | 41 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
Best Python Solution for Beginners | Simple Recursion | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | \n# Code\n```\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n if not original:\n return original\n else:\n if original == target:\n return cloned\n else:\n left = self.getTar... | 1 | Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.
The `cloned` tree is a **copy of** the `original` tree.
Return _a reference to the same node_ in the `cloned` tree.
**Note** that you are **not allowed** to change any of the two trees or the `target` node a... | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
Best Python Solution for Beginners | Simple Recursion | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | \n# Code\n```\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n if not original:\n return original\n else:\n if original == target:\n return cloned\n else:\n left = self.getTar... | 1 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.