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 |
|---|---|---|---|---|---|---|---|
Tried 2 methods to solve...Using algorithm and without using algorithm | valid-arrangement-of-pairs | 0 | 1 | ## Code 1 (TLE)\n\nTried out the concept in this question [332. Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/description/) to solve this problem. But got TLE although it did pass some testcases.\n\n```\nclass Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[in... | 0 | You are given a **0-indexed** 2D integer array `pairs` where `pairs[i] = [starti, endi]`. An arrangement of `pairs` is **valid** if for every index `i` where `1 <= i < pairs.length`, we have `endi-1 == starti`.
Return _**any** valid arrangement of_ `pairs`.
**Note:** The inputs will be generated such that there exist... | null |
[Python3] Eulerian path explanation | valid-arrangement-of-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a pretty standard eulerian path problem. If you haven\'t solved this type of problem, I recommend just googling that to get a gist of the idea. It is also very similar to leetcode #332.\n\n# Approach\n<!-- Describe your approach t... | 0 | You are given a **0-indexed** 2D integer array `pairs` where `pairs[i] = [starti, endi]`. An arrangement of `pairs` is **valid** if for every index `i` where `1 <= i < pairs.length`, we have `endi-1 == starti`.
Return _**any** valid arrangement of_ `pairs`.
**Note:** The inputs will be generated such that there exist... | null |
98.18/98.18 % in Both speed and memory | valid-arrangement-of-pairs | 0 | 1 | # Approach\n**Graph\nDepth-First Search\nEulerian Circuit\nRecursion\nHash Table\nQueue\nGreedy**\n\n# Code\n```\nfrom array import array\nclass Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n graph = defaultdict(lambda: array(\'I\'))\n degree = defaultdict(int)\n ... | 0 | You are given a **0-indexed** 2D integer array `pairs` where `pairs[i] = [starti, endi]`. An arrangement of `pairs` is **valid** if for every index `i` where `1 <= i < pairs.length`, we have `endi-1 == starti`.
Return _**any** valid arrangement of_ `pairs`.
**Note:** The inputs will be generated such that there exist... | null |
Solution using Dijkstra O(PlogP) | valid-arrangement-of-pairs | 0 | 1 | I did not know of Hierholzer so came up with another approach. It is less efficient but kinda funky and no solutions here have described it yet.\n\n# Intuition\n\nTLDR: Always pick the longest route to get to some end vertex that you\'ve chosen.\n\nWe can represent the pairs as a graph, and we want to neatly travel eac... | 0 | You are given a **0-indexed** 2D integer array `pairs` where `pairs[i] = [starti, endi]`. An arrangement of `pairs` is **valid** if for every index `i` where `1 <= i < pairs.length`, we have `endi-1 == starti`.
Return _**any** valid arrangement of_ `pairs`.
**Note:** The inputs will be generated such that there exist... | null |
[Java/Python 3] From O(n * logn) to average O(n) w/ brief explanation and analysis. | find-subsequence-of-length-k-with-the-largest-sum | 1 | 1 | **Method 1: Sort**\n\n*Sort the whole array*\n1. Combine each index with its corresponding value to create a 2-d array;\n2. Sort the 2-d array reversely by value, then copy the largest k ones;\n3. Sort the largest k ones by index, then return the corresponding values by index order.\n\n```java\n public int[] maxSubs... | 59 | You are given an integer array `nums` and an integer `k`. You want to find a **subsequence** of `nums` of length `k` that has the **largest** sum.
Return _**any** such subsequence as an integer array of length_ `k`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements w... | Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word. |
One liner code very easy | find-subsequence-of-length-k-with-the-largest-sum | 0 | 1 | # Code\n```\nclass Solution:\n def maxSubsequence(self, arr: List[int], k: int) -> List[int]:\n return [j[1] for j in sorted(sorted(enumerate(arr),reverse=True,key=lambda x:x[1])[:k],key=lambda x:x[0])]\n \n``` | 1 | You are given an integer array `nums` and an integer `k`. You want to find a **subsequence** of `nums` of length `k` that has the **largest** sum.
Return _**any** such subsequence as an integer array of length_ `k`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements w... | Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word. |
Concise Python solution | find-subsequence-of-length-k-with-the-largest-sum | 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)$$ --... | 8 | You are given an integer array `nums` and an integer `k`. You want to find a **subsequence** of `nums` of length `k` that has the **largest** sum.
Return _**any** such subsequence as an integer array of length_ `k`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements w... | Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word. |
Python Simple Solution | 100% Time | find-subsequence-of-length-k-with-the-largest-sum | 0 | 1 | ## Code:\n```\nclass Solution:\n def maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n tuple_heap = [] # Stores (value, index) as min heap\n for i, val in enumerate(nums):\n if len(tuple_heap) == k:\n heappushpop(tuple_heap, (val, i)) # To prevent size of heap grow... | 14 | You are given an integer array `nums` and an integer `k`. You want to find a **subsequence** of `nums` of length `k` that has the **largest** sum.
Return _**any** such subsequence as an integer array of length_ `k`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements w... | Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word. |
[Python3] Prefix Sum - Simple Solution | find-good-days-to-rob-the-bank | 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... | 1 | You and a gang of thieves are planning on robbing a bank. You are given a **0-indexed** integer array `security`, where `security[i]` is the number of guards on duty on the `ith` day. The days are numbered starting from `0`. You are also given an integer `time`.
The `ith` day is a good day to rob the bank if:
* The... | Try to minimize each element by swapping bits with any of the elements after it. If you swap out all the 1s in some element, this will lead to a product of zero. |
[Python3] prefix & suffix | find-good-days-to-rob-the-bank | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/b553623546e2799477b8bca6b5c89f22c83a4d08) for solutions of weekly 67. \n\n```\nclass Solution:\n def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:\n suffix = [0]*len(security)\n for i in range(len(secur... | 6 | You and a gang of thieves are planning on robbing a bank. You are given a **0-indexed** integer array `security`, where `security[i]` is the number of guards on duty on the `ith` day. The days are numbered starting from `0`. You are also given an integer `time`.
The `ith` day is a good day to rob the bank if:
* The... | Try to minimize each element by swapping bits with any of the elements after it. If you swap out all the 1s in some element, this will lead to a product of zero. |
✅ 🔥 Python3 || ⚡easy solution | detonate-the-maximum-bombs | 0 | 1 | # Code\n```\nfrom typing import List\nimport collections\n\nclass Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n n2nxt = collections.defaultdict(set)\n lb = len(bombs)\n\n for i in range(lb): # i is the source\n xi, yi, ri = bombs[i]\n\n for j in... | 1 | You are given a list of bombs. The **range** of a bomb is defined as the area where its effect can be felt. This area is in the shape of a **circle** with the center as the location of the bomb.
The bombs are represented by a **0-indexed** 2D integer array `bombs` where `bombs[i] = [xi, yi, ri]`. `xi` and `yi` denote ... | What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem? |
EASY PYTHON SOLUTION USING BFS TRAVERSAL | detonate-the-maximum-bombs | 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^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity he... | 1 | You are given a list of bombs. The **range** of a bomb is defined as the area where its effect can be felt. This area is in the shape of a **circle** with the center as the location of the bomb.
The bombs are represented by a **0-indexed** 2D integer array `bombs` where `bombs[i] = [xi, yi, ri]`. `xi` and `yi` denote ... | What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem? |
python 3 - dfs | detonate-the-maximum-bombs | 0 | 1 | # Intuition\nCan\'t do DSU for this question because explosion\'s effect should be unidirection. eg. bomb A can affect bomb B doesn\'t implies bomb B can also affect bomb A.\n\nYou can go either DFS/BFS.\n\n# Approach\nDFS\n\n# My mistake\nI chose DSU in the beginning. But later I realized the single direction effect. ... | 1 | You are given a list of bombs. The **range** of a bomb is defined as the area where its effect can be felt. This area is in the shape of a **circle** with the center as the location of the bomb.
The bombs are represented by a **0-indexed** 2D integer array `bombs` where `bombs[i] = [xi, yi, ri]`. `xi` and `yi` denote ... | What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem? |
Python short and clean. DFS. Functional programming. | detonate-the-maximum-bombs | 0 | 1 | # Approach\nTL;DR, Similar to [Editorial Solution](https://leetcode.com/problems/detonate-the-maximum-bombs/editorial/) but shorter and cleaner.\n\n# Complexity\n- Time complexity: $$O(n ^ 3)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\n# Code\n```python\nclass Solution:\n def maximumDetonation(self, bombs: list[list[in... | 2 | You are given a list of bombs. The **range** of a bomb is defined as the area where its effect can be felt. This area is in the shape of a **circle** with the center as the location of the bomb.
The bombs are represented by a **0-indexed** 2D integer array `bombs` where `bombs[i] = [xi, yi, ri]`. `xi` and `yi` denote ... | What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem? |
Python | Two Solutions | sortedContainers and minHeap+maxHeap with Explanation | sequentially-ordinal-rank-tracker | 0 | 1 | First Solution (Using sortedcontainers):\nHere we use SortedList which is implemented using divide & conquer and binary search, sortedlist always maintain the sorted order, so we can just query the ith index nd get the Ithe best location\nMore at: https://github.com/grantjenks/python-sortedcontainers/blob/master/src/so... | 2 | A scenic location is represented by its `name` and attractiveness `score`, where `name` is a **unique** string among all locations and `score` is an integer. Locations can be ranked from the best to the worst. The **higher** the score, the better the location. If the scores of two locations are equal, then the location... | Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i]. |
Python 2 heap easy to understand best solution | sequentially-ordinal-rank-tracker | 0 | 1 | \tclass MinHeapItem:\n\t\tdef __init__(self, name, score):\n\t\t\tself.name = name\n\t\t\tself.score = score\n\t\tdef __lt__(self, other):\n\t\t\treturn self.score < other.score or \\\n\t\t\t\t (self.score == other.score and self.name > other.name)\n\n\tclass MaxHeapItem:\n\t\tdef __init__(self, name, score):\n\t\t\t... | 0 | A scenic location is represented by its `name` and attractiveness `score`, where `name` is a **unique** string among all locations and `score` is an integer. Locations can be ranked from the best to the worst. The **higher** the score, the better the location. If the scores of two locations are equal, then the location... | Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i]. |
[Python3] brute-force | sequentially-ordinal-rank-tracker | 0 | 1 | Kinda cheating for Python3 as `insort` is fast enough for such problems. \n\nPlease check out this [commit](https://github.com/gaosanyong/leetcode/commit/b553623546e2799477b8bca6b5c89f22c83a4d08) for solutions of weekly 67. \n\n```\nclass SORTracker:\n\n def __init__(self):\n self.k = 0 \n self.data = ... | 2 | A scenic location is represented by its `name` and attractiveness `score`, where `name` is a **unique** string among all locations and `score` is an integer. Locations can be ranked from the best to the worst. The **higher** the score, the better the location. If the scores of two locations are equal, then the location... | Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i]. |
SortedList | sequentially-ordinal-rank-tracker | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | A scenic location is represented by its `name` and attractiveness `score`, where `name` is a **unique** string among all locations and `score` is an integer. Locations can be ranked from the best to the worst. The **higher** the score, the better the location. If the scores of two locations are equal, then the location... | Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i]. |
Short Python faster than 80%🔥🔥 SortedList | sequentially-ordinal-rank-tracker | 0 | 1 | ```\nfrom sortedcontainers import SortedList\n\nclass SORTracker:\n\n def __init__(self):\n self.scores = SortedList()\n self.i = 0\n\n\n def add(self, name: str, score: int) -> None:\n self.scores.add((-score, name))\n\n def get(self) -> str:\n self.i += 1\n return self.scor... | 0 | A scenic location is represented by its `name` and attractiveness `score`, where `name` is a **unique** string among all locations and `score` is an integer. Locations can be ranked from the best to the worst. The **higher** the score, the better the location. If the scores of two locations are equal, then the location... | Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i]. |
Simple Python Solution: beats 94.5% | rings-and-rods | 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 | There are `n` rings and each ring is either red, green, or blue. The rings are distributed **across ten rods** labeled from `0` to `9`.
You are given a string `rings` of length `2n` that describes the `n` rings that are placed onto the rods. Every two characters in `rings` forms a **color-position pair** that is used ... | Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through... |
Python simple solution | rings-and-rods | 0 | 1 | ```\nclass Solution:\n def countPoints(self, r: str) -> int:\n ans = 0\n for i in range(10):\n i = str(i)\n if \'R\'+i in r and \'G\'+i in r and \'B\'+i in r:\n ans += 1\n return ans\n``` | 24 | There are `n` rings and each ring is either red, green, or blue. The rings are distributed **across ten rods** labeled from `0` to `9`.
You are given a string `rings` of length `2n` that describes the `n` rings that are placed onto the rods. Every two characters in `rings` forms a **color-position pair** that is used ... | Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through... |
Python Short & Simple | rings-and-rods | 0 | 1 | ```\nclass Solution:\n def countPoints(self, rings: str) -> int:\n count = 0\n for i in range(10):\n c = str(i)\n if "B"+c in rings and "G"+c in rings and "R"+c in rings:\n count += 1\n return count\n \n``` | 3 | There are `n` rings and each ring is either red, green, or blue. The rings are distributed **across ten rods** labeled from `0` to `9`.
You are given a string `rings` of length `2n` that describes the `n` rings that are placed onto the rods. Every two characters in `rings` forms a **color-position pair** that is used ... | Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through... |
PYTHON3 || BEGINNER-FRIENDLY || DICTIONARY | rings-and-rods | 0 | 1 | # PYTHON3 || BEGINNER-FRIENDLY || DICTIONARY\n\n# Code\n```\nclass Solution:\n def countPoints(self, rings: str) -> int:\n count=0\n arr=[]\n for i in range(0,len(rings),2):\n arr.append(rings[i:i+2])\n print(arr)\n\n dicc={}\n\n for j in range(len(arr)):\n ... | 1 | There are `n` rings and each ring is either red, green, or blue. The rings are distributed **across ten rods** labeled from `0` to `9`.
You are given a string `rings` of length `2n` that describes the `n` rings that are placed onto the rods. Every two characters in `rings` forms a **color-position pair** that is used ... | Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through... |
Simplest Python solution using sets | rings-and-rods | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def countPoints(self, rings: str) -> int:\n r,g,b = [],[],[]\n for i in range(len(rings)):\n if rings[i] == "R": r.append(rings[i+1])\n if rings[i] == "G": g.append(rings[i+1])\n if rings[i] == "B": b.append(rings[i+1])\n return... | 3 | There are `n` rings and each ring is either red, green, or blue. The rings are distributed **across ten rods** labeled from `0` to `9`.
You are given a string `rings` of length `2n` that describes the `n` rings that are placed onto the rods. Every two characters in `rings` forms a **color-position pair** that is used ... | Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through... |
Python Stack O(n) Solution with inline explanation | sum-of-subarray-ranges | 0 | 1 | ```python\n\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n n = len(nums)\n \n # the answer will be sum{ Max(subarray) - Min(subarray) } over all possible subarray\n # which decomposes to sum{Max(subarray)} - sum{Min(subarray)} over all possible subarray\n # ... | 45 | You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray.
Return _the **sum of all** subarray ranges of_ `nums`_._
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** n... | How can we use the small constraints to help us solve the problem? How can we traverse the ancestors and descendants of a node? |
[Python3] stack | sum-of-subarray-ranges | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/f57038d6cca9ccb356a137b3af67fba615a067dd) for solutions of weekly 271. \n\n```\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n \n def fn(op): \n """Return min sum (if given gt) or max sum (if ... | 17 | You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray.
Return _the **sum of all** subarray ranges of_ `nums`_._
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** n... | How can we use the small constraints to help us solve the problem? How can we traverse the ancestors and descendants of a node? |
Python3 | Monotonus Stack | O(n) | sum-of-subarray-ranges | 0 | 1 | ```\n"""\nif you are not sure what is monotonous stack go through the concept given in this post:\n\nhttps://leetcode.com/problems/sum-of-subarray-minimums/discuss/178876/stack-solution-with-very-detailed-explanation-step-by-step\n\nhttps://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624268/Reformulate-Proble... | 8 | You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray.
Return _the **sum of all** subarray ranges of_ `nums`_._
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** n... | How can we use the small constraints to help us solve the problem? How can we traverse the ancestors and descendants of a node? |
Python 3, two monotonic stacks, O(n) time, O(n) space | sum-of-subarray-ranges | 0 | 1 | ```\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n res = 0\n min_stack, max_stack = [], []\n n = len(nums)\n nums.append(0)\n for i, num in enumerate(nums):\n while min_stack and (i == n or num < nums[min_stack[-1]]):\n top = min_st... | 11 | You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray.
Return _the **sum of all** subarray ranges of_ `nums`_._
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** n... | How can we use the small constraints to help us solve the problem? How can we traverse the ancestors and descendants of a node? |
Python3 || Monotonic Stack || O(n) time complexity | sum-of-subarray-ranges | 0 | 1 | ```\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n mon = monotonicStack()\n \n # for each element, check in how many sub-arrays arrays, it can be max\n # find the prev and next greater element\n\n # for each element, check in how many sub-arrays arrays, it c... | 5 | You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray.
Return _the **sum of all** subarray ranges of_ `nums`_._
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** n... | How can we use the small constraints to help us solve the problem? How can we traverse the ancestors and descendants of a node? |
[Python] Monostack explanation O(n) time and space | sum-of-subarray-ranges | 0 | 1 | \'\'\'\nThere are alot of good answers that explains max_sum and min_sum initiative \nHere I will try to explain how I analyzed and solved this monotonic stack problem\n\nAssuming you are familiar with monotonic stack but don\'t know how to write the "while" part that pops the stack\n\nLet\'s go with an example:\n\nnum... | 6 | You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray.
Return _the **sum of all** subarray ranges of_ `nums`_._
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** n... | How can we use the small constraints to help us solve the problem? How can we traverse the ancestors and descendants of a node? |
[Python3] 2 pointers | watering-plants-ii | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/f57038d6cca9ccb356a137b3af67fba615a067dd) for solutions of weekly 271. \n\n```\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n ans = 0 \n lo, hi = 0, len(plants)-1\n ... | 8 | Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in ... | Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums. |
python beats 98% | watering-plants-ii | 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 | Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in ... | Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums. |
CLEAN PYTHON SOLUTION || WITH COMMENTS | watering-plants-ii | 0 | 1 | \n# Code\n```\nclass Solution:\n def minimumRefill(self, plant: List[int], capacityA: int, capacityB: int) -> int:\n refill = 0\n canA = capacityA\n canB = capacityB\n left = 0\n right = len(plant) - 1\n while left <= right:\n if left == right: # when pointing to ... | 0 | Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in ... | Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums. |
python3 - simple | watering-plants-ii | 0 | 1 | # Intuition\neither it\'s an even count of plants \n\nor an odd count => Alice and Bob will meet at one plant \n\nin either case, half of the plants will be served by one of them.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(len(plants)), time to iter... | 0 | Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in ... | Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums. |
many conditionals | watering-plants-ii | 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 | Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in ... | Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums. |
Python easy sol. | watering-plants-ii | 0 | 1 | # Code\n```\nclass Solution:\n def minimumRefill(self, plants: List[int], ca: int, cb: int) -> int:\n a,b=0,len(plants)-1\n alice,bob=ca,cb\n res=0\n while a<=b:\n if a==b:\n if alice>=bob:\n if alice<plants[a]:\n res+=1\... | 0 | Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in ... | Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums. |
Python, 2 pointers with explanation | watering-plants-ii | 0 | 1 | # Intuition\nWe know that both Alice and Bob start from both ends and water them at the same time. The only tricky part about this problem is to determine the order of when both alice and bob reach the same plant.\n\n# Approach\nWe generate a separate array to contain True and False values, This is used to check which ... | 0 | Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in ... | Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums. |
Easy Python Solution beats 91.30% run time | watering-plants-ii | 0 | 1 | # Approach\nCompute if refill is needed at each plant[i].\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n a = 0\n b = len(plants)-1\n r = 0\n ca, c... | 0 | Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in ... | Consider only the numbers which have a good prime factorization. Use brute force to find all possible good subsets and then calculate its frequency in nums. |
Python (Simple Prefix Sum) | maximum-fruits-harvested-after-at-most-k-steps | 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 | Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array `fruits` where `fruits[i] = [positioni, amounti]` depicts `amounti` fruits at the position `positioni`. `fruits` is already **sorted** by `positioni` in **ascending order**, and each `positioni` is **unique**.
You are also g... | Find the minimum and maximum in one iteration. Let them be mn and mx. Try all the numbers in the range [1, mn] and check the largest number which divides both of them. |
Python3 code. | maximum-fruits-harvested-after-at-most-k-steps | 0 | 1 | # **Bold**# 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. $... | 0 | Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array `fruits` where `fruits[i] = [positioni, amounti]` depicts `amounti` fruits at the position `positioni`. `fruits` is already **sorted** by `positioni` in **ascending order**, and each `positioni` is **unique**.
You are also g... | Find the minimum and maximum in one iteration. Let them be mn and mx. Try all the numbers in the range [1, mn] and check the largest number which divides both of them. |
Simple python solution | find-first-palindromic-string-in-the-array | 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 array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.
A string is **palindromic** if it reads the same forward and backward.
**Example 1:**
**Input:** words = \[ "abc ", "car ", "ada ", "racecar ", "cool "\]
**Output... | The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much. |
4 liner code beats 99.83% in Runtime | find-first-palindromic-string-in-the-array | 0 | 1 | # Proof:\n\nsee my image\n\n# Code\n```\nclass Solution:\n def firstPalindrome(self, words: List[str]) -> str:\n for i in words:\n if i==i[::-1]:\n return i\n re... | 1 | Given an array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.
A string is **palindromic** if it reads the same forward and backward.
**Example 1:**
**Input:** words = \[ "abc ", "car ", "ada ", "racecar ", "cool "\]
**Output... | The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much. |
Python Easy Solution || word==word[::-1] | find-first-palindromic-string-in-the-array | 0 | 1 | # Code\n```\nclass Solution:\n def firstPalindrome(self, words: List[str]) -> str:\n for i in words:\n if i==i[::-1]:\n return i\n return ""\n``` | 3 | Given an array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.
A string is **palindromic** if it reads the same forward and backward.
**Example 1:**
**Input:** words = \[ "abc ", "car ", "ada ", "racecar ", "cool "\]
**Output... | The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much. |
Python Solution ||O(N) | find-first-palindromic-string-in-the-array | 0 | 1 | Time Complexcity O(N)\nSpace Complexcity O(1)\n```\nclass Solution:\n def firstPalindrome(self, words: List[str]) -> str:\n for word in words:\n print(word)\n if word==word[::-1]:\n return word\n return ""\n \n``` | 1 | Given an array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.
A string is **palindromic** if it reads the same forward and backward.
**Example 1:**
**Input:** words = \[ "abc ", "car ", "ada ", "racecar ", "cool "\]
**Output... | The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much. |
simple sol in python | find-first-palindromic-string-in-the-array | 0 | 1 | \n```\nclass Solution:\n def firstPalindrome(self, words: List[str]) -> str:\n for i in words:\n if(i[::-1]==i):\n return i\n break\n else:\n return ""\n``` | 1 | Given an array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.
A string is **palindromic** if it reads the same forward and backward.
**Example 1:**
**Input:** words = \[ "abc ", "car ", "ada ", "racecar ", "cool "\]
**Output... | The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much. |
Python | Reverse String | find-first-palindromic-string-in-the-array | 0 | 1 | \n def firstPalindrome(self, words: List[str]) -> str:\n for w in words:\n if w == w[::-1]:\n return w\n return "" | 1 | Given an array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.
A string is **palindromic** if it reads the same forward and backward.
**Example 1:**
**Input:** words = \[ "abc ", "car ", "ada ", "racecar ", "cool "\]
**Output... | The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much. |
Python - Clean and Simple + One-Liner! | find-first-palindromic-string-in-the-array | 0 | 1 | **Solution**:\n```\nclass Solution:\n def firstPalindrome(self, words):\n for word in words:\n if word == word[::-1]: return word\n return ""\n```\n\n**Solution with custom palindrome checker (Two-Pointer approach)**:\n```\nclass Solution:\n def firstPalindrome(self, words):\n for ... | 3 | Given an array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.
A string is **palindromic** if it reads the same forward and backward.
**Example 1:**
**Input:** words = \[ "abc ", "car ", "ada ", "racecar ", "cool "\]
**Output... | The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much. |
8 Line Python Code || One Pass | adding-spaces-to-a-string | 0 | 1 | # Intuition\nMaintain a lastAdded upto pointer -> this pointer will store the last index we have added in res of s.\nIterate in spaces and add chars from last seen index till i and then add space & update last idx added upto.\nreturn res.\n\n# Code\n```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int... | 2 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
[Java/Python 3] Traverse input. | adding-spaces-to-a-string | 1 | 1 | Reversely traverse input.\n\n```java\n public String addSpaces(String s, int[] spaces) {\n StringBuilder ans = new StringBuilder();\n for (int i = s.length() - 1, j = spaces.length - 1; i >= 0; --i) {\n ans.append(s.charAt(i));\n if (j >= 0 && spaces[j] == i) {\n --... | 15 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
[Python] Split and Join to the rescue. From TLE to Accepted ! Straightforward | adding-spaces-to-a-string | 0 | 1 | Just do what the question said i.e \nAdd spaces at that index \n\nIn the first solution i guess due to python\'s way of working with strings we are getting a TLE error\n```\n#TLE SOLUTION\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n\t\tspaces_idx = len(spaces)-1\n\n\t\tdef addString(in... | 8 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
** Python code: Adding Spaces to a String | adding-spaces-to-a-string | 0 | 1 | ```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n arr=[]\n prev=0\n for i in spaces:\n arr.append(s[prev:i])\n prev=i\n arr.append(s[i:])\n return " ".join(arr)\n``` | 6 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
Python simple and clean solution | adding-spaces-to-a-string | 0 | 1 | **Python :**\n\n```\ndef addSpaces(self, s: str, spaces: List[int]) -> str:\n\tres = s[:spaces[0]] + " "\n\n\tfor j in range(1, len(spaces)):\n\t\tres += s[spaces[j- 1]:spaces[j]] + " "\n\n\tres += s[spaces[-1]:] \n\treturn res\n```\n\n**Like it ? please upvote !** | 8 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
Python3 Easy understanding | adding-spaces-to-a-string | 0 | 1 | \n# Code\n```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n a = []\n string = 0\n for i in spaces:\n a.append(s[string:i])\n a.append(" ")\n string = i\n a.append(s[string:])\n return "".join(a)\n``` | 1 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
[Python3] forward & backward | adding-spaces-to-a-string | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/55c6a88797eef9ac745a3dbbff821a2aac735a70) for solutions of weekly 272. \n\n**Approach 1 -- forward**\n```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n ans = []\n j = 0 \n for i, ch in enum... | 5 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
Python Using String Comprehension vs Copying to another string | adding-spaces-to-a-string | 0 | 1 | The basic idea here is to do it inplace using string comprehension (Giving TLE) :\n\n```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n j = 0\n for i in spaces:\n s = s[:i+j]+" "+s[i+j:]\n j += 1\n return s \n```\n\nIt says - \n***66 / 6... | 2 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
Python3 || Simple Solution | adding-spaces-to-a-string | 0 | 1 | # 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 addSpaces(self, s: str, spaces: List[int]) -> str:\n spaces.append(len(s))\n result = ""... | 0 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
Simple Python Solution | adding-spaces-to-a-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to add the space at the given indices. If we directly add it to s, then with each addition, the length of s will change and the spaces position will differ. So, take an empty string and add the part of s and spaces respectively.\n... | 0 | You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.
* For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place sp... | What information do the two largest elements tell us? Can we use recursion to check all possible states? |
Easy approach || O(n) | number-of-smooth-descent-periods-of-a-stock | 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 `prices` representing the daily price history of a stock, where `prices[i]` is the stock price on the `ith` day.
A **smooth descent period** of a stock consists of **one or more contiguous** days such that the price on each day is **lower** than the price on the **preceding day** by **ex... | null |
[Java/Python 3] Time O(n) space O(1) code. | number-of-smooth-descent-periods-of-a-stock | 1 | 1 | For each descent periods ending at `i`, use `cnt` to count the # of the the periods and add to the output variable `ans`.\n```java\n public long getDescentPeriods(int[] prices) {\n long ans = 0;\n int cnt = 0, prev = -1;\n for (int cur : prices) {\n if (prev - cur == 1) {\n ... | 11 | You are given an integer array `prices` representing the daily price history of a stock, where `prices[i]` is the stock price on the `ith` day.
A **smooth descent period** of a stock consists of **one or more contiguous** days such that the price on each day is **lower** than the price on the **preceding day** by **ex... | null |
Little Maths, Little Sliding Window Without DP! | number-of-smooth-descent-periods-of-a-stock | 0 | 1 | In order to solve this problem I would prefer you take a pen and paper and make few testcases of your own.\nDuring that youll find some similarities\nLet me illustrate:\n[3,2,1] - [3,2] , [2,1] , [3,2,1] and singular values\n3+3 = 6\nNow when we have 4 numbers\n[4,3,2,1] \nwhen we take two numbers at once\n[4,3] ,[3,2... | 5 | You are given an integer array `prices` representing the daily price history of a stock, where `prices[i]` is the stock price on the `ith` day.
A **smooth descent period** of a stock consists of **one or more contiguous** days such that the price on each day is **lower** than the price on the **preceding day** by **ex... | null |
[Python3] counting | number-of-smooth-descent-periods-of-a-stock | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/55c6a88797eef9ac745a3dbbff821a2aac735a70) for solutions of weekly 272. \n\n```\nclass Solution:\n def getDescentPeriods(self, prices: List[int]) -> int:\n ans = 0 \n for i, x in enumerate(prices): \n if i == 0 or pr... | 8 | You are given an integer array `prices` representing the daily price history of a stock, where `prices[i]` is the stock price on the `ith` day.
A **smooth descent period** of a stock consists of **one or more contiguous** days such that the price on each day is **lower** than the price on the **preceding day** by **ex... | null |
Python (Simple LIS) | minimum-operations-to-make-the-array-k-increasing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a **0-indexed** array `arr` consisting of `n` positive integers, and a positive integer `k`.
The array `arr` is called **K-increasing** if `arr[i-k] <= arr[i]` holds for every index `i`, where `k <= i <= n-1`.
* For example, `arr = [4, 1, 5, 2, 6, 2]` is K-increasing for `k = 2` because:
* `arr[... | The target will not be found if it is removed from the sequence. When does this occur? If a pivot is to the left of and is greater than the target, then the target will be removed. The same occurs when the pivot is to the right of and is less than the target. Since any element can be chosen as the pivot, for any target... |
[Python3] almost LIS | minimum-operations-to-make-the-array-k-increasing | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/55c6a88797eef9ac745a3dbbff821a2aac735a70) for solutions of weekly 272. \n\n```\nclass Solution:\n def kIncreasing(self, arr: List[int], k: int) -> int:\n \n def fn(sub): \n """Return ops to make sub non-decreasing."... | 2 | You are given a **0-indexed** array `arr` consisting of `n` positive integers, and a positive integer `k`.
The array `arr` is called **K-increasing** if `arr[i-k] <= arr[i]` holds for every index `i`, where `k <= i <= n-1`.
* For example, `arr = [4, 1, 5, 2, 6, 2]` is K-increasing for `k = 2` because:
* `arr[... | The target will not be found if it is removed from the sequence. When does this occur? If a pivot is to the left of and is greater than the target, then the target will be removed. The same occurs when the pivot is to the right of and is less than the target. Since any element can be chosen as the pivot, for any target... |
Python and C++ Solutions | 2D array | maximum-number-of-words-found-in-sentences | 0 | 1 | # Code\n```C++ []\nclass Solution {\npublic:\n int mostWordsFound(vector<string>& sentences) {\n int answer = 1;\n int maxx = 0;\n for (int i = 0; i < sentences.size(); i++){\n for (int j = 0; j < sentences[i].size(); j++){\n if (sentences[i][j] == \' \'){answer += 1; }... | 1 | A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.
You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.
Return _the **maximum number of words** that appear in a single sentence_.
**Example 1:**
**Input:... | Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way. |
2 One-Liner solution | maximum-number-of-words-found-in-sentences | 0 | 1 | # Code\n```\nclass Solution:\n def mostWordsFound(self, sentences: List[str]) -> int:\n return max(len(x.split(" ")) for x in sentences)\n\n```\n# Counting " ", but its less efficient\n```\nclass Solution:\n def mostWordsFound(self, sentences: List[str]) -> int:\n return max(x.count(" ") for x in se... | 1 | A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.
You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.
Return _the **maximum number of words** that appear in a single sentence_.
**Example 1:**
**Input:... | Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way. |
Space-Based Word Count in Python | maximum-number-of-words-found-in-sentences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs included in the problem constraints:\n1. None of the sentences have leading or trailing spaces.\n2. All the words in sentences are separated by a single space.\n\nFrom these constraints, we can conclude that:\n> The more spaces there a... | 2 | A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.
You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.
Return _the **maximum number of words** that appear in a single sentence_.
**Example 1:**
**Input:... | Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way. |
Beginner Friendly! | maximum-number-of-words-found-in-sentences | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def mostWordsFound(self, sentences: List[str]) -> int:\n count = 0\n for i in sentences:\n c = len(i.split())\n if(c > count):\n count = c\n return count\n``` | 2 | A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.
You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.
Return _the **maximum number of words** that appear in a single sentence_.
**Example 1:**
**Input:... | Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way. |
(47 ms runtime) Best for Beginners (--) Simple logic | maximum-number-of-words-found-in-sentences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->My approch is straight forward as words are seperated by spaces count the number of spaces append it to a list and max of that list and add one to it and return it\n\n# Approach\n<!-- Describe your approach to solving the problem. -->Simple... | 2 | A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.
You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.
Return _the **maximum number of words** that appear in a single sentence_.
**Example 1:**
**Input:... | Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way. |
Python3 using enumerate | maximum-number-of-words-found-in-sentences | 0 | 1 | # Intuition\nUsed .split() to separate string \n\n# Approach\nWe know sentences is a list and we have to go through the list thus we need a for loop. We also need a variable to keep track of the length of the strings. Once were going through the loop we need to check the length of every string and compare to our previo... | 0 | A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.
You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.
Return _the **maximum number of words** that appear in a single sentence_.
**Example 1:**
**Input:... | Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way. |
Count Spaces | maximum-number-of-words-found-in-sentences | 1 | 1 | Count spaces in each sentence, and return `max + 1`. The benefit (comparing to a split method) is that we do not create temporary strings.\n\n**Python 3**\n```python\nclass Solution:\n def mostWordsFound(self, ss: List[str]) -> int:\n return max(s.count(" ") for s in ss) + 1\n```\n\n**C++**\n```cpp\nint mostW... | 101 | A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.
You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.
Return _the **maximum number of words** that appear in a single sentence_.
**Example 1:**
**Input:... | Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way. |
Solution of maximum number of words found in sentences problem | maximum-number-of-words-found-in-sentences | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n * m)$$ - as loop takes linear time $$O(n)$$ and split() function takes $$O(m)$$. This is because the method needs to iterate through the entire string to find all occurrences of the delimiter\n\n- Space complexity:\n$$O(1)$$ - as we use extra space for answer equal to a constant\... | 1 | A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.
You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.
Return _the **maximum number of words** that appear in a single sentence_.
**Example 1:**
**Input:... | Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way. |
SIMPLE PYTHON SOLUTION | find-all-possible-recipes-from-given-supplies | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
SIMPLE PYTHON TOPOLOGICAL SORT SOLUTION | find-all-possible-recipes-from-given-supplies | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
[Java/Python 3] Toplogical Sort w/ brief explanation. | find-all-possible-recipes-from-given-supplies | 1 | 1 | **Method 1: Bruteforce**\nRepeated BFS till no any more finding\n\n1. Put all supplies into a HashSet, `seen`, for checking the availability in `O(1)` time;\n2. Put into a Queue all indexes of the recipes;\n3. BFS and put into `seen` all recipes that we currently can create; put back into the Queue if a recipe we curre... | 110 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
DFS | find-all-possible-recipes-from-given-supplies | 0 | 1 | This problem is not complex but "hairy".\n\nSince we only care if a recipe can be made or not (regarless of in which order), we do not need a topological sort. \n\nWe can use a simple DFS; we just need to track `can_make` for each recipe (undefined, yes or no), so that we traverse each node only once.\n\nTo simplify th... | 74 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
[Python3] topological sort (Kahn's algo) | find-all-possible-recipes-from-given-supplies | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/8bba95f803d58a5e571fa13de6635c96f5d1c1ee) for solutions of biweekly 68. \n\n```\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n indeg = defaultdict(in... | 68 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
[Python3] Topological Sort -Simple Solution | find-all-possible-recipes-from-given-supplies | 0 | 1 | # Intuition\nSome Recipe depends on some other Recipe that is cooked before -> Sound very similar to course schedule -> Topological sort\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 *... | 5 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
📌📌 Beginners Friendly || Well-Explained || 94% Faster 🐍 | find-all-possible-recipes-from-given-supplies | 0 | 1 | ## IDEA :\n*Yeahh, This question is little tricky. But when we come to question in which one element is dependent on others element to complete then we have to first think of Graph.*\nHere, All the recipes and supplies ingredients should be made node and Edges `a->b` to be defined as for completion of recipe `b` we s... | 47 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
✅Python Easy Solution with explanation | Beginner Friendly | Kahn's Algorithm 🚀😀👍🏻 | find-all-possible-recipes-from-given-supplies | 0 | 1 | # Approach\nUsing Kahn\'s Algorithm / Topological Sort\n# Video Explanation\nhttps://youtu.be/jsSq5_h-6vE\n\n# Code\n```\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n # indegree = {"bread" : 2}\n indegree = defaultdict... | 4 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
[PYTHON3] BFS -EASY TO UNDERSTAND | find-all-possible-recipes-from-given-supplies | 0 | 1 | ```\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n adj=defaultdict(list)\n ind=defaultdict(int)\n \n for i in range(len(ingredients)):\n for j in range(len(ingredients[i])):\n adj... | 9 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
TOPOLOGICAL | Python Explained | find-all-possible-recipes-from-given-supplies | 0 | 1 | # Intuition\ntreat this problem as one of the standard topological problem finding ancestors.\nWhere if you can create the parent then u can create the child recipe too.\nNow the trick of the problem is to curate the graph.\n`1. Think of it as what can be the parents? The ingredients required to make a recipe.`\n`2. An... | 3 | You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **othe... | The number of unique good subsequences is equal to the number of unique decimal values there are for all possible subsequences. Find the answer at each index based on the previous indexes' answers. |
Left-to-right and right-to-left | check-if-a-parentheses-string-can-be-valid | 1 | 1 | A useful trick (when doing any parentheses validation) is to greedily check balance left-to-right, and then right-to-left.\n- Left-to-right check ensures that we do not have orphan \')\' parentheses.\n- Right-to-left checks for orphan \'(\' parentheses.\n\nWe go left-to-right:\n- Count `wild` (not locked) characters. \... | 207 | A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is valid if **any** of the following conditions is **true**:
* It is `()`.
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid parentheses strings.
* It can be written as `(A)`, where `A` is a v... | Can we check every possible pair? Can we use a nested for loop to solve this problem? |
[Python3, Java, C++] Counting Brackets O(n) | check-if-a-parentheses-string-can-be-valid | 1 | 1 | * We iterate over the string s twice. \n* Count of variable brackets is maintained using `tot`\n* Count of fixed open brackets is maintained using `op`\n* Count of fixed closed brackets is maintained using `cl`\n* In forward iteration we are checking if we have too many fixed closed brackets `)`, this is achieved using... | 120 | A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is valid if **any** of the following conditions is **true**:
* It is `()`.
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid parentheses strings.
* It can be written as `(A)`, where `A` is a v... | Can we check every possible pair? Can we use a nested for loop to solve this problem? |
[Python3] greedy 2-pass | check-if-a-parentheses-string-can-be-valid | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/8bba95f803d58a5e571fa13de6635c96f5d1c1ee) for solutions of biweekly 68. \n\n```\nclass Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n if len(s)&1: return False\n bal = 0\n for ch, lock in zip(s, locked... | 9 | A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is valid if **any** of the following conditions is **true**:
* It is `()`.
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid parentheses strings.
* It can be written as `(A)`, where `A` is a v... | Can we check every possible pair? Can we use a nested for loop to solve this problem? |
✔ Python3 Solution | Clean & Concise | check-if-a-parentheses-string-can-be-valid | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def canBeValid(self, s, locked):\n cmin, cmax = 0, 0\n for i, j in zip(s, locked):\n cmin -= 1 if cmin and (j == \'0\' or i == \')\') else -1\n cmax += 1 if j == \'0\' or i ==... | 3 | A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is valid if **any** of the following conditions is **true**:
* It is `()`.
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid parentheses strings.
* It can be written as `(A)`, where `A` is a v... | Can we check every possible pair? Can we use a nested for loop to solve this problem? |
Python (Simple Maths) | abbreviating-the-product-of-a-range | 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 two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
[Python3] quasi brute-force | abbreviating-the-product-of-a-range | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/8bba95f803d58a5e571fa13de6635c96f5d1c1ee) for solutions of biweekly 68. \n\n```\nclass Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n ans = prefix = suffix = 1\n trailing = 0 \n flag = False \n... | 10 | You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
Simple (5-line) Python solution beats 100% || 5 line solution || beats 100% | abbreviating-the-product-of-a-range | 0 | 1 | \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach: Simple and step by step approach as mentiones in problem description \nstep 1: calculate the product of the given range (left, right)\nrange(left, right+1) will give us a range object or the range which is converted into list by list()... | 1 | You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
Very straightforward completely beginner friendly Python solution | abbreviating-the-product-of-a-range | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFairly easy. Just find the product and convert it to str\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nYou just find the product and convert to string to slice it\n\n# Complexity\n- Time complexity: 51%\n<!-- Add... | 0 | You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
Understandable Python Solution with linear time complexity | abbreviating-the-product-of-a-range | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the above code is to efficiently calculate and represent the product of all integers in the given range in a human-readable format. The product can be very large and contain many trailing zeros, which can make it diff... | 0 | You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
Python, almost brute force | abbreviating-the-product-of-a-range | 0 | 1 | There are 2 steps:\nStep1: Calculate the number of trailing zeros\nStep2: Multiply & Keep track of the first 12 numbers and the last 5 numbers\n\nFor step1, we need to know the number of factors 2 and 5 in [right, left], because 10 = 2 * 5. The minimum of the two will be the number of trailing zeros.\n\nFor step2, If t... | 2 | You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
Non-bruteforce algorithm in Python3 with numpy | abbreviating-the-product-of-a-range | 0 | 1 | As suggested in the hints, the three parts are calculated separately. The precision issue in the Python built-in floating numbers happen, so I use numpy.float128 instead of the built-in floats. \n\n```\nimport numpy\n\nclass Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n log_prod = ... | 0 | You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
Python3 accepted solution (using rstrip) | abbreviating-the-product-of-a-range | 0 | 1 | ```\n class Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n product=1\n for i in range(left,right+1):\n product *= i\n if(len(str(product).rstrip("0"))<=10):\n return str(product).rstrip("0") + "e" + str(len(str(product)) - len(str(product).rstrip(... | 0 | You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
Brute Force Approach Python3 (Accepted) (Commented) | abbreviating-the-product-of-a-range | 0 | 1 | ```\nclass Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n ans = 1 //Initialise the product with 1\n while left <= right: // Start the multiplying numbers in\n ... | 0 | You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.
Since the product may be very large, you will **abbreviate** it following these steps:
1. Count all **trailing** zeros in the product and **remove** them.... | If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be... |
one string solution | a-number-after-a-double-reversal | 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 | **Reversing** an integer means to reverse all its digits.
* For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**.
Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed... | Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer. |
Efficient O(1) check in Python3 | a-number-after-a-double-reversal | 0 | 1 | # Intuition\nHere we have:\n- `num` as an integer\n- our goal is to **double reverse** and check, if reversed version is equal to original `num`\n\n# Approach\n1. simple check for `zero` (**true**) and `num % 10 != 0` \n\n# Complexity\n- Time complexity: **O(1)**\n\n- Space complexity: **O(1)**\n\n# Code\n```\nclass So... | 1 | **Reversing** an integer means to reverse all its digits.
* For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**.
Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed... | Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer. |
string convert and then convert it to integer again; | a-number-after-a-double-reversal | 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 | **Reversing** an integer means to reverse all its digits.
* For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**.
Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed... | Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer. |
Beats 93.42% || A number after a double reversal | a-number-after-a-double-reversal | 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 | **Reversing** an integer means to reverse all its digits.
* For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**.
Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed... | Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer. |
Solution of a number after a double reversal problem | a-number-after-a-double-reversal | 0 | 1 | # Approach\nThere are two options:\n- If the last digit is 0 --> False\n- In another situatiion --> True\n\n# Complexity\n\n- Space complexity:\n$$O(1)$$ - as, no extra space is required.\n\n# Code\n```\nclass Solution:\n def isSameAfterReversals(self, num: int) -> bool:\n if len(str(num)) > 1 and str(num)[-1... | 1 | **Reversing** an integer means to reverse all its digits.
* For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**.
Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed... | Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer. |
A Number After a Double Reversal | a-number-after-a-double-reversal | 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 | **Reversing** an integer means to reverse all its digits.
* For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**.
Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed... | Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.