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 |
|---|---|---|---|---|---|---|---|
[Python3🐍] [DP] [Drawing✍️] [Easy to understand ✌️] Dynamic Programming solution.✨🍻 | form-array-by-concatenating-subarrays-of-another-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\nConsider we have these three arrarys:\n- groups, provided by input.\n- nums, also provided by input.\n- dp, we create it, the meaning is: **in the current position `... | 1 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
[Python3] check group one-by-one | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | \n```\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n i = 0\n for grp in groups: \n for ii in range(i, len(nums)):\n if nums[ii:ii+len(grp)] == grp: \n i = ii + len(grp)\n break \n els... | 33 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
[Python3] check group one-by-one | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | \n```\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n i = 0\n for grp in groups: \n for ii in range(i, len(nums)):\n if nums[ii:ii+len(grp)] == grp: \n i = ii + len(grp)\n break \n els... | 33 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
Easy python solution | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | # Code\n```\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n ln=len(groups)\n idx=0\n for i in groups:\n for j in range(idx,len(nums)):\n if nums[j:j+len(i)]==i:\n idx=j+len(i)\n ln-=1\n ... | 4 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
Easy python solution | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | # Code\n```\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n ln=len(groups)\n idx=0\n for i in groups:\n for j in range(idx,len(nums)):\n if nums[j:j+len(i)]==i:\n idx=j+len(i)\n ln-=1\n ... | 4 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
||faster than 99 percent of python solutions||greedy||sliding window|| | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | **# Intuition**\nImagine laying out the groups like train cars on a track, and trying to find matching segments within the nums train to connect them in order. To ensure disjointness, each connected segment cannot overlap with any other.\n\nStart at the front: We begin searching at the beginning of the nums train.\nMat... | 0 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
||faster than 99 percent of python solutions||greedy||sliding window|| | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | **# Intuition**\nImagine laying out the groups like train cars on a track, and trying to find matching segments within the nums train to connect them in order. To ensure disjointness, each connected segment cannot overlap with any other.\n\nStart at the front: We begin searching at the beginning of the nums train.\nMat... | 0 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
KPM - DP - O(n) - [60%, 55%] | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | # Complexity\n```\nLet n = sum(len(G) forall g in G) and m = len(A).\nTime complexity: O(n + m)\nSpace complexity: O(n)\n```\n\n# Code\n```python\nclass Solution:\n def canChoose(self, G: List[List[int]], A: List[int]) -> bool:\n # Construct Longest-Proper-Suffix array for each group.\n L = []\n ... | 0 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
KPM - DP - O(n) - [60%, 55%] | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | # Complexity\n```\nLet n = sum(len(G) forall g in G) and m = len(A).\nTime complexity: O(n + m)\nSpace complexity: O(n)\n```\n\n# Code\n```python\nclass Solution:\n def canChoose(self, G: List[List[int]], A: List[int]) -> bool:\n # Construct Longest-Proper-Suffix array for each group.\n L = []\n ... | 0 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
Intuitive Sliding Window | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUpon reading the question, it can be seen that a sliding window solution might work as we are dealing with subarrays \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStart by creating a while loop to go through eac... | 0 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
Intuitive Sliding Window | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUpon reading the question, it can be seen that a sliding window solution might work as we are dealing with subarrays \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStart by creating a while loop to go through eac... | 0 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
[Python3] Good enough | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | ``` Python3 []\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n group = 0\n i = len(nums)-len(groups[-1-group])\n while i>=0:\n if nums[i:i+len(groups[-1-group])] == groups[-1-group]:\n if group==len(groups)-1:\n ... | 0 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
[Python3] Good enough | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | ``` Python3 []\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n group = 0\n i = len(nums)-len(groups[-1-group])\n while i>=0:\n if nums[i:i+len(groups[-1-group])] == groups[-1-group]:\n if group==len(groups)-1:\n ... | 0 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
Easy for Beginners | form-array-by-concatenating-subarrays-of-another-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)$$ --... | 0 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
Easy for Beginners | form-array-by-concatenating-subarrays-of-another-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)$$ --... | 0 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
Simple backtracking | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | # Intuition\nI thought it could be linear time until I realized you have to backtrack and can\'t greedily consume the sub-arrays from groups every time. This makes it $$O(n^2)$$.\n\n# Approach\nIterate over nums and compare and consume items from groups. If a non-match is encountered, backtrack to the beginning of the ... | 0 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
Simple backtracking | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | # Intuition\nI thought it could be linear time until I realized you have to backtrack and can\'t greedily consume the sub-arrays from groups every time. This makes it $$O(n^2)$$.\n\n# Approach\nIterate over nums and compare and consume items from groups. If a non-match is encountered, backtrack to the beginning of the ... | 0 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
Python 3 | Greedy, Multi-source BFS | Explanation | map-of-highest-peak | 0 | 1 | ### Explanation\n- Start from *water* nodes and BFS until all heights are found\n- NOTE: You don\'t need to worry about getting a skewed peak (by *skewed*, I mean a height with difference greater than 1 on some neighbors), because it will never be possible\n\t- For example: following situation will never be possible\n\... | 6 | You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells.
* If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell.
* If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell.
You must assign each cell a height in a way that follows these rules:
* The... | Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1. |
Python 3 | Greedy, Multi-source BFS | Explanation | map-of-highest-peak | 0 | 1 | ### Explanation\n- Start from *water* nodes and BFS until all heights are found\n- NOTE: You don\'t need to worry about getting a skewed peak (by *skewed*, I mean a height with difference greater than 1 on some neighbors), because it will never be possible\n\t- For example: following situation will never be possible\n\... | 6 | A string is **good** if there are no repeated characters.
Given a string `s`, return _the number of **good substrings** of length **three** in_ `s`.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A **substring** is a contiguous sequence of characters... | Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources. |
[Python3] bfs | map-of-highest-peak | 0 | 1 | \n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n m, n = len(isWater), len(isWater[0]) # dimensions \n queue = [(i, j) for i in range(m) for j in range(n) if isWater[i][j]]\n \n ht = 0\n ans = [[0]*n for _ in range(m)]\n seen = se... | 7 | You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells.
* If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell.
* If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell.
You must assign each cell a height in a way that follows these rules:
* The... | Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1. |
[Python3] bfs | map-of-highest-peak | 0 | 1 | \n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n m, n = len(isWater), len(isWater[0]) # dimensions \n queue = [(i, j) for i in range(m) for j in range(n) if isWater[i][j]]\n \n ht = 0\n ans = [[0]*n for _ in range(m)]\n seen = se... | 7 | A string is **good** if there are no repeated characters.
Given a string `s`, return _the number of **good substrings** of length **three** in_ `s`.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A **substring** is a contiguous sequence of characters... | Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources. |
📌📌 Greedy || BFS || Well-Explained 🐍 | map-of-highest-peak | 0 | 1 | ## IDEA:\n*Start from water nodes and BFS until all heights are found*\nNOTE: **You don\'t need to worry about height with difference greater than 1 on some neighbors because it will never be possible**\n* For example: following situation will never be possible\n1 1 0\n1 1 2\n2 0 1\n* This is because we are using BFS a... | 4 | You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells.
* If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell.
* If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell.
You must assign each cell a height in a way that follows these rules:
* The... | Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1. |
📌📌 Greedy || BFS || Well-Explained 🐍 | map-of-highest-peak | 0 | 1 | ## IDEA:\n*Start from water nodes and BFS until all heights are found*\nNOTE: **You don\'t need to worry about height with difference greater than 1 on some neighbors because it will never be possible**\n* For example: following situation will never be possible\n1 1 0\n1 1 2\n2 0 1\n* This is because we are using BFS a... | 4 | A string is **good** if there are no repeated characters.
Given a string `s`, return _the number of **good substrings** of length **three** in_ `s`.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A **substring** is a contiguous sequence of characters... | Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources. |
Easy Python Solution | map-of-highest-peak | 0 | 1 | # Code\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n arr = [[-1 for _ in range(len(isWater[0]))] for _ in range(len(isWater))]\n\n coords = []\n\n for i in range(len(isWater)):\n for j in range(len(isWater[i])):\n if isWat... | 0 | You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells.
* If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell.
* If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell.
You must assign each cell a height in a way that follows these rules:
* The... | Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1. |
Easy Python Solution | map-of-highest-peak | 0 | 1 | # Code\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n arr = [[-1 for _ in range(len(isWater[0]))] for _ in range(len(isWater))]\n\n coords = []\n\n for i in range(len(isWater)):\n for j in range(len(isWater[i])):\n if isWat... | 0 | A string is **good** if there are no repeated characters.
Given a string `s`, return _the number of **good substrings** of length **three** in_ `s`.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A **substring** is a contiguous sequence of characters... | Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources. |
python solution | map-of-highest-peak | 0 | 1 | \n# Code\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n q = deque()\n dir=[-1,0,1,0,-1]\n rowsize=len(isWater)\n colsize=len(isWater[0])\n visited=set()\n for i in range(rowsize):\n for j in range(colsize):\n ... | 0 | You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells.
* If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell.
* If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell.
You must assign each cell a height in a way that follows these rules:
* The... | Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1. |
python solution | map-of-highest-peak | 0 | 1 | \n# Code\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n q = deque()\n dir=[-1,0,1,0,-1]\n rowsize=len(isWater)\n colsize=len(isWater[0])\n visited=set()\n for i in range(rowsize):\n for j in range(colsize):\n ... | 0 | A string is **good** if there are no repeated characters.
Given a string `s`, return _the number of **good substrings** of length **three** in_ `s`.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A **substring** is a contiguous sequence of characters... | Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources. |
Just clean code. | map-of-highest-peak | 0 | 1 | The code speaks for itself. The only trick is in initializing the matrix with -= 1 -> turns water into 0 and land into -1 -> we reuse negative number during bfs as "not visited flag".\n\n\n# Code\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n n, m = len(isWater[0... | 0 | You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells.
* If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell.
* If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell.
You must assign each cell a height in a way that follows these rules:
* The... | Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1. |
Just clean code. | map-of-highest-peak | 0 | 1 | The code speaks for itself. The only trick is in initializing the matrix with -= 1 -> turns water into 0 and land into -1 -> we reuse negative number during bfs as "not visited flag".\n\n\n# Code\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n n, m = len(isWater[0... | 0 | A string is **good** if there are no repeated characters.
Given a string `s`, return _the number of **good substrings** of length **three** in_ `s`.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A **substring** is a contiguous sequence of characters... | Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources. |
[Python3] dfs | tree-of-coprimes | 0 | 1 | **Algo**\nThis is a typical DFS problem. However, the amont of nodes can be huge `10^5` but the values only vary from `0` to `50`. Due to this reason, we can organize what have been seen in a value to location mapping to reduce the amount of nodes to check. \n\n**Implementation**\n```\nclass Solution:\n def getCopri... | 10 | There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the **root** of the tree is node `0`.
To represent this tree, you are given an integer array `nums` and a 2D array `edge... | Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence Think of LIS it's kind of close |
BFS of GCD adjacency list | Commented and Explained | 100% memory, upper 80-90 T | tree-of-coprimes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a rather hard problem if you are unfamiliar with BFS and GCD. In this intuition and then in approach, I\'ll lay out a standardized solving approach I used and explain the findings from it as we go. To start any problem, I like to ... | 0 | There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the **root** of the tree is node `0`.
To represent this tree, you are given an integer array `nums` and a 2D array `edge... | Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence Think of LIS it's kind of close |
BFS + NumPy; RT 94% | M 94% | tree-of-coprimes | 0 | 1 | \n# Complexity\n- Time complexity: $O(kn)$, where $k=50$.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(k+n)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```PYTHON\nimport numpy as np\n\nPRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]\n\nclass ... | 0 | There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the **root** of the tree is node `0`.
To represent this tree, you are given an integer array `nums` and a 2D array `edge... | Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence Think of LIS it's kind of close |
Simple DFS | tree-of-coprimes | 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 | There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the **root** of the tree is node `0`.
To represent this tree, you are given an integer array `nums` and a 2D array `edge... | Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence Think of LIS it's kind of close |
Least Runtime-Beats 100% Users! Easy to understand code, with step by step explanation. | merge-strings-alternately | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> The goal is to merge two strings, word1 and word2, in an alternating fashion, starting with word1. If one of the strings is longer than the other, append the remaining characters to the end of the merged string. The key intuition is to ite... | 5 | You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return _the merged string._
**Example 1:**
**Input:** word1 = "abc ", word2 = "pqr "... | Apply the concept of Polymorphism to get a good design Implement the Node class using NumericNode and OperatorNode classes. NumericNode only maintains the value and evaluate returns this value. OperatorNode Maintains the left and right nodes representing the left and right operands, and the evaluate function applies th... |
Least Runtime-Beats 100% Users! Easy to understand code, with step by step explanation. | merge-strings-alternately | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> The goal is to merge two strings, word1 and word2, in an alternating fashion, starting with word1. If one of the strings is longer than the other, append the remaining characters to the end of the merged string. The key intuition is to ite... | 5 | There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student numb... | Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards. |
Easy Python beats 100% time and space | minimum-number-of-operations-to-move-all-balls-to-each-box | 0 | 1 | Similar to **238. Product of Array Except Self** and **42. Trapping Rain Water**.\nFor each index, the cost to move all boxes to it is sum of the cost ```leftCost``` to move all left boxes to it, and the cost ```rightCost``` to move all right boxes to it.\n- ```leftCost``` for all indexes can be calculted using a singl... | 157 | You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball.
In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing ... | Try generating the array. Make sure not to fall in the base case of 0. |
Easy Python beats 100% time and space | minimum-number-of-operations-to-move-all-balls-to-each-box | 0 | 1 | Similar to **238. Product of Array Except Self** and **42. Trapping Rain Water**.\nFor each index, the cost to move all boxes to it is sum of the cost ```leftCost``` to move all left boxes to it, and the cost ```rightCost``` to move all right boxes to it.\n- ```leftCost``` for all indexes can be calculted using a singl... | 157 | A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**.
Given an `m x n` integer `grid`, return _the **size... | If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i]. |
Simple Python3 Solution | minimum-number-of-operations-to-move-all-balls-to-each-box | 0 | 1 | ```\nclass Solution:\n def minOperations(self, boxes: str) -> List[int]:\n arr = []\n \n for i, balls in enumerate(boxes):\n if balls == \'1\':\n arr.append(i)\n \n res = []\n for i in range(len(boxes)):\n tmp = 0\n for index i... | 2 | You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball.
In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing ... | Try generating the array. Make sure not to fall in the base case of 0. |
Simple Python3 Solution | minimum-number-of-operations-to-move-all-balls-to-each-box | 0 | 1 | ```\nclass Solution:\n def minOperations(self, boxes: str) -> List[int]:\n arr = []\n \n for i, balls in enumerate(boxes):\n if balls == \'1\':\n arr.append(i)\n \n res = []\n for i in range(len(boxes)):\n tmp = 0\n for index i... | 2 | A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**.
Given an `m x n` integer `grid`, return _the **size... | If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i]. |
📌📌 96% faster || Greedy Approach || Well-Explained || For-Beginners 🐍 | minimum-number-of-operations-to-move-all-balls-to-each-box | 0 | 1 | ## IDEA :\nHere, we can create prefix and postfix array of size n\\*2 to store the number of ones before (or after) the index and also information of the number of costs required to collect all the ones at previous index.\n**For Example :** \n\'\'\'\n\n\tstring given = " 0 0 1 0 1 1 "\n\... | 7 | You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball.
In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing ... | Try generating the array. Make sure not to fall in the base case of 0. |
📌📌 96% faster || Greedy Approach || Well-Explained || For-Beginners 🐍 | minimum-number-of-operations-to-move-all-balls-to-each-box | 0 | 1 | ## IDEA :\nHere, we can create prefix and postfix array of size n\\*2 to store the number of ones before (or after) the index and also information of the number of costs required to collect all the ones at previous index.\n**For Example :** \n\'\'\'\n\n\tstring given = " 0 0 1 0 1 1 "\n\... | 7 | A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**.
Given an `m x n` integer `grid`, return _the **size... | If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i]. |
𝗪𝗵𝘆 Greedy Failed? From Level Zero | Beginner-Friendly | Fully Explained | Python | C | maximum-score-from-performing-multiplication-operations | 0 | 1 | # \uD83D\uDE0B Greedy!\n\n**Let\'s go Greedy!**\n\nWe have to pick integer `x` from **either end** of array `nums`. And, multiply that with `multipliers[i]`. Thus, let\'s pick larger `x` from either end. \n\n**`5` vs `3`, we will pick 5. Is it correct?** \nNo! On checking constraints `-1000 \u2264 nums[i], multipliers... | 151 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
𝗪𝗵𝘆 Greedy Failed? From Level Zero | Beginner-Friendly | Fully Explained | Python | C | maximum-score-from-performing-multiplication-operations | 0 | 1 | # \uD83D\uDE0B Greedy!\n\n**Let\'s go Greedy!**\n\nWe have to pick integer `x` from **either end** of array `nums`. And, multiply that with `multipliers[i]`. Thus, let\'s pick larger `x` from either end. \n\n**`5` vs `3`, we will pick 5. Is it correct?** \nNo! On checking constraints `-1000 \u2264 nums[i], multipliers... | 151 | You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`.
* For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*... | At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence... |
Solution from Recursion to Space optimization in Python and C++ | maximum-score-from-performing-multiplication-operations | 0 | 1 | **Recursion (TLE)**\n```\nn = len(multipliers)\nm = len(nums)\ndp = [[-1 for i in range(m)] for k in range(n)]\ndef f(ind,i):\n\tif ind==n:\n\t\treturn 0\n\tl = (nums[i]*multipliers[ind])+f(ind+1,i+1)\n\tr = (nums[m-1-(ind-i)]*multipliers[ind])+f(ind+1,i)\n\n\treturn max(l,r)\nreturn f(0,0)\n```\n**Time Complexity: Exp... | 4 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
Solution from Recursion to Space optimization in Python and C++ | maximum-score-from-performing-multiplication-operations | 0 | 1 | **Recursion (TLE)**\n```\nn = len(multipliers)\nm = len(nums)\ndp = [[-1 for i in range(m)] for k in range(n)]\ndef f(ind,i):\n\tif ind==n:\n\t\treturn 0\n\tl = (nums[i]*multipliers[ind])+f(ind+1,i+1)\n\tr = (nums[m-1-(ind-i)]*multipliers[ind])+f(ind+1,i)\n\n\treturn max(l,r)\nreturn f(0,0)\n```\n**Time Complexity: Exp... | 4 | You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`.
* For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*... | At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence... |
Python Solution | Memoization | Tabulation | maximum-score-from-performing-multiplication-operations | 0 | 1 | ```\ndef maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n s=0\n n=len(nums)\n m=len(multipliers)\n \n # Recursion + Memoization : TLE\n # dp=[[-1]*m for i in range(n)]\n# def helper(low, high, j):\n# if j==m:\n# return 0\... | 4 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
Python Solution | Memoization | Tabulation | maximum-score-from-performing-multiplication-operations | 0 | 1 | ```\ndef maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n s=0\n n=len(nums)\n m=len(multipliers)\n \n # Recursion + Memoization : TLE\n # dp=[[-1]*m for i in range(n)]\n# def helper(low, high, j):\n# if j==m:\n# return 0\... | 4 | You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`.
* For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*... | At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence... |
Python Solution From Recursion To Space Optimisation | maximum-score-from-performing-multiplication-operations | 0 | 1 | ***Recursion(TLE):***\n```\nn = len(nums) \nm = len(multipliers)\n```\n```\ndef f(ind,i,j):\n\tif ind == m:\n\t\treturn 0\n\tl = nums[i]*multipliers[ind]+f(ind+1,i+1,j)\n\tr = nums[j]*multipliers[ind]+f(ind+1,i,j-1)\nreturn f(0,0,n-1)\n```\n**Time Complexity:** Exponential\n**Space Complexity:** O(m)\n\n***Memoization(... | 3 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
Python Solution From Recursion To Space Optimisation | maximum-score-from-performing-multiplication-operations | 0 | 1 | ***Recursion(TLE):***\n```\nn = len(nums) \nm = len(multipliers)\n```\n```\ndef f(ind,i,j):\n\tif ind == m:\n\t\treturn 0\n\tl = nums[i]*multipliers[ind]+f(ind+1,i+1,j)\n\tr = nums[j]*multipliers[ind]+f(ind+1,i,j-1)\nreturn f(0,0,n-1)\n```\n**Time Complexity:** Exponential\n**Space Complexity:** O(m)\n\n***Memoization(... | 3 | You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`.
* For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*... | At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence... |
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔98% less memory and faster | maximum-score-from-performing-multiplication-operations | 0 | 1 | ***UPVOTE*** if it is helpful\n``` \nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n dp = [0] * (len(multipliers) + 1)\n for m in range(len(multipliers) - 1, -1, -1):\n pd = [0] * (m + 1)\n for l in range(m, -1, -1):\n pd[... | 2 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔98% less memory and faster | maximum-score-from-performing-multiplication-operations | 0 | 1 | ***UPVOTE*** if it is helpful\n``` \nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n dp = [0] * (len(multipliers) + 1)\n for m in range(len(multipliers) - 1, -1, -1):\n pd = [0] * (m + 1)\n for l in range(m, -1, -1):\n pd[... | 2 | You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`.
* For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*... | At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence... |
[Python3] bottom-up dp | maximum-score-from-performing-multiplication-operations | 0 | 1 | \n```\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n, m = len(nums), len(multipliers)\n dp = [[0]*m for _ in range(m+1)]\n \n for i in reversed(range(m)):\n for j in range(i, m): \n k = i + m - j - 1\n ... | 65 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
[Python3] bottom-up dp | maximum-score-from-performing-multiplication-operations | 0 | 1 | \n```\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n, m = len(nums), len(multipliers)\n dp = [[0]*m for _ in range(m+1)]\n \n for i in reversed(range(m)):\n for j in range(i, m): \n k = i + m - j - 1\n ... | 65 | You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`.
* For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*... | At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence... |
[Python 3] simple DP | maximize-palindrome-length-from-subsequences | 0 | 1 | \tclass Solution:\n\t\tdef longestPalindrome(self, word1: str, word2: str) -> int:\n\t\t\tres=0\n\t\t\tnew_word=word1+word2\n\t\t\tn,mid=len(word1)+len(word2),len(word1)\n\t\t\tdp=[[0]*n for _ in range(n)]\n\t\t\tfor i in range(n):\n\t\t\t\tdp[i][i]=1\n\t\t\tfor l in range(n-2,-1,-1):\n\t\t\t\tfor r in range(l+1,n,1):\... | 1 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
[Python 3] simple DP | maximize-palindrome-length-from-subsequences | 0 | 1 | \tclass Solution:\n\t\tdef longestPalindrome(self, word1: str, word2: str) -> int:\n\t\t\tres=0\n\t\t\tnew_word=word1+word2\n\t\t\tn,mid=len(word1)+len(word2),len(word1)\n\t\t\tdp=[[0]*n for _ in range(n)]\n\t\t\tfor i in range(n):\n\t\t\t\tdp[i][i]=1\n\t\t\tfor l in range(n-2,-1,-1):\n\t\t\t\tfor r in range(l+1,n,1):\... | 1 | You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **a... | Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse... |
[Python3] top-down dp | maximize-palindrome-length-from-subsequences | 0 | 1 | **Algo**\nFind common characters in `word1` and `word2` and use the anchor to find longest palindromic subsequence. \n\n**Implementation**\n```\nclass Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n \n @cache\n def fn(lo, hi):\n """Return length of longest pa... | 15 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
[Python3] top-down dp | maximize-palindrome-length-from-subsequences | 0 | 1 | **Algo**\nFind common characters in `word1` and `word2` and use the anchor to find longest palindromic subsequence. \n\n**Implementation**\n```\nclass Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n \n @cache\n def fn(lo, hi):\n """Return length of longest pa... | 15 | You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **a... | Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse... |
[Python] Dynamic Programming O((m+n)^2) | maximize-palindrome-length-from-subsequences | 0 | 1 | ```\nclass Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n s1 = word1 + word2\n n = len(s1)\n dp = [[0] * n for i in range(n)]\n ans = 0\n for i in range(n-1,-1,-1):\n\t\t# mark every character as a 1 length palindrome\n dp[i][i] = 1\n ... | 5 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
[Python] Dynamic Programming O((m+n)^2) | maximize-palindrome-length-from-subsequences | 0 | 1 | ```\nclass Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n s1 = word1 + word2\n n = len(s1)\n dp = [[0] * n for i in range(n)]\n ans = 0\n for i in range(n-1,-1,-1):\n\t\t# mark every character as a 1 length palindrome\n dp[i][i] = 1\n ... | 5 | You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **a... | Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse... |
DP | maximize-palindrome-length-from-subsequences | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this problem, we can use dynamic programming to find the longest palindrome that can be constructed using subsequences from word1 and word2. We\'ll create a 2D table, dp, where dp[i][j] represents the length of the longest palindrome that can... | 0 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
DP | maximize-palindrome-length-from-subsequences | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this problem, we can use dynamic programming to find the longest palindrome that can be constructed using subsequences from word1 and word2. We\'ll create a 2D table, dp, where dp[i][j] represents the length of the longest palindrome that can... | 0 | You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **a... | Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse... |
Python | O((m+n)**2) | Recursion + Memoization question | maximize-palindrome-length-from-subsequences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O((m+n)**2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g.... | 0 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
Python | O((m+n)**2) | Recursion + Memoization question | maximize-palindrome-length-from-subsequences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O((m+n)**2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g.... | 0 | You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **a... | Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse... |
Python | O(max(m,n)**2) solution | Recursion + Memoization question | maximize-palindrome-length-from-subsequences | 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(3*(max(m,n)**2))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity her... | 0 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
Python | O(max(m,n)**2) solution | Recursion + Memoization question | maximize-palindrome-length-from-subsequences | 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(3*(max(m,n)**2))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity her... | 0 | You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **a... | Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse... |
Solution of count items matching a rule problem | count-items-matching-a-rule | 0 | 1 | # Approach\n- Step one: create table with an index of Each Category\n- Step two: find index of category\n- Step three: count every matches in items list\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - as loop takes linear time\n\n- Space complexity:\n$$O(n)$$ - as we use extra space for rules table\n\n\n# Code\n```\ncl... | 1 | You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` ... | null |
Solution of count items matching a rule problem | count-items-matching-a-rule | 0 | 1 | # Approach\n- Step one: create table with an index of Each Category\n- Step two: find index of category\n- Step three: count every matches in items list\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - as loop takes linear time\n\n- Space complexity:\n$$O(n)$$ - as we use extra space for rules table\n\n\n# Code\n```\ncl... | 1 | A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain.
To obtain `target`, you may apply the following opera... | Iterate on each item, and check if each one matches the rule according to the statement. |
python code in easy | count-items-matching-a-rule | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` ... | null |
python code in easy | count-items-matching-a-rule | 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 | A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain.
To obtain `target`, you may apply the following opera... | Iterate on each item, and check if each one matches the rule according to the statement. |
Python 3 | 2-liner | Explanation | count-items-matching-a-rule | 0 | 1 | ### Explanation\n- Create a dict `{ruleKey: index_of_rulekey}`\n- Filter out items that satisfy the condition\n\n### Implementation\n```\nclass Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n d = {\'type\': 0, \'color\': 1, \'name\': 2}\n return sum(1 ... | 64 | You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` ... | null |
Python 3 | 2-liner | Explanation | count-items-matching-a-rule | 0 | 1 | ### Explanation\n- Create a dict `{ruleKey: index_of_rulekey}`\n- Filter out items that satisfy the condition\n\n### Implementation\n```\nclass Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n d = {\'type\': 0, \'color\': 1, \'name\': 2}\n return sum(1 ... | 64 | A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain.
To obtain `target`, you may apply the following opera... | Iterate on each item, and check if each one matches the rule according to the statement. |
✅ Explained - Simple and Clear Python3 Code✅ | count-items-matching-a-rule | 0 | 1 | # Intuition\nThe problem requires counting the number of items that match a given rule. We are given an array of items, where each item is represented by its type, color, and name. The rule is defined by a ruleKey and a ruleValue. We need to determine if the ruleKey matches the corresponding attribute of each item, and... | 8 | You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` ... | null |
✅ Explained - Simple and Clear Python3 Code✅ | count-items-matching-a-rule | 0 | 1 | # Intuition\nThe problem requires counting the number of items that match a given rule. We are given an array of items, where each item is represented by its type, color, and name. The rule is defined by a ruleKey and a ruleValue. We need to determine if the ruleKey matches the corresponding attribute of each item, and... | 8 | A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain.
To obtain `target`, you may apply the following opera... | Iterate on each item, and check if each one matches the rule according to the statement. |
Python solution using one for loop | count-items-matching-a-rule | 0 | 1 | # Intuition\nI figured I could match the ruleKey to a number which would make it easier to look at a certain index of the inner list. \n\n# Approach\nFirst I created a total variable to return later. Next I tied a number value to the type of value passed in as ruleKey. Then I used a for loop to loop through the list. I... | 0 | You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` ... | null |
Python solution using one for loop | count-items-matching-a-rule | 0 | 1 | # Intuition\nI figured I could match the ruleKey to a number which would make it easier to look at a certain index of the inner list. \n\n# Approach\nFirst I created a total variable to return later. Next I tied a number value to the type of value passed in as ruleKey. Then I used a for loop to loop through the list. I... | 0 | A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain.
To obtain `target`, you may apply the following opera... | Iterate on each item, and check if each one matches the rule according to the statement. |
[PYTHON 3] ONE LINER | count-items-matching-a-rule | 0 | 1 | Runtime: 305 ms, faster than 70.89% of Python3 online submissions for Count Items Matching a Rule.\nMemory Usage: 20.3 MB, less than 34.60% of Python3 online submissions for Count Items Matching a Rule.\n\n```\nclass Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n ... | 5 | You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` ... | null |
[PYTHON 3] ONE LINER | count-items-matching-a-rule | 0 | 1 | Runtime: 305 ms, faster than 70.89% of Python3 online submissions for Count Items Matching a Rule.\nMemory Usage: 20.3 MB, less than 34.60% of Python3 online submissions for Count Items Matching a Rule.\n\n```\nclass Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n ... | 5 | A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain.
To obtain `target`, you may apply the following opera... | Iterate on each item, and check if each one matches the rule according to the statement. |
[Python3] top-down dp | closest-dessert-cost | 0 | 1 | \n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n toppingCosts *= 2\n \n @cache\n def fn(i, x):\n """Return sum of subsequence of toppingCosts[i:] closest to x."""\n if x < 0 or i == len(toppingCosts)... | 24 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
[Python3] top-down dp | closest-dessert-cost | 0 | 1 | \n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n toppingCosts *= 2\n \n @cache\n def fn(i, x):\n """Return sum of subsequence of toppingCosts[i:] closest to x."""\n if x < 0 or i == len(toppingCosts)... | 24 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
Backtracking - Extremely simple, elegant, and beats 98.58%. You will love this! | closest-dessert-cost | 0 | 1 | # Intuition\nFind the minimum over all bases by running DFS over all toppings to find the choices which minimize the absolute difference to the total. We stop when adding more toppings will just take us further from the target as an optimiztion.\n\n\n# Code\n```\nclass Solution:\n def closestCost(self, baseCosts: Li... | 1 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
Backtracking - Extremely simple, elegant, and beats 98.58%. You will love this! | closest-dessert-cost | 0 | 1 | # Intuition\nFind the minimum over all bases by running DFS over all toppings to find the choices which minimize the absolute difference to the total. We stop when adding more toppings will just take us further from the target as an optimiztion.\n\n\n# Code\n```\nclass Solution:\n def closestCost(self, baseCosts: Li... | 1 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
Python | BFS | 207ms | 4-line | fast and simple solution | closest-dessert-cost | 0 | 1 | ```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n q = [target - basecost for basecost in baseCosts]\n\n for toppingcost in toppingCosts:\n q += [val - cost for val in q if val > 0 for cost in (toppingcost, toppingcost * 2)]\n\n... | 7 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
Python | BFS | 207ms | 4-line | fast and simple solution | closest-dessert-cost | 0 | 1 | ```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n q = [target - basecost for basecost in baseCosts]\n\n for toppingcost in toppingCosts:\n q += [val - cost for val in q if val > 0 for cost in (toppingcost, toppingcost * 2)]\n\n... | 7 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
Python 3 solution: Minimizing the error using backtracking | closest-dessert-cost | 0 | 1 | ```python\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n toppingCosts *= 2\n \n best_error = float("inf") # best error can be greater than `target`\n \n @cache\n def findError(index, target):\n if in... | 1 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
Python 3 solution: Minimizing the error using backtracking | closest-dessert-cost | 0 | 1 | ```python\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n toppingCosts *= 2\n \n best_error = float("inf") # best error can be greater than `target`\n \n @cache\n def findError(index, target):\n if in... | 1 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
Python easy to read and understand | backtracking | closest-dessert-cost | 0 | 1 | ```\nclass Solution:\n def solve(self, sums, topping, target, index):\n res = abs(sums-target)\n if res < self.diff:\n #print(sums, res)\n self.diff = res\n self.ans = sums\n elif res == self.diff:\n self.ans = min(self.ans, sums)\n if index == ... | 1 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
Python easy to read and understand | backtracking | closest-dessert-cost | 0 | 1 | ```\nclass Solution:\n def solve(self, sums, topping, target, index):\n res = abs(sums-target)\n if res < self.diff:\n #print(sums, res)\n self.diff = res\n self.ans = sums\n elif res == self.diff:\n self.ans = min(self.ans, sums)\n if index == ... | 1 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
Python simple DP O(NV) beat 99% | closest-dessert-cost | 0 | 1 | # Intuition\nSimple DP similar to Coin Change II, Time O(M+NV), V is target, N is number of toppings, M is number bases\n\n# Code\n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n price=set()\n minb=min(baseCosts)\n if minb>target... | 0 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
Python simple DP O(NV) beat 99% | closest-dessert-cost | 0 | 1 | # Intuition\nSimple DP similar to Coin Change II, Time O(M+NV), V is target, N is number of toppings, M is number bases\n\n# Code\n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n price=set()\n minb=min(baseCosts)\n if minb>target... | 0 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
Simple python solutions | base solution + 2 heuristics | closest-dessert-cost | 0 | 1 | # Complexity\n- Time complexity: $$O(n \\cdot 3^m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(3^m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\n# base solution\n\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCost... | 0 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
Simple python solutions | base solution + 2 heuristics | closest-dessert-cost | 0 | 1 | # Complexity\n- Time complexity: $$O(n \\cdot 3^m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(3^m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\n# base solution\n\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCost... | 0 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
Python, runtime O(n*3^m), memory O(m) | closest-dessert-cost | 0 | 1 | Backtracking - `n` = len(baseCosts), `m` = len(toppingCosts)\n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n\n def recur(cost, index, ans):\n if index == len(toppingCosts):\n if abs(cost-target) < abs(ans-target) or ... | 0 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
Python, runtime O(n*3^m), memory O(m) | closest-dessert-cost | 0 | 1 | Backtracking - `n` = len(baseCosts), `m` = len(toppingCosts)\n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n\n def recur(cost, index, ans):\n if index == len(toppingCosts):\n if abs(cost-target) < abs(ans-target) or ... | 0 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
[Python3] Using memo without the recursion | closest-dessert-cost | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt looked like a typical knapsack prob to at first.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI suck at recursions for such probs so I used a simple memo to record "reachable points". Think it as the distance... | 0 | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no topp... | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. |
[Python3] Using memo without the recursion | closest-dessert-cost | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt looked like a typical knapsack prob to at first.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI suck at recursions for such probs so I used a simple memo to record "reachable points". Think it as the distance... | 0 | There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.).
The tournament consists of multiple rounds (st... | As the constraints are not large, you can brute force and enumerate all the possibilities. |
[Python3] two heaps | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | \n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n if 6*len(nums1) < len(nums2) or 6*len(nums2) < len(nums1): return -1 # impossible \n \n if sum(nums1) < sum(nums2): nums1, nums2 = nums2, nums1\n s1, s2 = sum(nums1), sum(nums2)\n \n ... | 19 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
[Python3] two heaps | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | \n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n if 6*len(nums1) < len(nums2) or 6*len(nums2) < len(nums1): return -1 # impossible \n \n if sum(nums1) < sum(nums2): nums1, nums2 = nums2, nums1\n s1, s2 = sum(nums1), sum(nums2)\n \n ... | 19 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python 3 | Heap, Greedy | Explanations | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | ### Explanation\n- There will be a difference (`diff`) between `the sum of nums1` and `the sum of nums2`\n- To make the `diff` converges to 0 the fastest way, we want to make \n\t- The list with larger sum, become smaller\n\t- The list with smaller sum, become larger\n\t- We define `effort` as the absolute difference b... | 13 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Python 3 | Heap, Greedy | Explanations | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | ### Explanation\n- There will be a difference (`diff`) between `the sum of nums1` and `the sum of nums2`\n- To make the `diff` converges to 0 the fastest way, we want to make \n\t- The list with larger sum, become smaller\n\t- The list with smaller sum, become larger\n\t- We define `effort` as the absolute difference b... | 13 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python Short Clean | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the difference in sum between the two lists. Then put them in the same heap. Pull the biggest difference maker each time from the heap until you compensate for the difference or run the heap out of items.\n\n# Approach\n<!-- Des... | 1 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.