title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
✅ Python Solution || DP || Aditya Verma Approach||Bottom Up | shortest-common-supersequence | 0 | 1 | PLEASE UPVOTE if you like \uD83D\uDE01 If you have any question, feel free to ask.\n# Intuition\nUse Longest Common Subsequence to generated matrix and then matrix to get result string\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Complexity\n- Time complexity: O(N*M) + O(N+M)\n<!-- Add your... | 8 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
✅ Python Solution || DP || Aditya Verma Approach||Bottom Up | shortest-common-supersequence | 0 | 1 | PLEASE UPVOTE if you like \uD83D\uDE01 If you have any question, feel free to ask.\n# Intuition\nUse Longest Common Subsequence to generated matrix and then matrix to get result string\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Complexity\n- Time complexity: O(N*M) + O(N+M)\n<!-- Add your... | 8 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
Hard made Easy Python solution LCS Easy to Understand | shortest-common-supersequence | 0 | 1 | ```\nclass Solution:\n def LCS(self,s,t):\n m=len(s)\n n=len(t)\n dp=[[0 for i in range(n+1)]for j in range(m+1)]\n for i in range(m+1):\n dp[i][0]=0\n for j in range(n+1):\n dp[0][j]=0\n for i in range(1,m+1):\n for j in range(1,n+1):\n ... | 2 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Hard made Easy Python solution LCS Easy to Understand | shortest-common-supersequence | 0 | 1 | ```\nclass Solution:\n def LCS(self,s,t):\n m=len(s)\n n=len(t)\n dp=[[0 for i in range(n+1)]for j in range(m+1)]\n for i in range(m+1):\n dp[i][0]=0\n for j in range(n+1):\n dp[0][j]=0\n for i in range(1,m+1):\n for j in range(1,n+1):\n ... | 2 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
Python3 || Concise || Recursion + Memoization | shortest-common-supersequence | 0 | 1 | ```\n\nfrom functools import lru_cache\n\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n \n @lru_cache(maxsize= 8000)\n def helper(first: str, second: str):\n \n if not first and not second:\n return ""\n \n ... | 2 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Python3 || Concise || Recursion + Memoization | shortest-common-supersequence | 0 | 1 | ```\n\nfrom functools import lru_cache\n\nclass Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n \n @lru_cache(maxsize= 8000)\n def helper(first: str, second: str):\n \n if not first and not second:\n return ""\n \n ... | 2 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
Python simple solution O(n) linear time | statistics-from-a-large-sample | 0 | 1 | # Code\n```\nclass Solution:\n def sampleStats(self, count: List[int]) -> List[float]:\n def get_minimum():\n for i in range(len(count)):\n if count[i] > 0:\n return i\n\n def get_maximum():\n for i in reversed(range(len(count))):\n ... | 1 | You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
Python simple solution O(n) linear time | statistics-from-a-large-sample | 0 | 1 | # Code\n```\nclass Solution:\n def sampleStats(self, count: List[int]) -> List[float]:\n def get_minimum():\n for i in range(len(count)):\n if count[i] > 0:\n return i\n\n def get_maximum():\n for i in reversed(range(len(count))):\n ... | 1 | Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.
Return the maximum possible number of ones that the matrix `M` can have.
**Example 1:**
**Input:** width = 3, height = ... | The hard part is the median. Write a helper function which finds the k-th element from the sample. |
Easy to reason about, uses std library to good effect | statistics-from-a-large-sample | 0 | 1 | # Code\n```\nclass Solution:\n def sampleStats(self, count: list[int]) -> list[float]:\n counts = +Counter(dict(enumerate(count)))\n n = counts.total()\n\n _min = next(iter(counts.keys()))\n _max = next(reversed(counts.keys()))\n _mean = sum(map(lambda t: operator.mul(*t), counts.i... | 0 | You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
Easy to reason about, uses std library to good effect | statistics-from-a-large-sample | 0 | 1 | # Code\n```\nclass Solution:\n def sampleStats(self, count: list[int]) -> list[float]:\n counts = +Counter(dict(enumerate(count)))\n n = counts.total()\n\n _min = next(iter(counts.keys()))\n _max = next(reversed(counts.keys()))\n _mean = sum(map(lambda t: operator.mul(*t), counts.i... | 0 | Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.
Return the maximum possible number of ones that the matrix `M` can have.
**Example 1:**
**Input:** width = 3, height = ... | The hard part is the median. Write a helper function which finds the k-th element from the sample. |
✅ Python Solution | Little slow but understandable | statistics-from-a-large-sample | 0 | 1 | \n\n# Code\n```\nimport collections\nclass Solution:\n def sampleStats(self, count: List[int]) -> List[float]:\n totalNumbers = 0\n totalSum = 0\n maxFreq = -1\n maxFreqElem = -1\n minElem = -1\n maxElem = -1\n hashMap = collections.defaultdict(int)\n\n for i, ... | 0 | You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
✅ Python Solution | Little slow but understandable | statistics-from-a-large-sample | 0 | 1 | \n\n# Code\n```\nimport collections\nclass Solution:\n def sampleStats(self, count: List[int]) -> List[float]:\n totalNumbers = 0\n totalSum = 0\n maxFreq = -1\n maxFreqElem = -1\n minElem = -1\n maxElem = -1\n hashMap = collections.defaultdict(int)\n\n for i, ... | 0 | Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.
Return the maximum possible number of ones that the matrix `M` can have.
**Example 1:**
**Input:** width = 3, height = ... | The hard part is the median. Write a helper function which finds the k-th element from the sample. |
Python solution with mean calculation using left and right pointers | statistics-from-a-large-sample | 0 | 1 | The max, min, and mean calculations are fairly straightforward. \n\nMedian is a little more complicated. I\'m sure there\'s a more elegant way to approach this, but I\'m using left and right pointers for the beginning and end of *count*. I decrement the number at both ends of the array, until one or both of the numb... | 0 | You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
Python solution with mean calculation using left and right pointers | statistics-from-a-large-sample | 0 | 1 | The max, min, and mean calculations are fairly straightforward. \n\nMedian is a little more complicated. I\'m sure there\'s a more elegant way to approach this, but I\'m using left and right pointers for the beginning and end of *count*. I decrement the number at both ends of the array, until one or both of the numb... | 0 | Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.
Return the maximum possible number of ones that the matrix `M` can have.
**Example 1:**
**Input:** width = 3, height = ... | The hard part is the median. Write a helper function which finds the k-th element from the sample. |
Simple easy for beginners using hasmap beats 85 % !!!! | statistics-from-a-large-sample | 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 large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
Simple easy for beginners using hasmap beats 85 % !!!! | statistics-from-a-large-sample | 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 | Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.
Return the maximum possible number of ones that the matrix `M` can have.
**Example 1:**
**Input:** width = 3, height = ... | The hard part is the median. Write a helper function which finds the k-th element from the sample. |
Python 3 solution | statistics-from-a-large-sample | 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 large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
Python 3 solution | statistics-from-a-large-sample | 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 | Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.
Return the maximum possible number of ones that the matrix `M` can have.
**Example 1:**
**Input:** width = 3, height = ... | The hard part is the median. Write a helper function which finds the k-th element from the sample. |
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9% | statistics-from-a-large-sample | 0 | 1 | \n# Code\n```\nclass Solution:\n def sampleStats(self, count):\n n = sum(count)\n mi = next(i for i in range(256) if count[i]) * 1.0\n ma = next(i for i in range(255, -1, -1) if count[i]) * 1.0\n mean = sum(i * v for i, v in enumerate(count)) * 1.0 / n\n mode = count.index(max(coun... | 0 | You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9% | statistics-from-a-large-sample | 0 | 1 | \n# Code\n```\nclass Solution:\n def sampleStats(self, count):\n n = sum(count)\n mi = next(i for i in range(256) if count[i]) * 1.0\n ma = next(i for i in range(255, -1, -1) if count[i]) * 1.0\n mean = sum(i * v for i, v in enumerate(count)) * 1.0 / n\n mode = count.index(max(coun... | 0 | Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.
Return the maximum possible number of ones that the matrix `M` can have.
**Example 1:**
**Input:** width = 3, height = ... | The hard part is the median. Write a helper function which finds the k-th element from the sample. |
O(n) solution with code explanation | car-pooling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this question First thing that comes to my mind is that we just have to answer how many passengers currently we have. So, at every station some passengers are picked up and some may dropped off. To record this number we can use a... | 1 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
O(n) solution with code explanation | car-pooling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this question First thing that comes to my mind is that we just have to answer how many passengers currently we have. So, at every station some passengers are picked up and some may dropped off. To record this number we can use a... | 1 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
[Python] Solution with prefix sum - very easy to understand. | car-pooling | 0 | 1 | # Code\n```\nclass Solution:\n def carPooling(self, trips, capacity: int) -> bool: \n n = len(trips)\n prefix = [0]*(1001)\n left = 1e9\n right = 0\n for tpl in trips:\n prefix[tpl[1]] += tpl[0]\n prefix[tpl[2]] -= tpl[0]\n left = min(left, tpl[1])... | 1 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
[Python] Solution with prefix sum - very easy to understand. | car-pooling | 0 | 1 | # Code\n```\nclass Solution:\n def carPooling(self, trips, capacity: int) -> bool: \n n = len(trips)\n prefix = [0]*(1001)\n left = 1e9\n right = 0\n for tpl in trips:\n prefix[tpl[1]] += tpl[0]\n prefix[tpl[2]] -= tpl[0]\n left = min(left, tpl[1])... | 1 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
[Python] The algorithm that was not mentioned in the tags (with comments and complexity analysis) | car-pooling | 0 | 1 | # Intuition\nAfter I had read the problem it reminded me about Scanline Algorithm. \nThat usually is used in geometry problems. For example, "How many segments belongs to the point", "The number of intersecting segments" and many more.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n... | 6 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
[Python] The algorithm that was not mentioned in the tags (with comments and complexity analysis) | car-pooling | 0 | 1 | # Intuition\nAfter I had read the problem it reminded me about Scanline Algorithm. \nThat usually is used in geometry problems. For example, "How many segments belongs to the point", "The number of intersecting segments" and many more.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n... | 6 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
🔥 [Python3] Beginner friendly, short, using Heap, with comments. | car-pooling | 0 | 1 | ```\nclass Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n minHeap = []\n for trip in trips:\n # using for \'to\' negative value will help us fristly drop of all passangers in current point\n # and only than pick up others passanger at this point... | 8 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
🔥 [Python3] Beginner friendly, short, using Heap, with comments. | car-pooling | 0 | 1 | ```\nclass Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n minHeap = []\n for trip in trips:\n # using for \'to\' negative value will help us fristly drop of all passangers in current point\n # and only than pick up others passanger at this point... | 8 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
linear time most efficeint | car-pooling | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n # O(N) accoriding to input restrictions\n passChange = [0]*1001\n for t in trips:\n numPass,start,end = t\n passChange[start] += numPass\n passChange[end] -=... | 2 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
linear time most efficeint | car-pooling | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n # O(N) accoriding to input restrictions\n passChange = [0]*1001\n for t in trips:\n numPass,start,end = t\n passChange[start] += numPass\n passChange[end] -=... | 2 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
❤ [Python3] STRAIGHTFORWARD (✿◠‿◠), Explained | car-pooling | 0 | 1 | The idea is to create a list `path` with the length of 1000 (from the constraints) and fill it with the number of passengers that will be in the car at the location represented by the index of the list. For example: `path[4] = 30` means that at the 4th kilometer of the path there will be 30 passengers in the car. If at... | 12 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
❤ [Python3] STRAIGHTFORWARD (✿◠‿◠), Explained | car-pooling | 0 | 1 | The idea is to create a list `path` with the length of 1000 (from the constraints) and fill it with the number of passengers that will be in the car at the location represented by the index of the list. For example: `path[4] = 30` means that at the 4th kilometer of the path there will be 30 passengers in the car. If at... | 12 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
Two python solutions with and without min heap. Time: O(nlogn) Space: O(n) | car-pooling | 0 | 1 | # Option 1: without heap\n\n## Intuition\n\nEach interval has two events: first when interval starts then pople hop on the car and the second when interval ends and people hop off the car.\n\n## Approach\n\nThe intervals list of length N can be transformed to an hopOnOff list where each interval will involve a hopOn ev... | 1 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Two python solutions with and without min heap. Time: O(nlogn) Space: O(n) | car-pooling | 0 | 1 | # Option 1: without heap\n\n## Intuition\n\nEach interval has two events: first when interval starts then pople hop on the car and the second when interval ends and people hop off the car.\n\n## Approach\n\nThe intervals list of length N can be transformed to an hopOnOff list where each interval will involve a hopOn ev... | 1 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
⬆️✅🔥 100% | 0ms | easy | explained | faster | proof 🔥⬆️✅ | car-pooling | 1 | 1 | # Upvote pls\n<!-- Describe your first thoughts on how to solve this problem. -->\nadd passenget at start and remove at the end of the stop.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n.
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
⬆️✅🔥 100% | 0ms | easy | explained | faster | proof 🔥⬆️✅ | car-pooling | 1 | 1 | # Upvote pls\n<!-- Describe your first thoughts on how to solve this problem. -->\nadd passenget at start and remove at the end of the stop.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
Python O(N) Very simple to understand | car-pooling | 0 | 1 | We do lazy propagation. We mark the passanger changes first. We calculate exact passanger counts at the end once.\nWe do a optimization #1. If at any point count is larger than capacity, we return immediately False. \n```py\nclass Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n ... | 2 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Python O(N) Very simple to understand | car-pooling | 0 | 1 | We do lazy propagation. We mark the passanger changes first. We calculate exact passanger counts at the end once.\nWe do a optimization #1. If at any point count is larger than capacity, we return immediately False. \n```py\nclass Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n ... | 2 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance betw... | Sort the pickup and dropoff events by location, then process them in order. |
Sidha-Saadha Solution ! | find-in-mountain-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary Search\n# Approach\nFind the peak element using binasry search.\nApply binary search on left half of peak element.\nIf item found then return index.\nApply binary search on right half of peak element.\nIf item found then return ind... | 4 | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length ... | null |
Sidha-Saadha Solution ! | find-in-mountain-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary Search\n# Approach\nFind the peak element using binasry search.\nApply binary search on left half of peak element.\nIf item found then return index.\nApply binary search on right half of peak element.\nIf item found then return ind... | 4 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**... | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak... |
Python3 Solution | find-in-mountain-array | 0 | 1 | \n```\n# """\n# This is MountainArray\'s API interface.\n# You should not implement it, or speculate about its implementation\n# """\n#class MountainArray:\n# def get(self, index: int) -> int:\n# def length(self) -> int:\n\nclass Solution:\n def findInMountainArray(self, target: int, mountain_arr: \'MountainAr... | 2 | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length ... | null |
Python3 Solution | find-in-mountain-array | 0 | 1 | \n```\n# """\n# This is MountainArray\'s API interface.\n# You should not implement it, or speculate about its implementation\n# """\n#class MountainArray:\n# def get(self, index: int) -> int:\n# def length(self) -> int:\n\nclass Solution:\n def findInMountainArray(self, target: int, mountain_arr: \'MountainAr... | 2 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**... | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak... |
🚀 100% || Binary Search || Explained Intuition 🚀 | find-in-mountain-array | 1 | 1 | # Porblem Description\nThe problem requires **finding** the **minimum** index in a `mountain array` where a given `target` is located. \n\n- A mountain array is defined as an array that satisfies the conditions:\n - The array has a length **greater** than or **equal** to `3`.\n - There exists an index `i` `(0 < i... | 120 | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length ... | null |
🚀 100% || Binary Search || Explained Intuition 🚀 | find-in-mountain-array | 1 | 1 | # Porblem Description\nThe problem requires **finding** the **minimum** index in a `mountain array` where a given `target` is located. \n\n- A mountain array is defined as an array that satisfies the conditions:\n - The array has a length **greater** than or **equal** to `3`.\n - There exists an index `i` `(0 < i... | 120 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**... | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak... |
Easy Solution || Beginner Friendly || Beats 90% || Line by Line Explanation || | find-in-mountain-array | 0 | 1 | # Intuition\n\nThe problem involves finding a target value within a MountainArray. The MountainArray is a special type of array that increases up to a certain point and then decreases. The task is to determine the index at which the target value is located within the MountainArray.\n\n**Let\'s try to solve this problem... | 21 | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length ... | null |
Easy Solution || Beginner Friendly || Beats 90% || Line by Line Explanation || | find-in-mountain-array | 0 | 1 | # Intuition\n\nThe problem involves finding a target value within a MountainArray. The MountainArray is a special type of array that increases up to a certain point and then decreases. The task is to determine the index at which the target value is located within the MountainArray.\n\n**Let\'s try to solve this problem... | 21 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**... | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak... |
first find the peak then do binary search on both sides | find-in-mountain-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:\nO(logN)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n# """\n# This is MountainArray\'s API interface.\n# You should not implement i... | 1 | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length ... | null |
first find the peak then do binary search on both sides | find-in-mountain-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:\nO(logN)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n# """\n# This is MountainArray\'s API interface.\n# You should not implement i... | 1 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**... | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak... |
Easy Python3 Solution with explanation | find-in-mountain-array | 0 | 1 | # Intuition\nThe array is sorted in ascending order upto an index which I call as a peak index and from the peak index the array is sorted in descending order.\n\nBinary search not just once, but thrice with different intents:\n\n1. Find the peak element in the mountain array\n2. Find the target in the left half of the... | 1 | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length ... | null |
Easy Python3 Solution with explanation | find-in-mountain-array | 0 | 1 | # Intuition\nThe array is sorted in ascending order upto an index which I call as a peak index and from the peak index the array is sorted in descending order.\n\nBinary search not just once, but thrice with different intents:\n\n1. Find the peak element in the mountain array\n2. Find the target in the left half of the... | 1 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**... | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak... |
[Python3] Concise iterative solution using stack | brace-expansion-ii | 0 | 1 | Use stack for "{" and "}" just like in calculator.\nMaintain two lists:\n1. the previous list before ","\n2. the current list that is still growing\n\nWhen seeing an "alphabet", grow the second list by corss multiplying. So that [a]\\*b will become "ab", [a,c]\\*b will become ["ab", "cb"]\nWhen seeing "," it means the ... | 104 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
Python3 Stack Solution | brace-expansion-ii | 0 | 1 | ```\nclass Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n stack, union, product = [],[],[\'\']\n for c in expression:\n if c.isalpha():\n product = [r + c for r in product]\n elif c == \'{\':\n stack.append(union)\n ... | 21 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
Python3: Recursive Parser Pattern | brace-expansion-ii | 0 | 1 | # Intuition\n\nI have a hard time understanding and following the various stack-of-lists solutions, and I suspect your interviewers will have a hard time following them too.\n\nInstead, I prefer the parser pattern:\n* we break the input into the kinds of things we need to parse\n* each `parseThing` method takes the ind... | 0 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
Python Clear and Concise, Faster than 73% | Explained | brace-expansion-ii | 0 | 1 | # Intuition\nInitially this may sound as a very overwhelming problem. It has so much unplesant stuff like string expression parsing and full powerset generation. Even the definition sounds vague. But if you spend some time trying to understand the input - it is pretty straighforward.\n\nHere are some of the key takeawa... | 0 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
Python | Beats 96% | Recursion | brace-expansion-ii | 0 | 1 | # Code\n```\nclass Parser:\n def __init__(self, input):\n self.input = input\n self.i = 0\n\n def parse_expr(self):\n if self.input[self.i] == \'{\':\n ret = set()\n self.i += 1\n\n while self.i < len(self.input) and self.input[self.i] != \'}\':\n ... | 0 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
Python3 beats 90% short solution | brace-expansion-ii | 0 | 1 | # Code\n```\nclass Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n groups = [[]]\n level = 0\n for i, c in enumerate(expression):\n if c == \'{\':\n if level == 0:\n start = i+1\n level += 1\n elif c =... | 0 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
Python Easy Solution | distribute-candies-to-people | 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 | We distribute some number of `candies`, to a row of **`n = num_people`** people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person.
Then, we go back to the start of the row, giving `n + 1` candies to the first person, ... | For the minimum: We can always do it in at most 2 moves, by moving one stone next to another, then the third stone next to the other two. When can we do it in 1 move? 0 moves?
For the maximum: Every move, the maximum position minus the minimum position must decrease by at least 1. |
Easy Approach | distribute-candies-to-people | 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 | We distribute some number of `candies`, to a row of **`n = num_people`** people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person.
Then, we go back to the start of the row, giving `n + 1` candies to the first person, ... | For the minimum: We can always do it in at most 2 moves, by moving one stone next to another, then the third stone next to the other two. When can we do it in 1 move? 0 moves?
For the maximum: Every move, the maximum position minus the minimum position must decrease by at least 1. |
py3 sol | distribute-candies-to-people | 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 | We distribute some number of `candies`, to a row of **`n = num_people`** people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person.
Then, we go back to the start of the row, giving `n + 1` candies to the first person, ... | For the minimum: We can always do it in at most 2 moves, by moving one stone next to another, then the third stone next to the other two. When can we do it in 1 move? 0 moves?
For the maximum: Every move, the maximum position minus the minimum position must decrease by at least 1. |
Solution | Python | distribute-candies-to-people | 0 | 1 | ```\nclass Solution:\n def distributeCandies(self, candies: int, num_people: int) -> List[int]:\n # create an array of size num_people and initialize it with 0\n list_people = [0] * num_people\n \n # starting value\n index = 1\n \n # iterate until the number of candie... | 12 | We distribute some number of `candies`, to a row of **`n = num_people`** people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person.
Then, we go back to the start of the row, giving `n + 1` candies to the first person, ... | For the minimum: We can always do it in at most 2 moves, by moving one stone next to another, then the third stone next to the other two. When can we do it in 1 move? 0 moves?
For the maximum: Every move, the maximum position minus the minimum position must decrease by at least 1. |
Optimal Python Solution with clear Explanation of Idea | distribute-candies-to-people | 0 | 1 | Please read with patience for clear understanding - Before proceeding, remember that sum of first n natural numbers is n*(n+1)//2\n```\nclass Solution:\n def distributeCandies(self, candies, num_people):\n \'\'\'\n Idea: Round number k (starting from 1)\n -> give away\n (k-1)*n... | 10 | We distribute some number of `candies`, to a row of **`n = num_people`** people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person.
Then, we go back to the start of the row, giving `n + 1` candies to the first person, ... | For the minimum: We can always do it in at most 2 moves, by moving one stone next to another, then the third stone next to the other two. When can we do it in 1 move? 0 moves?
For the maximum: Every move, the maximum position minus the minimum position must decrease by at least 1. |
57 % effective code. | distribute-candies-to-people | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | We distribute some number of `candies`, to a row of **`n = num_people`** people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person.
Then, we go back to the start of the row, giving `n + 1` candies to the first person, ... | For the minimum: We can always do it in at most 2 moves, by moving one stone next to another, then the third stone next to the other two. When can we do it in 1 move? 0 moves?
For the maximum: Every move, the maximum position minus the minimum position must decrease by at least 1. |
Literal Math in Python 3, bottom-up | path-in-zigzag-labelled-binary-tree | 0 | 1 | ```python3\nclass Solution:\n def pathInZigZagTree(self, label: int) -> List[int]:\n def gen():\n nonlocal label\n lv, q = 0, label\n yield label\n while q:\n q, r = divmod(q, 2)\n lv += (q > 0)\n real_parent = label\n ... | 1 | In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the `label` of a node in th... | Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color. |
Complete Binary Tree | Python | path-in-zigzag-labelled-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves finding the path from the root of a zigzag binary tree to a specified node labeled label. In a regular binary tree, finding the parent of any node is straightforward, as it\'s simply the integer division of the node\'... | 1 | In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the `label` of a node in th... | Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color. |
Python Solution || With Explanation || Easy to Understand | path-in-zigzag-labelled-binary-tree | 0 | 1 | * How many levels will be there if n=14? The ans is 3 (level 0,level 1, level 2 and level3)\n* How many levels will be there if n=16? The ans is 4.\n* The number of levels in this binary tree will be [log2(n)] where [x] represents floor value. [3.99] = 3\n* The levels in this tree are odd levels and even levels all odd... | 1 | In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the `label` of a node in th... | Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color. |
Simple Python Solution | path-in-zigzag-labelled-binary-tree | 0 | 1 | # Intuition\nFirst Calculate at which level the target value will appear and then \ncalculate the path backword. \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 co... | 1 | In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the `label` of a node in th... | Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color. |
68% TC and 72% SC easy python solution | path-in-zigzag-labelled-binary-tree | 0 | 1 | ```\ndef pathInZigZagTree(self, label: int) -> List[int]:\n\tans = [label]\n\twhile(label != 1):\n\t\tpar1 = label//2\n\t\tx = int(log(par1, 2))\n\t\tdiff = par1 - 2**x\n\t\tlabel = 2**(x+1)-1 - diff\n\t\tans.append(label)\n\treturn ans[::-1]\n``` | 1 | In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the `label` of a node in th... | Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color. |
Bit masking | path-in-zigzag-labelled-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe parents of zig-zag tree and the original version are mutually exclusive to a factor.\n\nEx: The parent of 23 in the non zig-zag fashion is 23//2 - > 11\nin the zigzag version, it is 15 - 11 + 8 = 12 (15 -> higher bound in powers of ... | 0 | In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the `label` of a node in th... | Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color. |
Simple Python Solution | path-in-zigzag-labelled-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)$$ --... | 0 | In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the `label` of a node in th... | Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color. |
Python3 with explanation | path-in-zigzag-labelled-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo find a path in a zigzag binary tree, we need to understand the alternating pattern of levels. This involves converting the given label to a regular binary tree label, then tracing back to the root.\n\n\n# Approach\n<!-- Describe your a... | 0 | In an infinite binary tree where every node has two children, the nodes are labelled in row order.
In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
Given the `label` of a node in th... | Use a DFS to find every square in the component. Then for each square, color it if it has a neighbor that is outside the grid or a different color. |
Python 3 | DP | Explanation | filling-bookcase-shelves | 0 | 1 | ### Explanation\n- `dp[i]`: Minimum height sum for the first `i` books\n- Given the `i`th book, we just need to decide whether \n\t- It\'s gonna be on its own row, or\n\t- Append to some previous row\n- We can find out above with a nested loop `O(N*N)`\n- Time: `O(N*N)`\n- Space: `O(N)`\n### Implementation\n```\nclass ... | 12 | You are given an array `books` where `books[i] = [thicknessi, heighti]` indicates the thickness and height of the `ith` book. You are also given an integer `shelfWidth`.
We want to place these books in order onto bookcase shelves that have a total width `shelfWidth`.
We choose some of the books to place on this shelf... | Think dynamic programming. Given an oracle dp(i,j) that tells us how many lines A[i:], B[j:] [the sequence A[i], A[i+1], ... and B[j], B[j+1], ...] are uncrossed, can we write this as a recursion? |
Python 3 | DP | Explanation | filling-bookcase-shelves | 0 | 1 | ### Explanation\n- `dp[i]`: Minimum height sum for the first `i` books\n- Given the `i`th book, we just need to decide whether \n\t- It\'s gonna be on its own row, or\n\t- Append to some previous row\n- We can find out above with a nested loop `O(N*N)`\n- Time: `O(N*N)`\n- Space: `O(N)`\n### Implementation\n```\nclass ... | 12 | You have some apples and a basket that can carry up to `5000` units of weight.
Given an integer array `weight` where `weight[i]` is the weight of the `ith` apple, return _the maximum number of apples you can put in the basket_.
**Example 1:**
**Input:** weight = \[100,200,150,1000\]
**Output:** 4
**Explanation:** Al... | Use dynamic programming: dp(i) will be the answer to the problem for books[i:]. |
PYTHON SOL | EXPLAINED WITH PICTURE | RECURSION + MEMO | | filling-bookcase-shelves | 0 | 1 | # EXPLANATION\n```\nWe have 2 choices for each book\n1. Try to put the book on the same row \n2. Make a new row for the book\n\nWe select the choice that leads to minimum height\n\nSo our recursion cases are clear , now the termination will be when no books are left\n\nRemember in memoization we always memoize the vari... | 6 | You are given an array `books` where `books[i] = [thicknessi, heighti]` indicates the thickness and height of the `ith` book. You are also given an integer `shelfWidth`.
We want to place these books in order onto bookcase shelves that have a total width `shelfWidth`.
We choose some of the books to place on this shelf... | Think dynamic programming. Given an oracle dp(i,j) that tells us how many lines A[i:], B[j:] [the sequence A[i], A[i+1], ... and B[j], B[j+1], ...] are uncrossed, can we write this as a recursion? |
PYTHON SOL | EXPLAINED WITH PICTURE | RECURSION + MEMO | | filling-bookcase-shelves | 0 | 1 | # EXPLANATION\n```\nWe have 2 choices for each book\n1. Try to put the book on the same row \n2. Make a new row for the book\n\nWe select the choice that leads to minimum height\n\nSo our recursion cases are clear , now the termination will be when no books are left\n\nRemember in memoization we always memoize the vari... | 6 | You have some apples and a basket that can carry up to `5000` units of weight.
Given an integer array `weight` where `weight[i]` is the weight of the `ith` apple, return _the maximum number of apples you can put in the basket_.
**Example 1:**
**Input:** weight = \[100,200,150,1000\]
**Output:** 4
**Explanation:** Al... | Use dynamic programming: dp(i) will be the answer to the problem for books[i:]. |
1d DP easy solution python3 C++ | filling-bookcase-shelves | 0 | 1 | **Update**\n\n**Ask yourself, how many ways are there to place the i_th book? If you can answer it, then you can solve this problem easily.**\n\nI think this problem is really fantastic! Initially I used DFS which ETL very quickly due to time complexity of O(2**n). Here is my intuition. First of all, it is using DP met... | 4 | You are given an array `books` where `books[i] = [thicknessi, heighti]` indicates the thickness and height of the `ith` book. You are also given an integer `shelfWidth`.
We want to place these books in order onto bookcase shelves that have a total width `shelfWidth`.
We choose some of the books to place on this shelf... | Think dynamic programming. Given an oracle dp(i,j) that tells us how many lines A[i:], B[j:] [the sequence A[i], A[i+1], ... and B[j], B[j+1], ...] are uncrossed, can we write this as a recursion? |
1d DP easy solution python3 C++ | filling-bookcase-shelves | 0 | 1 | **Update**\n\n**Ask yourself, how many ways are there to place the i_th book? If you can answer it, then you can solve this problem easily.**\n\nI think this problem is really fantastic! Initially I used DFS which ETL very quickly due to time complexity of O(2**n). Here is my intuition. First of all, it is using DP met... | 4 | You have some apples and a basket that can carry up to `5000` units of weight.
Given an integer array `weight` where `weight[i]` is the weight of the `ith` apple, return _the maximum number of apples you can put in the basket_.
**Example 1:**
**Input:** weight = \[100,200,150,1000\]
**Output:** 4
**Explanation:** Al... | Use dynamic programming: dp(i) will be the answer to the problem for books[i:]. |
Python Solution (beats 99%) | filling-bookcase-shelves | 0 | 1 | \n\n# Approach\nThe idea is to use a dp array where `dp[i]` represents the minimum height required to place the first `i` books. We update the `dp` array iteratively, considering... | 3 | You are given an array `books` where `books[i] = [thicknessi, heighti]` indicates the thickness and height of the `ith` book. You are also given an integer `shelfWidth`.
We want to place these books in order onto bookcase shelves that have a total width `shelfWidth`.
We choose some of the books to place on this shelf... | Think dynamic programming. Given an oracle dp(i,j) that tells us how many lines A[i:], B[j:] [the sequence A[i], A[i+1], ... and B[j], B[j+1], ...] are uncrossed, can we write this as a recursion? |
Python Solution (beats 99%) | filling-bookcase-shelves | 0 | 1 | \n\n# Approach\nThe idea is to use a dp array where `dp[i]` represents the minimum height required to place the first `i` books. We update the `dp` array iteratively, considering... | 3 | You have some apples and a basket that can carry up to `5000` units of weight.
Given an integer array `weight` where `weight[i]` is the weight of the `ith` apple, return _the maximum number of apples you can put in the basket_.
**Example 1:**
**Input:** weight = \[100,200,150,1000\]
**Output:** 4
**Explanation:** Al... | Use dynamic programming: dp(i) will be the answer to the problem for books[i:]. |
⬆️✅🔥 100% | 0MS | DP +1D | 5 LINER | EXPLAINED | PROOF 🔥⬆️✅ | filling-bookcase-shelves | 1 | 1 | # UPVOTE pls\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n# Tack the thickness & revist the dp array having min height.\n\n that tells us how many lines A[i:], B[j:] [the sequence A[i], A[i+1], ... and B[j], B[j+1], ...] are uncrossed, can we write this as a recursion? |
⬆️✅🔥 100% | 0MS | DP +1D | 5 LINER | EXPLAINED | PROOF 🔥⬆️✅ | filling-bookcase-shelves | 1 | 1 | # UPVOTE pls\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n# Tack the thickness & revist the dp array having min height.\n\n will be the answer to the problem for books[i:]. |
[Python] Iterative O(n) Solution | parsing-a-boolean-expression | 0 | 1 | ```\nclass Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n logics = []\n stack = []\n \n def cal(tmp, top, op):\n if op == \'!\':\n tmp = \'t\' if tmp == \'f\' else \'f\'\n elif op == \'&\':\n tmp = \'t\' if (tmp == \'t\'... | 1 | A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the logical NOT** of the inner expression `subExpr`.
* `'&(subExpr1, subExpr2... | If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have? |
[Python] Iterative O(n) Solution | parsing-a-boolean-expression | 0 | 1 | ```\nclass Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n logics = []\n stack = []\n \n def cal(tmp, top, op):\n if op == \'!\':\n tmp = \'t\' if tmp == \'f\' else \'f\'\n elif op == \'&\':\n tmp = \'t\' if (tmp == \'t\'... | 1 | In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps ... | Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not". |
[Python][Stack]Easy to understand using stack Python (beats 88.89% runtime in python3) | parsing-a-boolean-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* After operator is always (expr1, expr2, ...).\n* You can solve every operator(\'f\', \'t\', ....).\n* Therefore you must solve expr => \'t\' or \'f\'.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* Using stack... | 1 | A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the logical NOT** of the inner expression `subExpr`.
* `'&(subExpr1, subExpr2... | If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have? |
[Python][Stack]Easy to understand using stack Python (beats 88.89% runtime in python3) | parsing-a-boolean-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* After operator is always (expr1, expr2, ...).\n* You can solve every operator(\'f\', \'t\', ....).\n* Therefore you must solve expr => \'t\' or \'f\'.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* Using stack... | 1 | In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps ... | Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not". |
Python super easy solution || Easy to Understand || Override the property || Very Easy | parsing-a-boolean-expression | 0 | 1 | ```\nclass Solution:\n \n def oro(self,*args):\n ans = False\n for elm in args:\n ans|=elm\n return ans\n \n def ando(self,*args):\n ans = True\n for elm in args:\n ans&=elm\n return ans\n \n def noto(self,args):\n return not args\... | 2 | A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the logical NOT** of the inner expression `subExpr`.
* `'&(subExpr1, subExpr2... | If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have? |
Python super easy solution || Easy to Understand || Override the property || Very Easy | parsing-a-boolean-expression | 0 | 1 | ```\nclass Solution:\n \n def oro(self,*args):\n ans = False\n for elm in args:\n ans|=elm\n return ans\n \n def ando(self,*args):\n ans = True\n for elm in args:\n ans&=elm\n return ans\n \n def noto(self,args):\n return not args\... | 2 | In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps ... | Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not". |
One pass with stack, 97% speed | parsing-a-boolean-expression | 0 | 1 | \n```\nclass Solution:\n operands = {"!", "&", "|", "t", "f"}\n values = {"t", "f"}\n\n def parseBoolExpr(self, expression: str) -> bool:\n stack = []\n for c in expression:\n ... | 5 | A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the logical NOT** of the inner expression `subExpr`.
* `'&(subExpr1, subExpr2... | If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have? |
One pass with stack, 97% speed | parsing-a-boolean-expression | 0 | 1 | \n```\nclass Solution:\n operands = {"!", "&", "|", "t", "f"}\n values = {"t", "f"}\n\n def parseBoolExpr(self, expression: str) -> bool:\n stack = []\n for c in expression:\n ... | 5 | In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps ... | Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not". |
Python3: Relatively Simple Stack-Based Parser | parsing-a-boolean-expression | 0 | 1 | # Intuition\n\nUsually I use a recursive parsing pattern, but often I see different solutions involving a stack. So I thought I\'d give one a shot.\n\nAnd, as it turns out, it turns out to be pretty straightforward.\n\nFirst I thought about what we\'d do recursively:\n* if we see a literal \'t\' of \'f\', take it as-is... | 0 | A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the logical NOT** of the inner expression `subExpr`.
* `'&(subExpr1, subExpr2... | If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have? |
Python3: Relatively Simple Stack-Based Parser | parsing-a-boolean-expression | 0 | 1 | # Intuition\n\nUsually I use a recursive parsing pattern, but often I see different solutions involving a stack. So I thought I\'d give one a shot.\n\nAnd, as it turns out, it turns out to be pretty straightforward.\n\nFirst I thought about what we\'d do recursively:\n* if we see a literal \'t\' of \'f\', take it as-is... | 0 | In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps ... | Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not". |
python super easy too understand recursion + stack counter | parsing-a-boolean-expression | 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 **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the logical NOT** of the inner expression `subExpr`.
* `'&(subExpr1, subExpr2... | If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have? |
python super easy too understand recursion + stack counter | parsing-a-boolean-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps ... | Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not". |
✅Beginner Solution✅(Python) (Using Two Stacks) | parsing-a-boolean-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Using two stacks. One for storing the last sign encountered and another for storing the values.\n- If value then push into \'stack\'\n- If opening bracket, then push into \'stack\'\n- If closing bracket, pop the values(fro... | 0 | A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the logical NOT** of the inner expression `subExpr`.
* `'&(subExpr1, subExpr2... | If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have? |
✅Beginner Solution✅(Python) (Using Two Stacks) | parsing-a-boolean-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Using two stacks. One for storing the last sign encountered and another for storing the values.\n- If value then push into \'stack\'\n- If opening bracket, then push into \'stack\'\n- If closing bracket, pop the values(fro... | 0 | In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps ... | Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not". |
Python solution with two stacks - easy to understand | parsing-a-boolean-expression | 0 | 1 | # Intuition\nWe use two stacks - one for data (`data`) and one for operations (`op`).\n\nWe scan the input from left to right.\n\nThe `t` and `f` in the input appends `True` and `False` to the `data` stack.\n\nThe `!`, `&` , `|` in the inputs appends to the `op` stack.\n\nThe `)` character in the input pops a single op... | 0 | A **boolean expression** is an expression that evaluates to either `true` or `false`. It can be in one of the following shapes:
* `'t'` that evaluates to `true`.
* `'f'` that evaluates to `false`.
* `'!(subExpr)'` that evaluates to **the logical NOT** of the inner expression `subExpr`.
* `'&(subExpr1, subExpr2... | If we become stuck, there's either a loop around the source or around the target. If there is a loop around say, the source, what is the maximum number of squares it can have? |
Python solution with two stacks - easy to understand | parsing-a-boolean-expression | 0 | 1 | # Intuition\nWe use two stacks - one for data (`data`) and one for operations (`op`).\n\nWe scan the input from left to right.\n\nThe `t` and `f` in the input appends `True` and `False` to the `data` stack.\n\nThe `!`, `&` , `|` in the inputs appends to the `op` stack.\n\nThe `)` character in the input pops a single op... | 0 | In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.
A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return _the minimum number of steps ... | Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not". |
Beginner-friendly || Simple solution with TypeScript / Python3 | defanging-an-ip-address | 0 | 1 | # Approach\n1. split `address` into dots, and join to string back again with `[.]` delimeter\n\n# Complexity\n- Time complexity: **O(N)**\n\n- Space complexity: **O(1)**\n\n# Code in Python3\n```\nclass Solution:\n def defangIPaddr(self, address: str) -> str:\n return \'[.]\'.join(address.split(\'.\'))\n```\n... | 1 | Given a valid (IPv4) IP `address`, return a defanged version of that IP address.
A _defanged IP address_ replaces every period `". "` with `"[.] "`.
**Example 1:**
**Input:** address = "1.1.1.1"
**Output:** "1\[.\]1\[.\]1\[.\]1"
**Example 2:**
**Input:** address = "255.100.50.0"
**Output:** "255\[.\]100\[.\]50\[.\... | Let's find for every user separately the websites he visited. Consider all possible 3-sequences, find the number of distinct users who visited each of them. How to check if some user visited some 3-sequence ? Store for every user all the 3-sequence he visited. |
EASY PYTHON SOLUTION || DEFANGING IP ADDRESS || O(n) SOLUTION | defanging-an-ip-address | 0 | 1 | Let\'s break it down:\n\nImagine you\'re reading a book (the input string), and you want to make a new version of the book where every time you see a period (\'.\'), you replace it with \'[.]\'. \n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\... | 1 | Given a valid (IPv4) IP `address`, return a defanged version of that IP address.
A _defanged IP address_ replaces every period `". "` with `"[.] "`.
**Example 1:**
**Input:** address = "1.1.1.1"
**Output:** "1\[.\]1\[.\]1\[.\]1"
**Example 2:**
**Input:** address = "255.100.50.0"
**Output:** "255\[.\]100\[.\]50\[.\... | Let's find for every user separately the websites he visited. Consider all possible 3-sequences, find the number of distinct users who visited each of them. How to check if some user visited some 3-sequence ? Store for every user all the 3-sequence he visited. |
Easy Python Solution to Defang IP Address | defanging-an-ip-address | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe should replace every period (`.`) in a given IPv4 address with `[.]`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can return a copy of the given address with all occurrences of substring **old** (`.`) rep... | 2 | Given a valid (IPv4) IP `address`, return a defanged version of that IP address.
A _defanged IP address_ replaces every period `". "` with `"[.] "`.
**Example 1:**
**Input:** address = "1.1.1.1"
**Output:** "1\[.\]1\[.\]1\[.\]1"
**Example 2:**
**Input:** address = "255.100.50.0"
**Output:** "255\[.\]100\[.\]50\[.\... | Let's find for every user separately the websites he visited. Consider all possible 3-sequences, find the number of distinct users who visited each of them. How to check if some user visited some 3-sequence ? Store for every user all the 3-sequence he visited. |
Simple PYTHON code using if-else statement | defanging-an-ip-address | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\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 valid (IPv4) IP `address`, return a defanged version of that IP address.
A _defanged IP address_ replaces every period `". "` with `"[.] "`.
**Example 1:**
**Input:** address = "1.1.1.1"
**Output:** "1\[.\]1\[.\]1\[.\]1"
**Example 2:**
**Input:** address = "255.100.50.0"
**Output:** "255\[.\]100\[.\]50\[.\... | Let's find for every user separately the websites he visited. Consider all possible 3-sequences, find the number of distinct users who visited each of them. How to check if some user visited some 3-sequence ? Store for every user all the 3-sequence he visited. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.