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: O(N^2) solution intuitive
maximum-repeating-substring
0
1
O(n^2) still but found it to be more intuitive than the top solutions\n\n# Code\n```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n i = 0\n j = 0\n max_ct = 0\n\n if len(word) > len(sequence):\n return 0\n\n ct = 0\n while i < len(sequence):\n while sequence[j:j+len(word)] == word:\n ct += 1\n j += len(word)\n max_ct = max(max_ct, ct)\n ct = 0\n i += 1\n j = i\n return max_ct\n```
2
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` subarray in `nums` (i.e. the subarrays must be in the same order as `groups`). Return `true` _if you can do this task, and_ `false` _otherwise_. Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. **Example 1:** **Input:** groups = \[\[1,-1,-1\],\[3,-2,0\]\], nums = \[1,-1,0,1,-1,-1,3,-2,0\] **Output:** true **Explanation:** You can choose the 0th subarray as \[1,-1,0,**1,-1,-1**,3,-2,0\] and the 1st one as \[1,-1,0,1,-1,-1,**3,-2,0**\]. These subarrays are disjoint as they share no common nums\[k\] element. **Example 2:** **Input:** groups = \[\[10,-2\],\[1,2,3,4\]\], nums = \[1,2,3,4,10,-2\] **Output:** false **Explanation:** Note that choosing the subarrays \[**1,2,3,4**,10,-2\] and \[1,2,3,4,**10,-2**\] is incorrect because they are not in the same order as in groups. \[10,-2\] must come before \[1,2,3,4\]. **Example 3:** **Input:** groups = \[\[1,2,3\],\[3,4\]\], nums = \[7,7,1,2,3,4,7,7\] **Output:** false **Explanation:** Note that choosing the subarrays \[7,7,**1,2,3**,4,7,7\] and \[7,7,1,2,**3,4**,7,7\] is invalid because they are not disjoint. They share a common elements nums\[4\] (0-indexed). **Constraints:** * `groups.length == n` * `1 <= n <= 103` * `1 <= groups[i].length, sum(groups[i].length) <= 103` * `1 <= nums.length <= 103` * `-107 <= groups[i][j], nums[k] <= 107`
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, Simple Solution
maximum-repeating-substring
0
1
We multiply the word and check occurence with `in`. \n```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n i = 0\n while word*(i+1) in sequence:\n i+=1\n return i\n```
5
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating value is `0`. Given strings `sequence` and `word`, return _the **maximum `k`\-repeating value** of `word` in `sequence`_. **Example 1:** **Input:** sequence = "ababc ", word = "ab " **Output:** 2 **Explanation: ** "abab " is a substring in "ababc ". **Example 2:** **Input:** sequence = "ababc ", word = "ba " **Output:** 1 **Explanation: ** "ba " is a substring in "ababc ". "baba " is not a substring in "ababc ". **Example 3:** **Input:** sequence = "ababc ", word = "ac " **Output:** 0 **Explanation: ** "ac " is not a substring in "ababc ". **Constraints:** * `1 <= sequence.length <= 100` * `1 <= word.length <= 100` * `sequence` and `word` contains only lowercase English letters.
Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).
Python3, Simple Solution
maximum-repeating-substring
0
1
We multiply the word and check occurence with `in`. \n```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n i = 0\n while word*(i+1) in sequence:\n i+=1\n return i\n```
5
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` subarray in `nums` (i.e. the subarrays must be in the same order as `groups`). Return `true` _if you can do this task, and_ `false` _otherwise_. Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. **Example 1:** **Input:** groups = \[\[1,-1,-1\],\[3,-2,0\]\], nums = \[1,-1,0,1,-1,-1,3,-2,0\] **Output:** true **Explanation:** You can choose the 0th subarray as \[1,-1,0,**1,-1,-1**,3,-2,0\] and the 1st one as \[1,-1,0,1,-1,-1,**3,-2,0**\]. These subarrays are disjoint as they share no common nums\[k\] element. **Example 2:** **Input:** groups = \[\[10,-2\],\[1,2,3,4\]\], nums = \[1,2,3,4,10,-2\] **Output:** false **Explanation:** Note that choosing the subarrays \[**1,2,3,4**,10,-2\] and \[1,2,3,4,**10,-2**\] is incorrect because they are not in the same order as in groups. \[10,-2\] must come before \[1,2,3,4\]. **Example 3:** **Input:** groups = \[\[1,2,3\],\[3,4\]\], nums = \[7,7,1,2,3,4,7,7\] **Output:** false **Explanation:** Note that choosing the subarrays \[7,7,**1,2,3**,4,7,7\] and \[7,7,1,2,**3,4**,7,7\] is invalid because they are not disjoint. They share a common elements nums\[4\] (0-indexed). **Constraints:** * `groups.length == n` * `1 <= n <= 103` * `1 <= groups[i].length, sum(groups[i].length) <= 103` * `1 <= nums.length <= 103` * `-107 <= groups[i][j], nums[k] <= 107`
The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.
Python Solution to the problem
maximum-repeating-substring
0
1
# Intuition\nThe intuition is to repeatedly concatenate the given word to itself and check if the resulting sequence is a substring of the given sequence. Keep track of the count until the condition is no longer satisfied.\n\n# Approach\nInitialize a count variable to 0.\nInitialize a variable current_sequence with the value of the given word.\nUse a while loop to check if current_sequence is a substring of the given sequence.\nInside the loop, increment the count and update current_sequence by concatenating the given word to it.\nContinue the loop until current_sequence is no longer a substring of the given sequence.\nReturn the count as the maximum k-repeating value.\n\n# Complexity\n- Time complexity:\nO(n\u22C5m), where n is the length of the given sequence and m is the length of the given word. In the worst case, the loop iterates n/m times.\n\n- Space complexity:\nO(m), where m is the length of the given word. The space is used to store current_sequence.\n\n# Code\n```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n count = 0\n current_sequence = word\n\n while current_sequence in sequence:\n count += 1\n current_sequence += word\n\n return count\n```
0
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating value is `0`. Given strings `sequence` and `word`, return _the **maximum `k`\-repeating value** of `word` in `sequence`_. **Example 1:** **Input:** sequence = "ababc ", word = "ab " **Output:** 2 **Explanation: ** "abab " is a substring in "ababc ". **Example 2:** **Input:** sequence = "ababc ", word = "ba " **Output:** 1 **Explanation: ** "ba " is a substring in "ababc ". "baba " is not a substring in "ababc ". **Example 3:** **Input:** sequence = "ababc ", word = "ac " **Output:** 0 **Explanation: ** "ac " is not a substring in "ababc ". **Constraints:** * `1 <= sequence.length <= 100` * `1 <= word.length <= 100` * `sequence` and `word` contains only lowercase English letters.
Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).
Python Solution to the problem
maximum-repeating-substring
0
1
# Intuition\nThe intuition is to repeatedly concatenate the given word to itself and check if the resulting sequence is a substring of the given sequence. Keep track of the count until the condition is no longer satisfied.\n\n# Approach\nInitialize a count variable to 0.\nInitialize a variable current_sequence with the value of the given word.\nUse a while loop to check if current_sequence is a substring of the given sequence.\nInside the loop, increment the count and update current_sequence by concatenating the given word to it.\nContinue the loop until current_sequence is no longer a substring of the given sequence.\nReturn the count as the maximum k-repeating value.\n\n# Complexity\n- Time complexity:\nO(n\u22C5m), where n is the length of the given sequence and m is the length of the given word. In the worst case, the loop iterates n/m times.\n\n- Space complexity:\nO(m), where m is the length of the given word. The space is used to store current_sequence.\n\n# Code\n```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n count = 0\n current_sequence = word\n\n while current_sequence in sequence:\n count += 1\n current_sequence += word\n\n return count\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` subarray in `nums` (i.e. the subarrays must be in the same order as `groups`). Return `true` _if you can do this task, and_ `false` _otherwise_. Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. **Example 1:** **Input:** groups = \[\[1,-1,-1\],\[3,-2,0\]\], nums = \[1,-1,0,1,-1,-1,3,-2,0\] **Output:** true **Explanation:** You can choose the 0th subarray as \[1,-1,0,**1,-1,-1**,3,-2,0\] and the 1st one as \[1,-1,0,1,-1,-1,**3,-2,0**\]. These subarrays are disjoint as they share no common nums\[k\] element. **Example 2:** **Input:** groups = \[\[10,-2\],\[1,2,3,4\]\], nums = \[1,2,3,4,10,-2\] **Output:** false **Explanation:** Note that choosing the subarrays \[**1,2,3,4**,10,-2\] and \[1,2,3,4,**10,-2**\] is incorrect because they are not in the same order as in groups. \[10,-2\] must come before \[1,2,3,4\]. **Example 3:** **Input:** groups = \[\[1,2,3\],\[3,4\]\], nums = \[7,7,1,2,3,4,7,7\] **Output:** false **Explanation:** Note that choosing the subarrays \[7,7,**1,2,3**,4,7,7\] and \[7,7,1,2,**3,4**,7,7\] is invalid because they are not disjoint. They share a common elements nums\[4\] (0-indexed). **Constraints:** * `groups.length == n` * `1 <= n <= 103` * `1 <= groups[i].length, sum(groups[i].length) <= 103` * `1 <= nums.length <= 103` * `-107 <= groups[i][j], nums[k] <= 107`
The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.
Python solution
maximum-repeating-substring
0
1
```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n counter, new_one = 0, word\n\n while True:\n if new_one in sequence:\n counter += 1\n new_one += word\n else: break\n\n return counter\n # 7m\n\n```
0
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating value is `0`. Given strings `sequence` and `word`, return _the **maximum `k`\-repeating value** of `word` in `sequence`_. **Example 1:** **Input:** sequence = "ababc ", word = "ab " **Output:** 2 **Explanation: ** "abab " is a substring in "ababc ". **Example 2:** **Input:** sequence = "ababc ", word = "ba " **Output:** 1 **Explanation: ** "ba " is a substring in "ababc ". "baba " is not a substring in "ababc ". **Example 3:** **Input:** sequence = "ababc ", word = "ac " **Output:** 0 **Explanation: ** "ac " is not a substring in "ababc ". **Constraints:** * `1 <= sequence.length <= 100` * `1 <= word.length <= 100` * `sequence` and `word` contains only lowercase English letters.
Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).
Python solution
maximum-repeating-substring
0
1
```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n counter, new_one = 0, word\n\n while True:\n if new_one in sequence:\n counter += 1\n new_one += word\n else: break\n\n return counter\n # 7m\n\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` subarray in `nums` (i.e. the subarrays must be in the same order as `groups`). Return `true` _if you can do this task, and_ `false` _otherwise_. Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. **Example 1:** **Input:** groups = \[\[1,-1,-1\],\[3,-2,0\]\], nums = \[1,-1,0,1,-1,-1,3,-2,0\] **Output:** true **Explanation:** You can choose the 0th subarray as \[1,-1,0,**1,-1,-1**,3,-2,0\] and the 1st one as \[1,-1,0,1,-1,-1,**3,-2,0**\]. These subarrays are disjoint as they share no common nums\[k\] element. **Example 2:** **Input:** groups = \[\[10,-2\],\[1,2,3,4\]\], nums = \[1,2,3,4,10,-2\] **Output:** false **Explanation:** Note that choosing the subarrays \[**1,2,3,4**,10,-2\] and \[1,2,3,4,**10,-2**\] is incorrect because they are not in the same order as in groups. \[10,-2\] must come before \[1,2,3,4\]. **Example 3:** **Input:** groups = \[\[1,2,3\],\[3,4\]\], nums = \[7,7,1,2,3,4,7,7\] **Output:** false **Explanation:** Note that choosing the subarrays \[7,7,**1,2,3**,4,7,7\] and \[7,7,1,2,**3,4**,7,7\] is invalid because they are not disjoint. They share a common elements nums\[4\] (0-indexed). **Constraints:** * `groups.length == n` * `1 <= n <= 103` * `1 <= groups[i].length, sum(groups[i].length) <= 103` * `1 <= nums.length <= 103` * `-107 <= groups[i][j], nums[k] <= 107`
The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.
Python Simple Solution!!
maximum-repeating-substring
0
1
# Code\n```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n\n k: int = 1\n while (word * k) in sequence:\n k += 1\n return k - 1\n```
0
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating value is `0`. Given strings `sequence` and `word`, return _the **maximum `k`\-repeating value** of `word` in `sequence`_. **Example 1:** **Input:** sequence = "ababc ", word = "ab " **Output:** 2 **Explanation: ** "abab " is a substring in "ababc ". **Example 2:** **Input:** sequence = "ababc ", word = "ba " **Output:** 1 **Explanation: ** "ba " is a substring in "ababc ". "baba " is not a substring in "ababc ". **Example 3:** **Input:** sequence = "ababc ", word = "ac " **Output:** 0 **Explanation: ** "ac " is not a substring in "ababc ". **Constraints:** * `1 <= sequence.length <= 100` * `1 <= word.length <= 100` * `sequence` and `word` contains only lowercase English letters.
Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).
Python Simple Solution!!
maximum-repeating-substring
0
1
# Code\n```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n\n k: int = 1\n while (word * k) in sequence:\n k += 1\n return k - 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` subarray in `nums` (i.e. the subarrays must be in the same order as `groups`). Return `true` _if you can do this task, and_ `false` _otherwise_. Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. **Example 1:** **Input:** groups = \[\[1,-1,-1\],\[3,-2,0\]\], nums = \[1,-1,0,1,-1,-1,3,-2,0\] **Output:** true **Explanation:** You can choose the 0th subarray as \[1,-1,0,**1,-1,-1**,3,-2,0\] and the 1st one as \[1,-1,0,1,-1,-1,**3,-2,0**\]. These subarrays are disjoint as they share no common nums\[k\] element. **Example 2:** **Input:** groups = \[\[10,-2\],\[1,2,3,4\]\], nums = \[1,2,3,4,10,-2\] **Output:** false **Explanation:** Note that choosing the subarrays \[**1,2,3,4**,10,-2\] and \[1,2,3,4,**10,-2**\] is incorrect because they are not in the same order as in groups. \[10,-2\] must come before \[1,2,3,4\]. **Example 3:** **Input:** groups = \[\[1,2,3\],\[3,4\]\], nums = \[7,7,1,2,3,4,7,7\] **Output:** false **Explanation:** Note that choosing the subarrays \[7,7,**1,2,3**,4,7,7\] and \[7,7,1,2,**3,4**,7,7\] is invalid because they are not disjoint. They share a common elements nums\[4\] (0-indexed). **Constraints:** * `groups.length == n` * `1 <= n <= 103` * `1 <= groups[i].length, sum(groups[i].length) <= 103` * `1 <= nums.length <= 103` * `-107 <= groups[i][j], nums[k] <= 107`
The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.
Solution with Linked List in Python3 / TypeScript
merge-in-between-linked-lists
0
1
# Intuition\nLet\'s briefly explain what the problem is:\n- there\'re **Linked Lists** `list1` and `list2`, integers `a` and `b`\n- our goal is to remove nodes at `list1` from `a` to `b` indexes and insert `list2` instead.\n\nThe algorithm is **quite simple**: store index `c` as current count of nodes, store nodes with values `a` and `b` into `left` and `right`, respectively.\nThen **remove** referrences from `left` and `right` an replace it with `list2`. \n\n# Approach\n1. declare `dummy` to have an actual referrence to the `list1`\n2. declare `left`, `right` as **pointers**\n3. use `c` as count of nodes from `list1`\n4. iterate over `list1` and find `a` and `b` vals, store nodes into **pointers**, then append at `left.next = list2` \n5. iterate over `list2`, find **last node** for appending `right`\n6. append `right` as `list2.next = right`\n7. return `dummy.next` \n\n# Complexity\n- Time complexity: **O(N + M)**, where `N` and `M` - sizes of `list1` and `list2`\n\n- Space complexity: **O(1)**, we don\'t allocate extra space.\n\n# Code in Python3\n```\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n dummy = ListNode(-1, list1)\n left = None\n right = None\n c = 0\n\n while list1 and (not left or not right):\n c += 1\n\n if c == a: left = list1\n if c == b: right = list1.next.next\n\n list1 = list1.next\n\n if left: left.next = list2\n\n while list2.next: list2 = list2.next\n\n list2.next = right\n\n return dummy.next\n```\n\n# Code in TypeScript\n```\nfunction mergeInBetween(\n list1: ListNode | null,\n a: number,\n b: number,\n list2: ListNode | null\n): ListNode | null {\n let dummy = new ListNode(-1, list1);\n let left = null;\n let right = null;\n let c = 0\n\n while (list1 && (!left || !right)) {\n c++\n\n if (c === a) left = list1;\n if (c === b) right = list1.next.next;\n\n list1 = list1.next;\n }\n\n if (left) left.next = list2;\n\n while (list2.next) list2 = list2.next;\n\n list2.next = right;\n\n return dummy.next;\n}\n\n```
1
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Solution with Linked List in Python3 / TypeScript
merge-in-between-linked-lists
0
1
# Intuition\nLet\'s briefly explain what the problem is:\n- there\'re **Linked Lists** `list1` and `list2`, integers `a` and `b`\n- our goal is to remove nodes at `list1` from `a` to `b` indexes and insert `list2` instead.\n\nThe algorithm is **quite simple**: store index `c` as current count of nodes, store nodes with values `a` and `b` into `left` and `right`, respectively.\nThen **remove** referrences from `left` and `right` an replace it with `list2`. \n\n# Approach\n1. declare `dummy` to have an actual referrence to the `list1`\n2. declare `left`, `right` as **pointers**\n3. use `c` as count of nodes from `list1`\n4. iterate over `list1` and find `a` and `b` vals, store nodes into **pointers**, then append at `left.next = list2` \n5. iterate over `list2`, find **last node** for appending `right`\n6. append `right` as `list2.next = right`\n7. return `dummy.next` \n\n# Complexity\n- Time complexity: **O(N + M)**, where `N` and `M` - sizes of `list1` and `list2`\n\n- Space complexity: **O(1)**, we don\'t allocate extra space.\n\n# Code in Python3\n```\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n dummy = ListNode(-1, list1)\n left = None\n right = None\n c = 0\n\n while list1 and (not left or not right):\n c += 1\n\n if c == a: left = list1\n if c == b: right = list1.next.next\n\n list1 = list1.next\n\n if left: left.next = list2\n\n while list2.next: list2 = list2.next\n\n list2.next = right\n\n return dummy.next\n```\n\n# Code in TypeScript\n```\nfunction mergeInBetween(\n list1: ListNode | null,\n a: number,\n b: number,\n list2: ListNode | null\n): ListNode | null {\n let dummy = new ListNode(-1, list1);\n let left = null;\n let right = null;\n let c = 0\n\n while (list1 && (!left || !right)) {\n c++\n\n if (c === a) left = list1;\n if (c === b) right = list1.next.next;\n\n list1 = list1.next;\n }\n\n if (left) left.next = list2;\n\n while (list2.next) list2 = list2.next;\n\n list2.next = right;\n\n return dummy.next;\n}\n\n```
1
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 height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
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.
EFFICIENT MERGING WITH [O(n) && O(1)] COMPLEXITIES
merge-in-between-linked-lists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition is a way more generalized, as it will be analogous to repair the damaged patch in a cloth or the rope.\nAnyone can do is to navigate to the damaged portions and then sew the new patch to the both ends of the older part.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. As it was discussed in the intuition, we\'r going to initilize the pointers that will help us in navigating through the lists.\n2. At first we need to track about the curtailing ends in the list1, so we\'r going to traverse along the list and make the notes of "a - 1" and "b + 1" positions.(as we need to remove the positions in the range of [a, b] so we need the past and next pointers of this range.)\n3. In the next stage we need the last node of the list2.(To attach it to the remains of the curtailed list1.)\n4. Now we need to attach the first pointer of list2 to the ath pointer of the list1.(Which in turn removes the list1\'s nodes from ath pointer, and the new list1\'s end point is list2\'s end point.)\n5. Now with the previously marked last pointer of list2, we will attach the list1\'s "b + 1" pointer to list2\'s end point.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWith 2 while loops running independently, the time complexity would be O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe didnt used any extra data structure in the procedure, therefore space complexity would be constant i.e., O(1).\n\n# Code\n```\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n l1ptr, l2ptr, i = list1, list2, 0\n while True:\n if i == a - 1:\n athptr = l1ptr\n if i == b + 1:\n bthptr = l1ptr\n break\n i += 1\n l1ptr = l1ptr.next\n while True:\n if l2ptr.next == None:\n break\n else:\n l2ptr = l2ptr.next\n athptr.next = list2\n l2ptr.next = bthptr\n return list1\n```
1
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
EFFICIENT MERGING WITH [O(n) && O(1)] COMPLEXITIES
merge-in-between-linked-lists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition is a way more generalized, as it will be analogous to repair the damaged patch in a cloth or the rope.\nAnyone can do is to navigate to the damaged portions and then sew the new patch to the both ends of the older part.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. As it was discussed in the intuition, we\'r going to initilize the pointers that will help us in navigating through the lists.\n2. At first we need to track about the curtailing ends in the list1, so we\'r going to traverse along the list and make the notes of "a - 1" and "b + 1" positions.(as we need to remove the positions in the range of [a, b] so we need the past and next pointers of this range.)\n3. In the next stage we need the last node of the list2.(To attach it to the remains of the curtailed list1.)\n4. Now we need to attach the first pointer of list2 to the ath pointer of the list1.(Which in turn removes the list1\'s nodes from ath pointer, and the new list1\'s end point is list2\'s end point.)\n5. Now with the previously marked last pointer of list2, we will attach the list1\'s "b + 1" pointer to list2\'s end point.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWith 2 while loops running independently, the time complexity would be O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe didnt used any extra data structure in the procedure, therefore space complexity would be constant i.e., O(1).\n\n# Code\n```\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n l1ptr, l2ptr, i = list1, list2, 0\n while True:\n if i == a - 1:\n athptr = l1ptr\n if i == b + 1:\n bthptr = l1ptr\n break\n i += 1\n l1ptr = l1ptr.next\n while True:\n if l2ptr.next == None:\n break\n else:\n l2ptr = l2ptr.next\n athptr.next = list2\n l2ptr.next = bthptr\n return list1\n```
1
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 height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
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 | Loops | Arrays
merge-in-between-linked-lists
0
1
# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n res = []\n pos = 0\n while list1:\n if pos == a:\n while True:\n while list2:\n res.append(list2.val)\n list2 = list2.next\n\n if pos == b:\n list1 = list1.next\n break\n list1 = list1.next\n pos += 1\n\n res.append(list1.val)\n list1 = list1.next\n pos += 1\n d = n = ListNode()\n for i in res:\n d.next = ListNode(i)\n d = d.next\n\n return n.next\n\n\n```\nDo upvote if you like the solution :)\n
1
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Easy | Python Solution | Loops | Arrays
merge-in-between-linked-lists
0
1
# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n res = []\n pos = 0\n while list1:\n if pos == a:\n while True:\n while list2:\n res.append(list2.val)\n list2 = list2.next\n\n if pos == b:\n list1 = list1.next\n break\n list1 = list1.next\n pos += 1\n\n res.append(list1.val)\n list1 = list1.next\n pos += 1\n d = n = ListNode()\n for i in res:\n d.next = ListNode(i)\n d = d.next\n\n return n.next\n\n\n```\nDo upvote if you like the solution :)\n
1
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 height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
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, easy to understand,
merge-in-between-linked-lists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will get to the node before \'a\' th index and will link the next pointer to list 2 and using another loop will get to the \'b\' th node.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We will get to the "a - 1"th node (in code the first loop).\n2. Link this to the first node of list2 but before that store the a\'th node in a temporary variable.\n3. Now we must visit the last node of list2 which we have linked to the list1\n```\nwhile itr.next:\n itr = itr.next\n```\n4. Now we have to find the b\'th node (using temporary variable node) and linked the \'b + 1\'th to the list got from Step 2.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nm)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n itr = list1\n cnt = 0\n while itr:\n if cnt == a - 1:\n node = itr.next\n itr.next = list2\n while itr.next:\n itr = itr.next\n \n while node:\n if cnt == b:\n itr.next = node\n break\n else:\n node = node.next\n cnt += 1\n else:\n cnt += 1\n itr = itr.next\n return list1\n\n```
2
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Python3, easy to understand,
merge-in-between-linked-lists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will get to the node before \'a\' th index and will link the next pointer to list 2 and using another loop will get to the \'b\' th node.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We will get to the "a - 1"th node (in code the first loop).\n2. Link this to the first node of list2 but before that store the a\'th node in a temporary variable.\n3. Now we must visit the last node of list2 which we have linked to the list1\n```\nwhile itr.next:\n itr = itr.next\n```\n4. Now we have to find the b\'th node (using temporary variable node) and linked the \'b + 1\'th to the list got from Step 2.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nm)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n itr = list1\n cnt = 0\n while itr:\n if cnt == a - 1:\n node = itr.next\n itr.next = list2\n while itr.next:\n itr = itr.next\n \n while node:\n if cnt == b:\n itr.next = node\n break\n else:\n node = node.next\n cnt += 1\n else:\n cnt += 1\n itr = itr.next\n return list1\n\n```
2
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 height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
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.
Beats 90% || Linked List || Python
merge-in-between-linked-lists
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)$$ -->\nO((length(list1))+(length(list2)))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n curr=list1\n t=0\n var=None\n while curr!=None:\n t+=1\n if t==b+1:\n break\n if a==t:\n pp=curr.next\n var=curr\n var.next=list2\n # curr.next=None\n curr=pp\n curr=curr.next\n temp=list1\n while temp!=None:\n if temp.next==None:\n break\n temp=temp.next\n temp.next=curr\n return list1\n\n \n \n```
1
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Beats 90% || Linked List || Python
merge-in-between-linked-lists
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)$$ -->\nO((length(list1))+(length(list2)))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n curr=list1\n t=0\n var=None\n while curr!=None:\n t+=1\n if t==b+1:\n break\n if a==t:\n pp=curr.next\n var=curr\n var.next=list2\n # curr.next=None\n curr=pp\n curr=curr.next\n temp=list1\n while temp!=None:\n if temp.next==None:\n break\n temp=temp.next\n temp.next=curr\n return list1\n\n \n \n```
1
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 height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
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 || Easy solution.
merge-in-between-linked-lists
0
1
# It would be really great if you guys upvote, if found the solution helpful.\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n lst1,lst2= [],[]\n while list1:\n lst1.append(list1.val)\n list1 = list1.next\n while list2:\n lst2.append(list2.val)\n list2 = list2.next\n lst1[a:b+1]=lst2[:]\n a = ListNode(0)\n temp = a\n for i in lst1:\n temp.next = ListNode(i)\n temp = temp.next\n return a.next\n```
1
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Python3 || Easy solution.
merge-in-between-linked-lists
0
1
# It would be really great if you guys upvote, if found the solution helpful.\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n lst1,lst2= [],[]\n while list1:\n lst1.append(list1.val)\n list1 = list1.next\n while list2:\n lst2.append(list2.val)\n list2 = list2.next\n lst1[a:b+1]=lst2[:]\n a = ListNode(0)\n temp = a\n for i in lst1:\n temp.next = ListNode(i)\n temp = temp.next\n return a.next\n```
1
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 height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
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.
Super Easy and Efficient Python
merge-in-between-linked-lists
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n start, end = list1, list1\n for _ in range(a-1):\n start = start.next\n print(start.val)\n\n for _ in range(b+1):\n end = end.next\n print(end.val)\n\n start.next = list2\n while start.next:\n start = start.next\n start.next = end\n return list1\n```
1
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Super Easy and Efficient Python
merge-in-between-linked-lists
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n start, end = list1, list1\n for _ in range(a-1):\n start = start.next\n print(start.val)\n\n for _ in range(b+1):\n end = end.next\n print(end.val)\n\n start.next = list2\n while start.next:\n start = start.next\n start.next = end\n return list1\n```
1
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 height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
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] - 2 pointers approach code with comments - O(m+n)
merge-in-between-linked-lists
0
1
This is my approach to the problem using 2 pointers :\n```\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n # Define 2 pointers\n\t\tptr1 = list1\n ptr2 = list1\n i, j = 0, 0\n\t\t\n\t\t# Loop for pointer 1 to reach previous node from a\n while i!=a-1:\n ptr1 = ptr1.next\n i += 1 \n\t\t\t\n\t\t# Loop for pointer 2 to reach node b\n while j!=b:\n ptr2 = ptr2.next\n j += 1\n\t\t\t\n\t\t# Connect list2 to the next of pointer1\n ptr1.next = list2\n\t\t\n\t\t# Traverse the list2 till end node\n while list2.next!=None:\n list2 = list2.next\n\t\t\n\t\t# Assign the next of pointer 2 to the next of list2 i.e connect the remaining part of list1 to list2\n list2.next = ptr2.next\n\t\t\n\t\t# return final list\n return list1\n```\n\nFeel free to comment down your solutions as well :)
16
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
[Python 3] - 2 pointers approach code with comments - O(m+n)
merge-in-between-linked-lists
0
1
This is my approach to the problem using 2 pointers :\n```\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n # Define 2 pointers\n\t\tptr1 = list1\n ptr2 = list1\n i, j = 0, 0\n\t\t\n\t\t# Loop for pointer 1 to reach previous node from a\n while i!=a-1:\n ptr1 = ptr1.next\n i += 1 \n\t\t\t\n\t\t# Loop for pointer 2 to reach node b\n while j!=b:\n ptr2 = ptr2.next\n j += 1\n\t\t\t\n\t\t# Connect list2 to the next of pointer1\n ptr1.next = list2\n\t\t\n\t\t# Traverse the list2 till end node\n while list2.next!=None:\n list2 = list2.next\n\t\t\n\t\t# Assign the next of pointer 2 to the next of list2 i.e connect the remaining part of list1 to list2\n list2.next = ptr2.next\n\t\t\n\t\t# return final list\n return list1\n```\n\nFeel free to comment down your solutions as well :)
16
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 height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
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 Solution
design-front-middle-back-queue
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)$$ -->\n\n# Code\n```\nclass FrontMiddleBackQueue:\n\n def __init__(self):\n self.queue=[]\n \n\n def pushFront(self, val: int) -> None:\n self.queue.insert(0,val)\n \n\n def pushMiddle(self, val: int) -> None:\n leng=len(self.queue)\n mid=leng//2\n \n self.queue.insert(mid,val)\n \n\n def pushBack(self, val: int) -> None:\n self.queue.append(val)\n \n\n def popFront(self) -> int:\n \n if(len(self.queue)==0):\n return(-1)\n \n return(self.queue.pop(0))\n \n\n def popMiddle(self) -> int:\n if(len(self.queue)==0):\n return(-1)\n\n leng=len(self.queue)\n mid=leng//2\n if(leng%2!=0):\n \n return(self.queue.pop(mid))\n else:\n return(self.queue.pop(mid-1))\n\n \n\n def popBack(self) -> int:\n if(len(self.queue)==0):\n return(-1)\n return(self.queue.pop(-1))\n \n\n\n# Your FrontMiddleBackQueue object will be instantiated and called as such:\n# obj = FrontMiddleBackQueue()\n# obj.pushFront(val)\n# obj.pushMiddle(val)\n# obj.pushBack(val)\n# param_4 = obj.popFront()\n# param_5 = obj.popMiddle()\n# param_6 = obj.popBack()\n```
1
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
Design Front Middle Back Queue
design-front-middle-back-queue
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)$$ -->\n![image.png](https://assets.leetcode.com/users/images/cec6492f-2ebe-45ff-9614-85e1aefa95af_1687808754.8704185.png)\n\n# Code\n```\nclass FrontMiddleBackQueue:\n\n def __init__(self):\n self.queue=[]\n \n\n def pushFront(self, val: int) -> None:\n self.queue.insert(0,val)\n \n\n def pushMiddle(self, val: int) -> None:\n n=len(self.queue)\n self.queue.insert(n//2,val)\n def pushBack(self, val: int) -> None:\n self.queue.append(val)\n\n def popFront(self) -> int:\n if len(self.queue)==0:\n return -1 \n return self.queue.pop(0)\n \n\n def popMiddle(self) -> int:\n if len(self.queue)==0:\n return -1\n n=len(self.queue)\n if n%2==0:\n n=(n//2)-1\n else:\n n=int(n//2)\n return self.queue.pop(n)\n \n\n def popBack(self) -> int:\n if len(self.queue)==0:\n return -1 \n return self.queue.pop()\n \n\n\n# Your FrontMiddleBackQueue object will be instantiated and called as such:\n# obj = FrontMiddleBackQueue()\n# obj.pushFront(val)\n# obj.pushMiddle(val)\n# obj.pushBack(val)\n# param_4 = obj.popFront()\n# param_5 = obj.popMiddle()\n# param_6 = obj.popBack()\n```
1
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
O(1) with simple two deques
design-front-middle-back-queue
0
1
# Intuition\ntwo deque with the number of elements [x,x] or [x,x+1] will be good\n\n# Approach\nmaintain two deque, make sure len(right)-len(left) in [0,1]\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nfrom collections import deque\nclass FrontMiddleBackQueue:\n\n def __init__(self):\n self.left = deque()\n self.right = deque()\n\n def pushFront(self, val: int) -> None:\n self.left.appendleft(val)\n if len(self.left) > len(self.right):\n self.right.appendleft(self.left.pop())\n\n def pushMiddle(self, val: int) -> None:\n if len(self.left) < len(self.right):\n self.left.append(val)\n else:\n self.right.appendleft(val)\n\n def pushBack(self, val: int) -> None:\n self.right.append(val)\n if len(self.right)-1 > len(self.left):\n self.left.append(self.right.popleft())\n\n def popFront(self) -> int:\n if len(self.left)+len(self.right) == 0: return -1\n if len(self.left) < len(self.right):\n self.left.append(self.right.popleft())\n return self.left.popleft()\n\n def popMiddle(self) -> int:\n if len(self.left)+len(self.right) == 0: return -1\n if len(self.left) < len(self.right):\n return self.right.popleft()\n else:\n return self.left.pop()\n\n def popBack(self) -> int:\n if len(self.left)+len(self.right) == 0: return -1\n if len(self.left) == len(self.right):\n self.right.appendleft(self.left.pop())\n return self.right.pop()\n \n```
0
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
Minor Modification to List | Explained
design-front-middle-back-queue
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMost of a pythonic list in fact has this functionality already. \nAs such, we can just extend and logically implement much from there. Only real catch is middle push and pop. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAs stated in intution, do most of this with just rehashing a list. \nMake a get size function to help yourself out a bit. If the interviewer squaks, just use the len function in lists already. I did it for readability in the pop middle part. \n\nAnyways, push front and back work as expected. \nFor push middle, you\'ll insert at half of size rounded down whatever it is. Should be more finicky on their test cases but it works for now. \n\nFor pop on front and back, can only do so if you have a queue. No queue, return -1. Used conditional chaining but can be made to simple if else if desired as pop middle shows. \n\nFor pop middle \n- if we have a queue \n - get the size of the queue, calculate middle and determine if it is an even size \n - An even size split in 2 is still even\n - An odd size split in two is a fraction. \n - If it was an even size, you\'ll be off by one. Return a pop from queue at middle less one \n - Otherwise, just pop from middle \n\n# Complexity\n- Time complexity : varies \n - O(1) on the pushes front and back based on python impl and two of the pops. O(some constant) on popMiddle. \n - O(n) technically on push middle based on how python does its arrays\n\n- Space complexity : O(n) \n - n being size of the list stored \n - Only comes up in the case that you do need space to store something \n\n# Code\n```\nclass FrontMiddleBackQueue:\n\n def __init__(self):\n self.queue = []\n\n def get_size(self) : \n return len(self.queue)\n\n def pushFront(self, val: int) -> None:\n self.queue.insert(0, val)\n\n def pushMiddle(self, val: int) -> None:\n self.queue.insert(self.get_size()//2, val)\n\n def pushBack(self, val: int) -> None:\n self.queue.append(val)\n\n def popFront(self) -> int:\n return self.queue.pop(0) if self.queue else -1 \n\n def popMiddle(self) -> int:\n if self.queue : \n size = self.get_size() \n middle = size // 2 \n is_even = size % 2 == 0 \n if is_even : \n return self.queue.pop(middle-1) \n else : \n return self.queue.pop(middle)\n else : \n return -1 \n\n def popBack(self) -> int:\n return self.queue.pop() if self.queue else -1\n\n\n# Your FrontMiddleBackQueue object will be instantiated and called as such:\n# obj = FrontMiddleBackQueue()\n# obj.pushFront(val)\n# obj.pushMiddle(val)\n# obj.pushBack(val)\n# param_4 = obj.popFront()\n# param_5 = obj.popMiddle()\n# param_6 = obj.popBack()\n```
0
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
Solution
design-front-middle-back-queue
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)$$ -->\n\n# Code\n```\nclass FrontMiddleBackQueue:\n\n def __init__(self):\n self.queue = []\n\n def pushFront(self, val: int):\n self.queue.insert(0, val)\n\n def pushMiddle(self, val: int):\n middle = len(self.queue) // 2\n self.queue.insert(middle, val)\n\n def pushBack(self, val: int):\n self.queue.append(val)\n\n def popFront(self) -> int:\n if not self.queue:\n return -1\n return self.queue.pop(0)\n\n def popMiddle(self) -> int:\n if not self.queue:\n return -1\n middle = len(self.queue) // 2\n if len(self.queue) % 2 == 0:\n middle -= 1\n return self.queue.pop(middle)\n\n def popBack(self) -> int:\n if not self.queue:\n return -1\n return self.queue.pop()\n\n\n```
0
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
✅using list || python
design-front-middle-back-queue
0
1
\n# Code\n```\nclass FrontMiddleBackQueue:\n\n def __init__(self):\n self.q=[] \n\n def pushFront(self, val: int) -> None:\n self.q=[val]+self.q[:]\n\n def pushMiddle(self, val: int) -> None:\n i=(len(self.q))//2\n self.q=self.q[:i]+[val]+self.q[i:]\n\n def pushBack(self, val: int) -> None:\n self.q.append(val)\n\n def popFront(self) -> int:\n # print(self.q)\n if(len(self.q)>0):return self.q.pop(0)\n return -1\n\n def popMiddle(self) -> int:\n if(len(self.q)>0):return self.q.pop((len(self.q)-1)//2)\n return -1\n\n def popBack(self) -> int:\n if(len(self.q)>0):return self.q.pop()\n return -1\n \n\n\n# Your FrontMiddleBackQueue object will be instantiated and called as such:\n# obj = FrontMiddleBackQueue()\n# obj.pushFront(val)\n# obj.pushMiddle(val)\n# obj.pushBack(val)\n# param_4 = obj.popFront()\n# param_5 = obj.popMiddle()\n# param_6 = obj.popBack()\n```
0
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
[Python] LIS from Left and Right and Combine Result | Easy Understanding
minimum-number-of-removals-to-make-mountain-array
0
1
\n# Code\n```\nclass Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n N = len(nums)\n LIS = [1] * N\n LDS = [1] * N\n\n # Longest Increasing Subsequences from Left\n for i in range(N):\n for j in range(i):\n if nums[j] < nums[i]:\n LIS[i] = max(LIS[i], 1 + LIS[j])\n \n #Longest Increasing Subsequences from Right\n for i in range(N-1,-1,-1):\n for j in range(i+1, N):\n if nums[j] < nums[i]:\n LDS[i] = max(LDS[i], 1 + LDS[j])\n \n ans = 1000\n for a,b in zip(LIS, LDS):\n if a == 1 or b == 1: continue\n else: ans = min(ans, N - a - b + 1)\n return ans\n\n```
1
You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some index `i` (**0-indexed**) 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 - 1]` Given an integer array `nums`​​​, return _the **minimum** number of elements to remove to make_ `nums_​​​_` _a **mountain array**._ **Example 1:** **Input:** nums = \[1,3,1\] **Output:** 0 **Explanation:** The array itself is a mountain array so we do not need to remove any elements. **Example 2:** **Input:** nums = \[2,1,1,5,6,2,3,1\] **Output:** 3 **Explanation:** One solution is to remove the elements at indices 0, 1, and 5, making the array nums = \[1,5,6,3,1\]. **Constraints:** * `3 <= nums.length <= 1000` * `1 <= nums[i] <= 109` * It is guaranteed that you can make a mountain array out of `nums`.
null
[Python] LIS from Left and Right and Combine Result | Easy Understanding
minimum-number-of-removals-to-make-mountain-array
0
1
\n# Code\n```\nclass Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n N = len(nums)\n LIS = [1] * N\n LDS = [1] * N\n\n # Longest Increasing Subsequences from Left\n for i in range(N):\n for j in range(i):\n if nums[j] < nums[i]:\n LIS[i] = max(LIS[i], 1 + LIS[j])\n \n #Longest Increasing Subsequences from Right\n for i in range(N-1,-1,-1):\n for j in range(i+1, N):\n if nums[j] < nums[i]:\n LDS[i] = max(LDS[i], 1 + LDS[j])\n \n ans = 1000\n for a,b in zip(LIS, LDS):\n if a == 1 or b == 1: continue\n else: ans = min(ans, N - a - b + 1)\n return ans\n\n```
1
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 `edges`. Each `nums[i]` represents the `ith` node's value, and each `edges[j] = [uj, vj]` represents an edge between nodes `uj` and `vj` in the tree. Two values `x` and `y` are **coprime** if `gcd(x, y) == 1` where `gcd(x, y)` is the **greatest common divisor** of `x` and `y`. An ancestor of a node `i` is any other node on the shortest path from node `i` to the **root**. A node is **not** considered an ancestor of itself. Return _an array_ `ans` _of size_ `n`, _where_ `ans[i]` _is the closest ancestor to node_ `i` _such that_ `nums[i]` _and_ `nums[ans[i]]` are **coprime**, or `-1` _if there is no such ancestor_. **Example 1:** **Input:** nums = \[2,3,3,2\], edges = \[\[0,1\],\[1,2\],\[1,3\]\] **Output:** \[-1,0,0,1\] **Explanation:** In the above figure, each node's value is in parentheses. - Node 0 has no coprime ancestors. - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1). - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor. - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its closest valid ancestor. **Example 2:** **Input:** nums = \[5,6,10,2,3,6,15\], edges = \[\[0,1\],\[0,2\],\[1,3\],\[1,4\],\[2,5\],\[2,6\]\] **Output:** \[-1,0,-1,0,0,0,-1\] **Constraints:** * `nums.length == n` * `1 <= nums[i] <= 50` * `1 <= n <= 105` * `edges.length == n - 1` * `edges[j].length == 2` * `0 <= uj, vj < n` * `uj != vj`
Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence Think of LIS it's kind of close
cout << "Solution C++ and Python3" << endl;
richest-customer-wealth
0
1
# Solution in C++\n```\nclass Solution {\npublic:\n int maximumWealth(vector<vector<int>>& accounts) {\n int max = 0;\n int sum = 0;\n for (int i = 0; i < accounts.size(); i++ ){\n for (int j = 0; j < accounts.at(i).size(); j++){\n sum += accounts.at(i).at(j); \n }\n if (max < sum){max = sum;}\n sum = 0;\n }\n\n return max;\n }\n};\n```\n# Solution in Python3\n```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n answer = []\n for l in accounts:\n answer.append(sum(l))\n\n return max(answer)\n```
2
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. **Example 1:** **Input:** accounts = \[\[1,2,3\],\[3,2,1\]\] **Output:** 6 **Explanation****:** `1st customer has wealth = 1 + 2 + 3 = 6` `2nd customer has wealth = 3 + 2 + 1 = 6` Both customers are considered the richest with a wealth of 6 each, so return 6. **Example 2:** **Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\] **Output:** 10 **Explanation**: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. **Example 3:** **Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\] **Output:** 17 **Constraints:** * `m == accounts.length` * `n == accounts[i].length` * `1 <= m, n <= 50` * `1 <= accounts[i][j] <= 100`
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
cout << "Solution C++ and Python3" << endl;
richest-customer-wealth
0
1
# Solution in C++\n```\nclass Solution {\npublic:\n int maximumWealth(vector<vector<int>>& accounts) {\n int max = 0;\n int sum = 0;\n for (int i = 0; i < accounts.size(); i++ ){\n for (int j = 0; j < accounts.at(i).size(); j++){\n sum += accounts.at(i).at(j); \n }\n if (max < sum){max = sum;}\n sum = 0;\n }\n\n return max;\n }\n};\n```\n# Solution in Python3\n```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n answer = []\n for l in accounts:\n answer.append(sum(l))\n\n return max(answer)\n```
2
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
Python | 1-liner simple solution
richest-customer-wealth
0
1
```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n return max([sum(acc) for acc in accounts])\n```
192
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. **Example 1:** **Input:** accounts = \[\[1,2,3\],\[3,2,1\]\] **Output:** 6 **Explanation****:** `1st customer has wealth = 1 + 2 + 3 = 6` `2nd customer has wealth = 3 + 2 + 1 = 6` Both customers are considered the richest with a wealth of 6 each, so return 6. **Example 2:** **Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\] **Output:** 10 **Explanation**: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. **Example 3:** **Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\] **Output:** 17 **Constraints:** * `m == accounts.length` * `n == accounts[i].length` * `1 <= m, n <= 50` * `1 <= accounts[i][j] <= 100`
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
Python | 1-liner simple solution
richest-customer-wealth
0
1
```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n return max([sum(acc) for acc in accounts])\n```
192
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
solution for beginners
richest-customer-wealth
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)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n max_num = 0\n\n for item in accounts:\n summ = 0\n for i_num in item:\n summ += i_num\n if summ > max_num:\n max_num = summ\n return max_num\n```
2
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. **Example 1:** **Input:** accounts = \[\[1,2,3\],\[3,2,1\]\] **Output:** 6 **Explanation****:** `1st customer has wealth = 1 + 2 + 3 = 6` `2nd customer has wealth = 3 + 2 + 1 = 6` Both customers are considered the richest with a wealth of 6 each, so return 6. **Example 2:** **Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\] **Output:** 10 **Explanation**: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. **Example 3:** **Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\] **Output:** 17 **Constraints:** * `m == accounts.length` * `n == accounts[i].length` * `1 <= m, n <= 50` * `1 <= accounts[i][j] <= 100`
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
solution for beginners
richest-customer-wealth
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)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n max_num = 0\n\n for item in accounts:\n summ = 0\n for i_num in item:\n summ += i_num\n if summ > max_num:\n max_num = summ\n return max_num\n```
2
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
Simple and elegant result in Python3!
richest-customer-wealth
0
1
# Intuition\nSimple and elegant one-liner.\nHave a nice day!\n\n# Code\n```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n return max(map(sum, accounts))\n\n```
3
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. **Example 1:** **Input:** accounts = \[\[1,2,3\],\[3,2,1\]\] **Output:** 6 **Explanation****:** `1st customer has wealth = 1 + 2 + 3 = 6` `2nd customer has wealth = 3 + 2 + 1 = 6` Both customers are considered the richest with a wealth of 6 each, so return 6. **Example 2:** **Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\] **Output:** 10 **Explanation**: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. **Example 3:** **Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\] **Output:** 17 **Constraints:** * `m == accounts.length` * `n == accounts[i].length` * `1 <= m, n <= 50` * `1 <= accounts[i][j] <= 100`
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
Simple and elegant result in Python3!
richest-customer-wealth
0
1
# Intuition\nSimple and elegant one-liner.\nHave a nice day!\n\n# Code\n```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n return max(map(sum, accounts))\n\n```
3
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
Python 3 -> O(1) space. Simple solution with explanation
richest-customer-wealth
0
1
**Suggestions to make it better are always welcomed.**\n\nApproach:\n1. For every person, add his wealth from all the banks ie. for every row, sum all the column values and store in totalWealth.\n2. If totalWealth is more than maxWealth, then update maxWealth.\n\n```\ndef maximumWealth(self, accounts: List[List[int]]) -> int:\n\tmaxWealth = 0\n\tfor i in range(len(accounts)):\n\t\ttotalWealth = sum(accounts[i])\n\t\tmaxWealth = max(maxWealth, totalWealth)\n\treturn maxWealth\n```\n\n**I hope that you\'ve found this useful.\nIn that case, please upvote. It only motivates me to write more such posts\uD83D\uDE03**
146
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. **Example 1:** **Input:** accounts = \[\[1,2,3\],\[3,2,1\]\] **Output:** 6 **Explanation****:** `1st customer has wealth = 1 + 2 + 3 = 6` `2nd customer has wealth = 3 + 2 + 1 = 6` Both customers are considered the richest with a wealth of 6 each, so return 6. **Example 2:** **Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\] **Output:** 10 **Explanation**: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. **Example 3:** **Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\] **Output:** 17 **Constraints:** * `m == accounts.length` * `n == accounts[i].length` * `1 <= m, n <= 50` * `1 <= accounts[i][j] <= 100`
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
Python 3 -> O(1) space. Simple solution with explanation
richest-customer-wealth
0
1
**Suggestions to make it better are always welcomed.**\n\nApproach:\n1. For every person, add his wealth from all the banks ie. for every row, sum all the column values and store in totalWealth.\n2. If totalWealth is more than maxWealth, then update maxWealth.\n\n```\ndef maximumWealth(self, accounts: List[List[int]]) -> int:\n\tmaxWealth = 0\n\tfor i in range(len(accounts)):\n\t\ttotalWealth = sum(accounts[i])\n\t\tmaxWealth = max(maxWealth, totalWealth)\n\treturn maxWealth\n```\n\n**I hope that you\'ve found this useful.\nIn that case, please upvote. It only motivates me to write more such posts\uD83D\uDE03**
146
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
Python | Easy Solution✅
richest-customer-wealth
0
1
Solution 1:\n```\ndef maximumWealth(self, accounts: List[List[int]]) -> int:\n return max(map(sum,accounts))\n```\nSolution 2:\n```\ndef maximumWealth(self, accounts: List[List[int]]) -> int:\n large = 0\n for money in accounts:\n large = max(sum(money), large)\n return large\n```
7
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. **Example 1:** **Input:** accounts = \[\[1,2,3\],\[3,2,1\]\] **Output:** 6 **Explanation****:** `1st customer has wealth = 1 + 2 + 3 = 6` `2nd customer has wealth = 3 + 2 + 1 = 6` Both customers are considered the richest with a wealth of 6 each, so return 6. **Example 2:** **Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\] **Output:** 10 **Explanation**: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. **Example 3:** **Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\] **Output:** 17 **Constraints:** * `m == accounts.length` * `n == accounts[i].length` * `1 <= m, n <= 50` * `1 <= accounts[i][j] <= 100`
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
Python | Easy Solution✅
richest-customer-wealth
0
1
Solution 1:\n```\ndef maximumWealth(self, accounts: List[List[int]]) -> int:\n return max(map(sum,accounts))\n```\nSolution 2:\n```\ndef maximumWealth(self, accounts: List[List[int]]) -> int:\n large = 0\n for money in accounts:\n large = max(sum(money), large)\n return large\n```
7
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
Beats 97.25% #python3
richest-customer-wealth
0
1
\n\n# Approach\nAt first, sum the first user\'s wealth and store it to a variable.\nThen, traverse through the users and calculate their wealth and check if the wealth is greater than that variable assign it again or pass.\n\n\n# Code\n```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n m = sum(accounts[0])\n for i in accounts:\n m = max(m, sum(i))\n return m\n```
8
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. **Example 1:** **Input:** accounts = \[\[1,2,3\],\[3,2,1\]\] **Output:** 6 **Explanation****:** `1st customer has wealth = 1 + 2 + 3 = 6` `2nd customer has wealth = 3 + 2 + 1 = 6` Both customers are considered the richest with a wealth of 6 each, so return 6. **Example 2:** **Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\] **Output:** 10 **Explanation**: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. **Example 3:** **Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\] **Output:** 17 **Constraints:** * `m == accounts.length` * `n == accounts[i].length` * `1 <= m, n <= 50` * `1 <= accounts[i][j] <= 100`
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
Beats 97.25% #python3
richest-customer-wealth
0
1
\n\n# Approach\nAt first, sum the first user\'s wealth and store it to a variable.\nThen, traverse through the users and calculate their wealth and check if the wealth is greater than that variable assign it again or pass.\n\n\n# Code\n```\nclass Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n m = sum(accounts[0])\n for i in accounts:\n m = max(m, sum(i))\n return m\n```
8
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
✔️ [Python3] ONE-LINER, Explained
richest-customer-wealth
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nTwo simple steps: \n1. Iterate over accounts and for every account calculate the sum.\n2. Iterate over the resulting list and find the maximum.\n\nTime: **O(n)** - for scan\nSpace: **O(1)** - can be implemented without storing intermediate list of sums\n\n```\nreturn max(sum(acc) for acc in accounts)\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
54
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._ A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**. **Example 1:** **Input:** accounts = \[\[1,2,3\],\[3,2,1\]\] **Output:** 6 **Explanation****:** `1st customer has wealth = 1 + 2 + 3 = 6` `2nd customer has wealth = 3 + 2 + 1 = 6` Both customers are considered the richest with a wealth of 6 each, so return 6. **Example 2:** **Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\] **Output:** 10 **Explanation**: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. **Example 3:** **Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\] **Output:** 17 **Constraints:** * `m == accounts.length` * `n == accounts[i].length` * `1 <= m, n <= 50` * `1 <= accounts[i][j] <= 100`
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
✔️ [Python3] ONE-LINER, Explained
richest-customer-wealth
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nTwo simple steps: \n1. Iterate over accounts and for every account calculate the sum.\n2. Iterate over the resulting list and find the maximum.\n\nTime: **O(n)** - for scan\nSpace: **O(1)** - can be implemented without storing intermediate list of sums\n\n```\nreturn max(sum(acc) for acc in accounts)\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
54
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node. You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph. **Example 1:** **Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\] **Output:** 2 **Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center. **Example 2:** **Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\] **Output:** 1 **Constraints:** * `3 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * `ui != vi` * The given `edges` represent a valid star graph.
Calculate the wealth of each customer Find the maximum element in array.
Python 3 approach with detailed explanation , algorithm and dry run using Monotonic Stack.
find-the-most-competitive-subsequence
0
1
# Intuition\nHere, we take into consideration, the concept that, whether we will have enough surplus elements to add in the result(stack), if we pop/remove the current element from the result(stack).\n\n# Approach\nALGORITHM - \n \n 1. Initialize the \'stack\' and a variable \'stack_len\' to keep track \n of its length.\n 2. Let \'n\' denote the length of the \'nums\' array.\n 3. Start a loop from 0 to n:\n a. remove elements from stack and decrement the stack_len by 1\n i. till stack is not empty and \n ii. top element of stack is greater than the current element and\n iii. {Important part} the count of surplus elements in the nums list\n is greater than or equal to the remaining space in the stack, \n i.e. \'k-stack_len\'\n b. Then check is stack_len < k, then add the element to the stack\n and increment the stack_len by 1\n 4. return stack\n \n\nDRY RUN - \n\n Let,\n nums = [2,4,3,3,5,4,9,1]\n k = 4\n \n Initially, \n \n i stack stack_len nums[i]\n \n 0 [ ] 0 2\n \n While Loop will run till stack!=[], but here, stack==[] so it will come \n out of the loop \n AND\n stack_len (0) < k (4) \n so, nums[i] (2) will be added in the stack\n \n 1 [2] 1 4\n\n While Loop will run till stack!=[] and stack.top() > nums[i], \n but here, stack_top() (2) < nums[i] (4) so it will come \n out of the loop \n AND\n stack_len (1) < k (4) \n so, nums[i] (4) will be added in the stack\n \n 2 [2,4] 2 3\n\n While Loop will run till stack!=[] and stack.top() > nums[i],\n as stack.top() (4) > 3 therefore,\n {IMPORTANT}\n Here, Before removing stack_top() i.e, 4 It will check, if there \n are enought surplus elements in the nums array, to fill the \n condition of \'k\' values by checking the condition:\n \n n-i-1>=k-stack_len\n \n here, n = 8, i = 2, k = 4, stack_len = 2\n \n so, 8-2-1 >= 4-2 ,i.e., 5>=2, It means we have a total of \n 5 elements in surplus, which can fill the stack, as we only \n need 2 more elements to fill the stack\n \n Therefore, we will pop the element stack.top(), i.e., 4\n and Update the stack_len as - \n \n stack_len -= 1\n \n Therefore, updated stack_len = 1\n \n We keep on doing the same till the above conditions hold True\n \n \n here, after removing 4, stack = [2] and stack_top (2) < nums[i], \n therefore it will come out of the loop \n AND\n stack_len (1) < k (4) \n so, nums[i] (3) will be added in the stack \n\n 3 [2,3] 2 3 \n\n While Loop will run till stack!=[] and stack.top() > nums[i], \n but here, stack_top() (3) == nums[i] (3) so it will come \n out of the loop \n AND\n stack_len (2) < k (4) \n so, nums[i] (3) will be added in the stack\n \n 4 [2,3,3] 3 5\n\n While Loop will run till stack!=[] and stack.top() > nums[i], \n but here, stack_top() (3) < nums[i] (5) so it will come \n out of the loop \n AND\n stack_len (3) < k (4) \n so, nums[i] (5) will be added in the stack\n \n 5 [2,3,3,5] 4 4\n\n While Loop will run till stack!=[] and stack.top() > nums[i],\n as stack.top() (5) > 4 therefore,\n {IMPORTANT}\n Here, Before removing stack_top() i.e, 5 It will check, if there \n are enought surplus elements in the nums array, to fill the \n condition of \'k\' values by checking the condition:\n \n n-i-1>=k-stack_len\n \n here, n = 8, i = 5, k = 4, stack_len = 4\n \n so, 8-5-1 >= 4-4 ,i.e., 2>=0, It means we have a total of \n 2 elements in surplus, which can fill the stack, as now we dont\n have emought space to just add a new element, i.e., We can only \n remove an element, in order to update the result(stack)\n \n Therefore, we will pop the element stack.top(), i.e., 5\n and Update the stack_len as - \n \n stack_len -= 1\n \n Therefore, updated stack_len = 3\n \n We keep on doing the same till the above conditions hold True\n \n here, after removing 5, stack = [2,3,3] and stack_top (3) < nums[i] (4), \n therefore it will come out of the loop \n AND\n stack_len (3) < k (4) \n so, nums[i] (4) will be added in the stack \n\n 6 [2,3,3,4] 4 9\n\n While Loop will run till stack!=[] and stack.top() > nums[i], \n but here, stack_top() (4) < nums[i] (9) so it will come \n out of the loop \n AND\n as, stack_len (4) == k (4) \n so, nums[i] (9) will NOT be added in the stack\n\n 7 [2,3,3,4] 4 1\n\n While Loop will run till stack!=[] and stack.top() > nums[i],\n as stack.top() (4) > 1 therefore,\n {IMPORTANT}\n Here, Before removing stack_top() i.e, 4 It will check, if there \n are enought surplus elements in the nums array, to fill the \n condition of \'k\' values by checking the condition:\n \n n-i-1>=k-stack_len\n \n here, n = 8, i = 7, k = 4, stack_len = 4\n \n so, 8-7-1 >= 4-4 ,i.e., 0==0, It means we don\'t have more\n elements in surplus, which can fill the stack, and also we dont\n have emought space to just add a new element, i.e., We can only \n remove one element, in order to update the result(stack)\n \n Therefore, we will pop the element stack.top(), i.e., 4\n and Update the stack_len as - \n \n stack_len -= 1\n \n Therefore, updated stack_len = 3\n \n \n Now our stack = [2,3,3], \n We will check if stack!=[] and stack.top() (3) > nums[i] (1) \n and at the end... \n Whether we have enought surplus elements to fill the remaining\n space of the result(stack)\n as- \n \n n = 8, i = 7, k = 4, stack_len = 3\n \n if n-i-1>=k-stack_len := 8-7-1>=4-3 \n := 0>=1 i.e., This condition is False\n \n It means, We have no more surplus element in the nums\n array, But If we replace the current stack.top(), then \n we will need 1 more element to meet the \'k\' elements \n condition. Therefore, We will not remove the current \n stack.top() and come out of the loop\n \n \n here, after removing 4 and after exiting the loop, \n stack = [2,3,3] and stack_len = 3 \n AND \n as, stack_len (3) < k (4) \n so, nums[i] (1) will be added in the stack\n\n \n Therefore, at the end, The final values will be-\n \n stack = [2,3,3,1], stack_len = 4\n \n AND we will return this \'stack\' as the result.\n\n\n In Summary, The flow of Values goes as - \n \n i stack stack_len nums[i]\n \n 0 [ ] 0 2\n 1 [2] 1 4\n 2 [2,4] 2 3\n 3 [2,3] 2 3\n 4 [2,3,3] 3 5\n 5 [2,3,3,5] 4 4\n 6 [2,3,3,4] 4 9\n 7 [2,3,3,4] 4 1\n \n FINAL\n \n stack = [2,3,3,1]\n stack_len = 4\n\nEXERCISE -\n\n Try to dry run on the following example, to better understand \n the approach.\n\n nums = [9,1,2,5,8,3]\n k = 4\n\n It\'s answer is [1,2,5,3]\n\n\n# Complexity\n- Time complexity:\n I might be wrong, but the Time complexity will be\n O(N+k) ~ O(N)\n As, The main loop runs in O(N) and , the inner while loop \n runs only for some few iterations with worst case of O(k)\n\n\n- Space complexity:\n Space complexity, will be \n O(k)\n As, we are using a stack of length \'k\'\n\n# Code\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = []\n stack_len = 0\n n = len(nums)\n for i in range(n):\n while stack and stack[-1]>nums[i] and n-i-1>=k-stack_len:\n stack.pop(-1)\n stack_len-=1\n if stack_len<k:\n stack+=[nums[i]]\n stack_len+=1\n \n return stack\n```
12
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
Python 3 approach with detailed explanation , algorithm and dry run using Monotonic Stack.
find-the-most-competitive-subsequence
0
1
# Intuition\nHere, we take into consideration, the concept that, whether we will have enough surplus elements to add in the result(stack), if we pop/remove the current element from the result(stack).\n\n# Approach\nALGORITHM - \n \n 1. Initialize the \'stack\' and a variable \'stack_len\' to keep track \n of its length.\n 2. Let \'n\' denote the length of the \'nums\' array.\n 3. Start a loop from 0 to n:\n a. remove elements from stack and decrement the stack_len by 1\n i. till stack is not empty and \n ii. top element of stack is greater than the current element and\n iii. {Important part} the count of surplus elements in the nums list\n is greater than or equal to the remaining space in the stack, \n i.e. \'k-stack_len\'\n b. Then check is stack_len < k, then add the element to the stack\n and increment the stack_len by 1\n 4. return stack\n \n\nDRY RUN - \n\n Let,\n nums = [2,4,3,3,5,4,9,1]\n k = 4\n \n Initially, \n \n i stack stack_len nums[i]\n \n 0 [ ] 0 2\n \n While Loop will run till stack!=[], but here, stack==[] so it will come \n out of the loop \n AND\n stack_len (0) < k (4) \n so, nums[i] (2) will be added in the stack\n \n 1 [2] 1 4\n\n While Loop will run till stack!=[] and stack.top() > nums[i], \n but here, stack_top() (2) < nums[i] (4) so it will come \n out of the loop \n AND\n stack_len (1) < k (4) \n so, nums[i] (4) will be added in the stack\n \n 2 [2,4] 2 3\n\n While Loop will run till stack!=[] and stack.top() > nums[i],\n as stack.top() (4) > 3 therefore,\n {IMPORTANT}\n Here, Before removing stack_top() i.e, 4 It will check, if there \n are enought surplus elements in the nums array, to fill the \n condition of \'k\' values by checking the condition:\n \n n-i-1>=k-stack_len\n \n here, n = 8, i = 2, k = 4, stack_len = 2\n \n so, 8-2-1 >= 4-2 ,i.e., 5>=2, It means we have a total of \n 5 elements in surplus, which can fill the stack, as we only \n need 2 more elements to fill the stack\n \n Therefore, we will pop the element stack.top(), i.e., 4\n and Update the stack_len as - \n \n stack_len -= 1\n \n Therefore, updated stack_len = 1\n \n We keep on doing the same till the above conditions hold True\n \n \n here, after removing 4, stack = [2] and stack_top (2) < nums[i], \n therefore it will come out of the loop \n AND\n stack_len (1) < k (4) \n so, nums[i] (3) will be added in the stack \n\n 3 [2,3] 2 3 \n\n While Loop will run till stack!=[] and stack.top() > nums[i], \n but here, stack_top() (3) == nums[i] (3) so it will come \n out of the loop \n AND\n stack_len (2) < k (4) \n so, nums[i] (3) will be added in the stack\n \n 4 [2,3,3] 3 5\n\n While Loop will run till stack!=[] and stack.top() > nums[i], \n but here, stack_top() (3) < nums[i] (5) so it will come \n out of the loop \n AND\n stack_len (3) < k (4) \n so, nums[i] (5) will be added in the stack\n \n 5 [2,3,3,5] 4 4\n\n While Loop will run till stack!=[] and stack.top() > nums[i],\n as stack.top() (5) > 4 therefore,\n {IMPORTANT}\n Here, Before removing stack_top() i.e, 5 It will check, if there \n are enought surplus elements in the nums array, to fill the \n condition of \'k\' values by checking the condition:\n \n n-i-1>=k-stack_len\n \n here, n = 8, i = 5, k = 4, stack_len = 4\n \n so, 8-5-1 >= 4-4 ,i.e., 2>=0, It means we have a total of \n 2 elements in surplus, which can fill the stack, as now we dont\n have emought space to just add a new element, i.e., We can only \n remove an element, in order to update the result(stack)\n \n Therefore, we will pop the element stack.top(), i.e., 5\n and Update the stack_len as - \n \n stack_len -= 1\n \n Therefore, updated stack_len = 3\n \n We keep on doing the same till the above conditions hold True\n \n here, after removing 5, stack = [2,3,3] and stack_top (3) < nums[i] (4), \n therefore it will come out of the loop \n AND\n stack_len (3) < k (4) \n so, nums[i] (4) will be added in the stack \n\n 6 [2,3,3,4] 4 9\n\n While Loop will run till stack!=[] and stack.top() > nums[i], \n but here, stack_top() (4) < nums[i] (9) so it will come \n out of the loop \n AND\n as, stack_len (4) == k (4) \n so, nums[i] (9) will NOT be added in the stack\n\n 7 [2,3,3,4] 4 1\n\n While Loop will run till stack!=[] and stack.top() > nums[i],\n as stack.top() (4) > 1 therefore,\n {IMPORTANT}\n Here, Before removing stack_top() i.e, 4 It will check, if there \n are enought surplus elements in the nums array, to fill the \n condition of \'k\' values by checking the condition:\n \n n-i-1>=k-stack_len\n \n here, n = 8, i = 7, k = 4, stack_len = 4\n \n so, 8-7-1 >= 4-4 ,i.e., 0==0, It means we don\'t have more\n elements in surplus, which can fill the stack, and also we dont\n have emought space to just add a new element, i.e., We can only \n remove one element, in order to update the result(stack)\n \n Therefore, we will pop the element stack.top(), i.e., 4\n and Update the stack_len as - \n \n stack_len -= 1\n \n Therefore, updated stack_len = 3\n \n \n Now our stack = [2,3,3], \n We will check if stack!=[] and stack.top() (3) > nums[i] (1) \n and at the end... \n Whether we have enought surplus elements to fill the remaining\n space of the result(stack)\n as- \n \n n = 8, i = 7, k = 4, stack_len = 3\n \n if n-i-1>=k-stack_len := 8-7-1>=4-3 \n := 0>=1 i.e., This condition is False\n \n It means, We have no more surplus element in the nums\n array, But If we replace the current stack.top(), then \n we will need 1 more element to meet the \'k\' elements \n condition. Therefore, We will not remove the current \n stack.top() and come out of the loop\n \n \n here, after removing 4 and after exiting the loop, \n stack = [2,3,3] and stack_len = 3 \n AND \n as, stack_len (3) < k (4) \n so, nums[i] (1) will be added in the stack\n\n \n Therefore, at the end, The final values will be-\n \n stack = [2,3,3,1], stack_len = 4\n \n AND we will return this \'stack\' as the result.\n\n\n In Summary, The flow of Values goes as - \n \n i stack stack_len nums[i]\n \n 0 [ ] 0 2\n 1 [2] 1 4\n 2 [2,4] 2 3\n 3 [2,3] 2 3\n 4 [2,3,3] 3 5\n 5 [2,3,3,5] 4 4\n 6 [2,3,3,4] 4 9\n 7 [2,3,3,4] 4 1\n \n FINAL\n \n stack = [2,3,3,1]\n stack_len = 4\n\nEXERCISE -\n\n Try to dry run on the following example, to better understand \n the approach.\n\n nums = [9,1,2,5,8,3]\n k = 4\n\n It\'s answer is [1,2,5,3]\n\n\n# Complexity\n- Time complexity:\n I might be wrong, but the Time complexity will be\n O(N+k) ~ O(N)\n As, The main loop runs in O(N) and , the inner while loop \n runs only for some few iterations with worst case of O(k)\n\n\n- Space complexity:\n Space complexity, will be \n O(k)\n As, we are using a stack of length \'k\'\n\n# Code\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = []\n stack_len = 0\n n = len(nums)\n for i in range(n):\n while stack and stack[-1]>nums[i] and n-i-1>=k-stack_len:\n stack.pop(-1)\n stack_len-=1\n if stack_len<k:\n stack+=[nums[i]]\n stack_len+=1\n \n return stack\n```
12
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
Python3, monotonic stack
find-the-most-competitive-subsequence
0
1
# Intuition\nInitially I thought its going to be a LIS problem but optimized LIS requires binary search and this might be an overkill for the problem\nIn discussion section someone mentioned lexicographically smallest subsequence and I recall this problem [1081](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/). Immideately in my mind popped up `monotonic stack` with a core property to keep increasing/decreasing subsequences in O(N)\n\nThe last piece of the puzzle was to come up with the formula `k-len(q) < n-i` to stop popping up elements from a stack when there\'s left less elements than `k`\n\nConsider this test case:\nAt processing `2` stack will be `[8,80]` it means all elements will be popped-up and only `[2]` is left if not to prevent it:\n````\n[71,18,52,29,55,73,24,42,66,8,80,2]\n3\n````\nExpected answer: `[8,80,2]`\n\n# Approach\nMonotonic queue\n\n# Complexity\nO(N), monotonic queue uses every element only once\n\n# Space complexity:\nO(N) for an answer\n\n# Code\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n \n n,q = len(nums),[]\n for i,num in enumerate(nums):\n while q and q[-1] > num and k-len(q) < n-i:\n q.pop()\n q.append(num)\n \n while len(q) > k:\n q.pop()\n \n return q\n```\n\nMy current intuition behind monotonic stack is based on solved before problems in the order:\nhttps://leetcode.com/problems/remove-k-digits/\nhttps://leetcode.com/problems/next-greater-element-ii/\nhttps://leetcode.com/problems/next-greater-element-i/\nhttps://leetcode.com/problems/sum-of-subarray-minimums/\nhttps://leetcode.com/problems/sum-of-subarray-ranges/\nhttps://leetcode.com/problems/largest-rectangle-in-histogram/\n\n
2
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
Python3, monotonic stack
find-the-most-competitive-subsequence
0
1
# Intuition\nInitially I thought its going to be a LIS problem but optimized LIS requires binary search and this might be an overkill for the problem\nIn discussion section someone mentioned lexicographically smallest subsequence and I recall this problem [1081](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/). Immideately in my mind popped up `monotonic stack` with a core property to keep increasing/decreasing subsequences in O(N)\n\nThe last piece of the puzzle was to come up with the formula `k-len(q) < n-i` to stop popping up elements from a stack when there\'s left less elements than `k`\n\nConsider this test case:\nAt processing `2` stack will be `[8,80]` it means all elements will be popped-up and only `[2]` is left if not to prevent it:\n````\n[71,18,52,29,55,73,24,42,66,8,80,2]\n3\n````\nExpected answer: `[8,80,2]`\n\n# Approach\nMonotonic queue\n\n# Complexity\nO(N), monotonic queue uses every element only once\n\n# Space complexity:\nO(N) for an answer\n\n# Code\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n \n n,q = len(nums),[]\n for i,num in enumerate(nums):\n while q and q[-1] > num and k-len(q) < n-i:\n q.pop()\n q.append(num)\n \n while len(q) > k:\n q.pop()\n \n return q\n```\n\nMy current intuition behind monotonic stack is based on solved before problems in the order:\nhttps://leetcode.com/problems/remove-k-digits/\nhttps://leetcode.com/problems/next-greater-element-ii/\nhttps://leetcode.com/problems/next-greater-element-i/\nhttps://leetcode.com/problems/sum-of-subarray-minimums/\nhttps://leetcode.com/problems/sum-of-subarray-ranges/\nhttps://leetcode.com/problems/largest-rectangle-in-histogram/\n\n
2
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
Easy peasy python solution
find-the-most-competitive-subsequence
0
1
\n```\ndef mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n st = []\n for idx, num in enumerate(nums):\n if not st:\n st.append(num)\n else:\n # pop element from st if last element is greater than the current element\n # and also I have enough elements left such that I can have list of size k\n while st and st[-1] > num and (len(st)-1 + len(nums)-idx >= k):\n st.pop()\n if len(st) < k:\n st.append(num)\n return st
14
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
Easy peasy python solution
find-the-most-competitive-subsequence
0
1
\n```\ndef mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n st = []\n for idx, num in enumerate(nums):\n if not st:\n st.append(num)\n else:\n # pop element from st if last element is greater than the current element\n # and also I have enough elements left such that I can have list of size k\n while st and st[-1] > num and (len(st)-1 + len(nums)-idx >= k):\n st.pop()\n if len(st) < k:\n st.append(num)\n return st
14
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
[Python3] greedy O(N)
find-the-most-competitive-subsequence
0
1
**Approach 1** - stack `O(N)`\nHere, we maintain an increasing mono-stack. The trick is that there is a capacity constraint of `k`. You are only allowed to pop out of the stack if the sum of elements on stack `len(stack)` and remaining elements in `nums` (`len(nums) - i`) is more than enough for `k`. \n\nImplementation (`O(N)` time & `O(N)` space)\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = [] # (increasing) mono-stack \n for i, x in enumerate(nums): \n while stack and stack[-1] > x and len(stack) + len(nums) - i > k: stack.pop()\n if len(stack) < k: stack.append(x)\n return stack \n```\n\n**Approach 2** - priority queue `O(NlogN)`\nThis is my original approach which utilizes priority queue. The idea is similar to that of Approach 1, but the reletive order is managed via a priority queue. \n\nImplementation (`O(NlogN)` time & `O(N)` space)\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n ans, pq = [], []\n prev = -inf \n for i, x in enumerate(nums): \n heappush(pq, (x, i))\n if i+k >= len(nums): \n while pq and pq[0][1] < prev: heappop(pq)\n x, prev = heappop(pq)\n ans.append(x)\n return ans \n```
6
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
[Python3] greedy O(N)
find-the-most-competitive-subsequence
0
1
**Approach 1** - stack `O(N)`\nHere, we maintain an increasing mono-stack. The trick is that there is a capacity constraint of `k`. You are only allowed to pop out of the stack if the sum of elements on stack `len(stack)` and remaining elements in `nums` (`len(nums) - i`) is more than enough for `k`. \n\nImplementation (`O(N)` time & `O(N)` space)\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = [] # (increasing) mono-stack \n for i, x in enumerate(nums): \n while stack and stack[-1] > x and len(stack) + len(nums) - i > k: stack.pop()\n if len(stack) < k: stack.append(x)\n return stack \n```\n\n**Approach 2** - priority queue `O(NlogN)`\nThis is my original approach which utilizes priority queue. The idea is similar to that of Approach 1, but the reletive order is managed via a priority queue. \n\nImplementation (`O(NlogN)` time & `O(N)` space)\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n ans, pq = [], []\n prev = -inf \n for i, x in enumerate(nums): \n heappush(pq, (x, i))\n if i+k >= len(nums): \n while pq and pq[0][1] < prev: heappop(pq)\n x, prev = heappop(pq)\n ans.append(x)\n return ans \n```
6
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
python3: easy to understand
find-the-most-competitive-subsequence
0
1
Very silimar to [**Monotonous Stack**](https://labuladong.gitbook.io/algo-en/ii.-data-structure/monotonicstack)\n\nWe should maintance a decreasing monotone stack from top to botom, so we should choose the numbers as small as possible into the stack. \nFor example: \nnums = [3,5,2,6,8], k = 2\nstep1: stack = [3] `append(3)`\nstep2: stack = [3,5] since 5 > 3 `append(5)`\nstep3: stack = [3] since 2<5 and `pop()`\nstep4: stack = [] since 2<3 and `pop()`\nstep5: stack = [2] `append(2)`\nstep6: stack = [2,6] since 6>2 `append(6)`\nstep7: stack = [2,6,8] since 8>6 `append(8)`\nThe answer is stack[:2] = [2,6]\n\n**However**, the numbers in stack cannot be less than k. \nWhen **len(stack)+len(nums)-i <= k**, it means we have no choice but choose all the numbers left in the list into stack. \nFor example:\nnums = [71,18,66,8,80,2], k = 3\nstep1: stack = [71] `append(71)`\nstep2: stack = [18] since 18< 71 `pop()` and `append(18)`\nstep3: stack = [18, 66] since 66>18 `append(66)`\nstep4: stack = [18] since 8<66 and `pop()`\nstep5: stack = [] since 8<18 and `pop()`\nstep6: stack = [8] `append(8)`\nstep7: stack = [8, 80] since 80>8 `append(80)`\nstep8: stack = [8] since 2<80 and `pop()`\nstep9: stack = [] since 2<8 and `pop()`\nstep10: stack = [2] `append(2)`\nOutput: stack = [2]\nThis is a **Wrong** answer as the` len(output)` must be k\nIn step8, i = 5 and len(stack)+len(nums)-i == k, so we should not pop anything but just append 2 into stack\nstep9: stack = [8,80,2] `append(2)`\nThe answer is stack[:3] = [8,80,2]\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = []\n for i in range(len(nums)):\n while stack and len(stack)+len(nums)-i>k and stack[-1] > nums[i]:\n stack.pop()\n stack.append(nums[i])\n return stack[:k]\n```
5
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
python3: easy to understand
find-the-most-competitive-subsequence
0
1
Very silimar to [**Monotonous Stack**](https://labuladong.gitbook.io/algo-en/ii.-data-structure/monotonicstack)\n\nWe should maintance a decreasing monotone stack from top to botom, so we should choose the numbers as small as possible into the stack. \nFor example: \nnums = [3,5,2,6,8], k = 2\nstep1: stack = [3] `append(3)`\nstep2: stack = [3,5] since 5 > 3 `append(5)`\nstep3: stack = [3] since 2<5 and `pop()`\nstep4: stack = [] since 2<3 and `pop()`\nstep5: stack = [2] `append(2)`\nstep6: stack = [2,6] since 6>2 `append(6)`\nstep7: stack = [2,6,8] since 8>6 `append(8)`\nThe answer is stack[:2] = [2,6]\n\n**However**, the numbers in stack cannot be less than k. \nWhen **len(stack)+len(nums)-i <= k**, it means we have no choice but choose all the numbers left in the list into stack. \nFor example:\nnums = [71,18,66,8,80,2], k = 3\nstep1: stack = [71] `append(71)`\nstep2: stack = [18] since 18< 71 `pop()` and `append(18)`\nstep3: stack = [18, 66] since 66>18 `append(66)`\nstep4: stack = [18] since 8<66 and `pop()`\nstep5: stack = [] since 8<18 and `pop()`\nstep6: stack = [8] `append(8)`\nstep7: stack = [8, 80] since 80>8 `append(80)`\nstep8: stack = [8] since 2<80 and `pop()`\nstep9: stack = [] since 2<8 and `pop()`\nstep10: stack = [2] `append(2)`\nOutput: stack = [2]\nThis is a **Wrong** answer as the` len(output)` must be k\nIn step8, i = 5 and len(stack)+len(nums)-i == k, so we should not pop anything but just append 2 into stack\nstep9: stack = [8,80,2] `append(2)`\nThe answer is stack[:3] = [8,80,2]\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = []\n for i in range(len(nums)):\n while stack and len(stack)+len(nums)-i>k and stack[-1] > nums[i]:\n stack.pop()\n stack.append(nums[i])\n return stack[:k]\n```
5
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
Python. clear & cool solution. O(n). Using stack
find-the-most-competitive-subsequence
0
1
\tclass Solution:\n\t\tdef mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n\t\t\tend = len(nums) - k\n\t\t\tans = []\n\t\t\tfor num in nums:\n\t\t\t\twhile end and ans and num < ans[-1] :\n\t\t\t\t\tans.pop()\n\t\t\t\t\tend -= 1\n\t\t\t\tans.append(num)\n\t\t\t\n\t\t\treturn ans[:k]
8
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
Python. clear & cool solution. O(n). Using stack
find-the-most-competitive-subsequence
0
1
\tclass Solution:\n\t\tdef mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n\t\t\tend = len(nums) - k\n\t\t\tans = []\n\t\t\tfor num in nums:\n\t\t\t\twhile end and ans and num < ans[-1] :\n\t\t\t\t\tans.pop()\n\t\t\t\t\tend -= 1\n\t\t\t\tans.append(num)\n\t\t\t\n\t\t\treturn ans[:k]
8
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
Monotonic stack + condition on subsequence length
find-the-most-competitive-subsequence
0
1
# Intuition\nWe can use the greedy approach and to keep at the begenning of the subsequence the smallest elements, as long as we have enough elements left.\n\n# Approach\nUse monotonic stack and keep track of the length of subsequence. You should break the invariant of monotonic non-decrease when you have just enough elements to return the subsequence of the desired length.\n\n# Complexity\n- Time complexity:\nO(n), where n is the number of elements. Each element is added and removed from the stack only once, thus O(2n), which is O(n).\n\n- Space complexity:\nO(n), where n is the number of elements\n\n# Code\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = []\n L = len(nums)\n for i, n in enumerate(nums):\n #follow the monotonic requirement and check that the amount of elements in a stack plus elements left in the initial array is bigger than k.\n while stack and n<stack[-1] and len(stack)+(L-i)>k:\n stack.pop()\n stack.append(n) \n #return k first elements (as for poping we require the break of the monotonic increase)\n return stack[:k]\n \n```
0
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
Monotonic stack + condition on subsequence length
find-the-most-competitive-subsequence
0
1
# Intuition\nWe can use the greedy approach and to keep at the begenning of the subsequence the smallest elements, as long as we have enough elements left.\n\n# Approach\nUse monotonic stack and keep track of the length of subsequence. You should break the invariant of monotonic non-decrease when you have just enough elements to return the subsequence of the desired length.\n\n# Complexity\n- Time complexity:\nO(n), where n is the number of elements. Each element is added and removed from the stack only once, thus O(2n), which is O(n).\n\n- Space complexity:\nO(n), where n is the number of elements\n\n# Code\n```\nclass Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = []\n L = len(nums)\n for i, n in enumerate(nums):\n #follow the monotonic requirement and check that the amount of elements in a stack plus elements left in the initial array is bigger than k.\n while stack and n<stack[-1] and len(stack)+(L-i)>k:\n stack.pop()\n stack.append(n) \n #return k first elements (as for poping we require the break of the monotonic increase)\n return stack[:k]\n \n```
0
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
Very easy Python solution with detailed expanation
minimum-moves-to-make-array-complementary
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs other solution describe:\nIf `x + y = T`, the cost is 0.\nIf `min(x, y) + 1 > T`, the cost is 2 -- we need to decrease both x and y.\nIf `max(x, y) + limit < T`, the cost is 2 -- we need to increase both x and y.\nOtherwise the cost is 1.\n\n# Approach\nNow let\'s keep track of intervals of targets where cost is 1 for each number, also we keep track of targets which make the cost 0 for each of the given pair of numbers. \nThan cost for each target should be: \n```\nN (at most we change all numbers) - (number intervals which decrease the cost by 1 each) - (number of zero_moves for this target)\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe traverse 2 times, so time complexity N\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nwe store 3 dictionaries of N each -> space complexity is also N\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n starts, ends, zero_moves = defaultdict(int), defaultdict(int), defaultdict(int)\n N = len(nums)\n for i in range(N // 2):\n x, y = nums[i], nums[N-i-1]\n starts[min(x, y)+1] += 1\n ends[max(x,y)+limit] += 1\n zero_moves[x+y] += 1\n result = float(\'inf\')\n intervals = 0\n for target in range(2, 2*limit+1):\n intervals += starts[target]\n cost = N - intervals - zero_moves[target]\n result = min(cost, result)\n intervals -= ends[target]\n return result\n```
3
You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive. The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same number. For example, the array `[1,2,3,4]` is complementary because for all indices `i`, `nums[i] + nums[n - 1 - i] = 5`. Return the _**minimum** number of moves required to make_ `nums` _**complementary**_. **Example 1:** **Input:** nums = \[1,2,4,3\], limit = 4 **Output:** 1 **Explanation:** In 1 move, you can change nums to \[1,2,2,3\] (underlined elements are changed). nums\[0\] + nums\[3\] = 1 + 3 = 4. nums\[1\] + nums\[2\] = 2 + 2 = 4. nums\[2\] + nums\[1\] = 2 + 2 = 4. nums\[3\] + nums\[0\] = 3 + 1 = 4. Therefore, nums\[i\] + nums\[n-1-i\] = 4 for every i, so nums is complementary. **Example 2:** **Input:** nums = \[1,2,2,1\], limit = 2 **Output:** 2 **Explanation:** In 2 moves, you can change nums to \[2,2,2,2\]. You cannot change any number to 3 since 3 > limit. **Example 3:** **Input:** nums = \[1,2,1,2\], limit = 2 **Output:** 0 **Explanation:** nums is already complementary. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `1 <= nums[i] <= limit <= 105` * `n` is even.
Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?
Very easy Python solution with detailed expanation
minimum-moves-to-make-array-complementary
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs other solution describe:\nIf `x + y = T`, the cost is 0.\nIf `min(x, y) + 1 > T`, the cost is 2 -- we need to decrease both x and y.\nIf `max(x, y) + limit < T`, the cost is 2 -- we need to increase both x and y.\nOtherwise the cost is 1.\n\n# Approach\nNow let\'s keep track of intervals of targets where cost is 1 for each number, also we keep track of targets which make the cost 0 for each of the given pair of numbers. \nThan cost for each target should be: \n```\nN (at most we change all numbers) - (number intervals which decrease the cost by 1 each) - (number of zero_moves for this target)\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe traverse 2 times, so time complexity N\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nwe store 3 dictionaries of N each -> space complexity is also N\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n starts, ends, zero_moves = defaultdict(int), defaultdict(int), defaultdict(int)\n N = len(nums)\n for i in range(N // 2):\n x, y = nums[i], nums[N-i-1]\n starts[min(x, y)+1] += 1\n ends[max(x,y)+limit] += 1\n zero_moves[x+y] += 1\n result = float(\'inf\')\n intervals = 0\n for target in range(2, 2*limit+1):\n intervals += starts[target]\n cost = N - intervals - zero_moves[target]\n result = min(cost, result)\n intervals -= ends[target]\n return result\n```
3
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Sweep Algorithm | Explained [Python]
minimum-moves-to-make-array-complementary
0
1
Let\'s start with a few observations:\n1. Let\'s say x = target number (sum for each complimentary numbers) => We need to change complimentary values to achieve this target\n2. The min target number achievable is 2 \n\t* 1 <= nums[i] <= limit <= 105\n\t* so either the nums[i] already equal to 1 each or we replace them by 1\n3. The max target number achievable is 2 * limit\n\t* \tWe replace both complimentary values by **limit**\n\nNow the problem is to find an optimal target which would minimize total number of moves. For, each complimentary numbers \n1) we could either make 0 move and achieve the target = nums[i] + nums[n-1-i]\n2) or, make one move and achieve a target range of [min(nums[i], nums[n-1-i]) + 1, max(nums[i], nums[n-1-i] + limit]\n\t* lower limit -> change max(nums[i], nums[n-1-i]) to 1 -> target would be min(nums[i], nums[n-1-i]) + 1\n\t* upper limit -> change min(nums[i], nums[n-1-i] to limit -> target would be max(nums[i], nums[n-1-i] + limit\n3) Make two moves and achieve a target range of \n\t* [2, min(nums[i], nums[n-1-i]) + 1) \n\t* or, (max(nums[i], nums[n-1-i] + limit, 2*limit]\n\nLet\'s say our array was [1,2,4,3] and limit = 4\n -> possible target sum would be 2 to 2* limit (2-8)\n -> first complimentary pair would be (1,3). And the number of moves to achieve the corresponding target would be as follows\n\n\t\tnum_moves: 1 1 0 1 1 1 2 \n\t\ttarget: 2 3 4 5 6 7 8 \n\n -> second complimentary pair would be (2,4) index = (1,2):\n\n\t\tnum_moves: 2 1 1 1 0 1 1 \n\t\ttarget: 2 3 4 5 6 7 8 \n\nAs we can see we can make a minimum total moves = 1 by either achieving a target of 4 ( make a change in second complimentary pair) or a target of 6 (make a change in first complimentary pair)\n\nSo if we sum num_moves across all our targets, we can find the target with the min_total_moves. So, how to efficiently merge all the intervals?\n\nWe can derive the idea from Sweep Line Algorithm. (Have a look at the sweep line algorithm to understand the solution) \n\nLet\'s start by our worst case scenario of having to make two moves for each pair to achieve a target - we would have to make n moves in that case. We can maintain a overlap_arr which tries to reduce the number of moves according to our above observation.\n1) For target in range [min(nums[i], nums[n-1-i]) + 1, nums[i] + nums[n-1-i]), we need only 1 move - since we assumed 2 moves for each pair, we can reduce overlap_arr[min(nums[i], nums[n-1-i]) + 1] by 1\n2) For target == nums[i] + nums[n-1-i], our move would further reduce by 1 \n3) For target = (nums[i] + nums[n-1-i], max(nums[i], nums[n-1-i]) + limit], we need to increase our moves by 1\n4) and for target = (max(nums[i], nums[n-1-i]) + limit, 2*limit), we need to restore our initital assumption of two moves - increase again by 1\n\n```\nclass Solution: \n def minMoves(self, nums: List[int], limit: int) -> int:\n n = len(nums)\n overlay_arr = [0] * (2*limit+2)\n for i in range(n//2):\n left_boundary = min(nums[i], nums[n-1-i]) + 1\n no_move_value = nums[i] + nums[n-1-i]\n right_boundary = max(nums[i], nums[n-1-i]) + limit\n overlay_arr[left_boundary] -= 1\n overlay_arr[no_move_value] -= 1\n overlay_arr[no_move_value+1] += 1\n overlay_arr[right_boundary+1] += 1\n curr_moves = n #initial assumption of two moves for each pair\n res = float("inf")\n\t\t# start Sweeping\n for i in range(2, 2*limit+1):\n curr_moves += overlay_arr[i]\n res = min(res, curr_moves)\n return res\n```\n
6
You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive. The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same number. For example, the array `[1,2,3,4]` is complementary because for all indices `i`, `nums[i] + nums[n - 1 - i] = 5`. Return the _**minimum** number of moves required to make_ `nums` _**complementary**_. **Example 1:** **Input:** nums = \[1,2,4,3\], limit = 4 **Output:** 1 **Explanation:** In 1 move, you can change nums to \[1,2,2,3\] (underlined elements are changed). nums\[0\] + nums\[3\] = 1 + 3 = 4. nums\[1\] + nums\[2\] = 2 + 2 = 4. nums\[2\] + nums\[1\] = 2 + 2 = 4. nums\[3\] + nums\[0\] = 3 + 1 = 4. Therefore, nums\[i\] + nums\[n-1-i\] = 4 for every i, so nums is complementary. **Example 2:** **Input:** nums = \[1,2,2,1\], limit = 2 **Output:** 2 **Explanation:** In 2 moves, you can change nums to \[2,2,2,2\]. You cannot change any number to 3 since 3 > limit. **Example 3:** **Input:** nums = \[1,2,1,2\], limit = 2 **Output:** 0 **Explanation:** nums is already complementary. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `1 <= nums[i] <= limit <= 105` * `n` is even.
Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?
Sweep Algorithm | Explained [Python]
minimum-moves-to-make-array-complementary
0
1
Let\'s start with a few observations:\n1. Let\'s say x = target number (sum for each complimentary numbers) => We need to change complimentary values to achieve this target\n2. The min target number achievable is 2 \n\t* 1 <= nums[i] <= limit <= 105\n\t* so either the nums[i] already equal to 1 each or we replace them by 1\n3. The max target number achievable is 2 * limit\n\t* \tWe replace both complimentary values by **limit**\n\nNow the problem is to find an optimal target which would minimize total number of moves. For, each complimentary numbers \n1) we could either make 0 move and achieve the target = nums[i] + nums[n-1-i]\n2) or, make one move and achieve a target range of [min(nums[i], nums[n-1-i]) + 1, max(nums[i], nums[n-1-i] + limit]\n\t* lower limit -> change max(nums[i], nums[n-1-i]) to 1 -> target would be min(nums[i], nums[n-1-i]) + 1\n\t* upper limit -> change min(nums[i], nums[n-1-i] to limit -> target would be max(nums[i], nums[n-1-i] + limit\n3) Make two moves and achieve a target range of \n\t* [2, min(nums[i], nums[n-1-i]) + 1) \n\t* or, (max(nums[i], nums[n-1-i] + limit, 2*limit]\n\nLet\'s say our array was [1,2,4,3] and limit = 4\n -> possible target sum would be 2 to 2* limit (2-8)\n -> first complimentary pair would be (1,3). And the number of moves to achieve the corresponding target would be as follows\n\n\t\tnum_moves: 1 1 0 1 1 1 2 \n\t\ttarget: 2 3 4 5 6 7 8 \n\n -> second complimentary pair would be (2,4) index = (1,2):\n\n\t\tnum_moves: 2 1 1 1 0 1 1 \n\t\ttarget: 2 3 4 5 6 7 8 \n\nAs we can see we can make a minimum total moves = 1 by either achieving a target of 4 ( make a change in second complimentary pair) or a target of 6 (make a change in first complimentary pair)\n\nSo if we sum num_moves across all our targets, we can find the target with the min_total_moves. So, how to efficiently merge all the intervals?\n\nWe can derive the idea from Sweep Line Algorithm. (Have a look at the sweep line algorithm to understand the solution) \n\nLet\'s start by our worst case scenario of having to make two moves for each pair to achieve a target - we would have to make n moves in that case. We can maintain a overlap_arr which tries to reduce the number of moves according to our above observation.\n1) For target in range [min(nums[i], nums[n-1-i]) + 1, nums[i] + nums[n-1-i]), we need only 1 move - since we assumed 2 moves for each pair, we can reduce overlap_arr[min(nums[i], nums[n-1-i]) + 1] by 1\n2) For target == nums[i] + nums[n-1-i], our move would further reduce by 1 \n3) For target = (nums[i] + nums[n-1-i], max(nums[i], nums[n-1-i]) + limit], we need to increase our moves by 1\n4) and for target = (max(nums[i], nums[n-1-i]) + limit, 2*limit), we need to restore our initital assumption of two moves - increase again by 1\n\n```\nclass Solution: \n def minMoves(self, nums: List[int], limit: int) -> int:\n n = len(nums)\n overlay_arr = [0] * (2*limit+2)\n for i in range(n//2):\n left_boundary = min(nums[i], nums[n-1-i]) + 1\n no_move_value = nums[i] + nums[n-1-i]\n right_boundary = max(nums[i], nums[n-1-i]) + limit\n overlay_arr[left_boundary] -= 1\n overlay_arr[no_move_value] -= 1\n overlay_arr[no_move_value+1] += 1\n overlay_arr[right_boundary+1] += 1\n curr_moves = n #initial assumption of two moves for each pair\n res = float("inf")\n\t\t# start Sweeping\n for i in range(2, 2*limit+1):\n curr_moves += overlay_arr[i]\n res = min(res, curr_moves)\n return res\n```\n
6
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Python3: Sweep Line with Comments
minimum-moves-to-make-array-complementary
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)$$ -->\n\n# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n # 0 1 2 3 4 5\n # 1 4 2 1 5 3 # 5\n\n # create an interval [i, n - i - 1] -> [min, max]\n N = len(nums) # 4 -> 2\n res, cur = N, N # at maximum N number of changes\n ranges = [0] * (2 * limit + 2)\n\n # fill the ranges with the marginal increase in the number of changes\n # for current interval,\n # if the target change is out side of changes that can be made by\n # changing one element; \n # left: min + 1; -= 1 - come in the range\n # right: max + limit + 1; += 1 - goes out of the range\n # same: min + max; -= 1\n # not same: min + max + 1; += 1\n for i in range(N // 2):\n a, b = nums[i], nums[N - i - 1]\n s, e = min(a, b), max(a, b)\n\n # update the ranges\n ranges[s + 1] -= 1 # in the left bound\n ranges[s + e] -= 1 # is the same\n ranges[s + e + 1] += 1 # is not the same\n ranges[e + limit + 1] += 1 # if out of bound\n\n for i in range(2, 2 * limit + 1):\n # update the cur\n cur += ranges[i]\n\n # update the res\n res = min(res, cur)\n \n return res\n```
0
You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive. The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same number. For example, the array `[1,2,3,4]` is complementary because for all indices `i`, `nums[i] + nums[n - 1 - i] = 5`. Return the _**minimum** number of moves required to make_ `nums` _**complementary**_. **Example 1:** **Input:** nums = \[1,2,4,3\], limit = 4 **Output:** 1 **Explanation:** In 1 move, you can change nums to \[1,2,2,3\] (underlined elements are changed). nums\[0\] + nums\[3\] = 1 + 3 = 4. nums\[1\] + nums\[2\] = 2 + 2 = 4. nums\[2\] + nums\[1\] = 2 + 2 = 4. nums\[3\] + nums\[0\] = 3 + 1 = 4. Therefore, nums\[i\] + nums\[n-1-i\] = 4 for every i, so nums is complementary. **Example 2:** **Input:** nums = \[1,2,2,1\], limit = 2 **Output:** 2 **Explanation:** In 2 moves, you can change nums to \[2,2,2,2\]. You cannot change any number to 3 since 3 > limit. **Example 3:** **Input:** nums = \[1,2,1,2\], limit = 2 **Output:** 0 **Explanation:** nums is already complementary. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `1 <= nums[i] <= limit <= 105` * `n` is even.
Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?
Python3: Sweep Line with Comments
minimum-moves-to-make-array-complementary
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)$$ -->\n\n# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n # 0 1 2 3 4 5\n # 1 4 2 1 5 3 # 5\n\n # create an interval [i, n - i - 1] -> [min, max]\n N = len(nums) # 4 -> 2\n res, cur = N, N # at maximum N number of changes\n ranges = [0] * (2 * limit + 2)\n\n # fill the ranges with the marginal increase in the number of changes\n # for current interval,\n # if the target change is out side of changes that can be made by\n # changing one element; \n # left: min + 1; -= 1 - come in the range\n # right: max + limit + 1; += 1 - goes out of the range\n # same: min + max; -= 1\n # not same: min + max + 1; += 1\n for i in range(N // 2):\n a, b = nums[i], nums[N - i - 1]\n s, e = min(a, b), max(a, b)\n\n # update the ranges\n ranges[s + 1] -= 1 # in the left bound\n ranges[s + e] -= 1 # is the same\n ranges[s + e + 1] += 1 # is not the same\n ranges[e + limit + 1] += 1 # if out of bound\n\n for i in range(2, 2 * limit + 1):\n # update the cur\n cur += ranges[i]\n\n # update the res\n res = min(res, cur)\n \n return res\n```
0
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Sweep line
minimum-moves-to-make-array-complementary
0
1
# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n cnt = Counter()\n i, n = 0, len(nums)\n p = [0] * (2 * limit + 2)\n while i < n // 2:\n cnt[nums[i] + nums[n-1-i]] += 1\n p[min(nums[i], nums[n-1-i]) + 1] += 1\n p[max(nums[i], nums[n-1-i]) + limit + 1] -= 1\n i += 1\n \n v, ans = 0, inf\n for q in range(2, 2 * limit + 1):\n v += p[q]\n ans = min(ans, v - cnt[q] + (n // 2 - v) * 2)\n return ans\n```
0
You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive. The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same number. For example, the array `[1,2,3,4]` is complementary because for all indices `i`, `nums[i] + nums[n - 1 - i] = 5`. Return the _**minimum** number of moves required to make_ `nums` _**complementary**_. **Example 1:** **Input:** nums = \[1,2,4,3\], limit = 4 **Output:** 1 **Explanation:** In 1 move, you can change nums to \[1,2,2,3\] (underlined elements are changed). nums\[0\] + nums\[3\] = 1 + 3 = 4. nums\[1\] + nums\[2\] = 2 + 2 = 4. nums\[2\] + nums\[1\] = 2 + 2 = 4. nums\[3\] + nums\[0\] = 3 + 1 = 4. Therefore, nums\[i\] + nums\[n-1-i\] = 4 for every i, so nums is complementary. **Example 2:** **Input:** nums = \[1,2,2,1\], limit = 2 **Output:** 2 **Explanation:** In 2 moves, you can change nums to \[2,2,2,2\]. You cannot change any number to 3 since 3 > limit. **Example 3:** **Input:** nums = \[1,2,1,2\], limit = 2 **Output:** 0 **Explanation:** nums is already complementary. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `1 <= nums[i] <= limit <= 105` * `n` is even.
Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?
Sweep line
minimum-moves-to-make-array-complementary
0
1
# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n cnt = Counter()\n i, n = 0, len(nums)\n p = [0] * (2 * limit + 2)\n while i < n // 2:\n cnt[nums[i] + nums[n-1-i]] += 1\n p[min(nums[i], nums[n-1-i]) + 1] += 1\n p[max(nums[i], nums[n-1-i]) + limit + 1] -= 1\n i += 1\n \n v, ans = 0, inf\n for q in range(2, 2 * limit + 1):\n v += p[q]\n ans = min(ans, v - cnt[q] + (n // 2 - v) * 2)\n return ans\n```
0
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
clean code with good explanation
minimum-moves-to-make-array-complementary
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### Let `l` be the `nums[i]`, and `r` be the `nums[n-i-1]`\n1. All pair sum must in the range `[2, limit*2]`.\n2. By one step modification, the max sum that we can get is `max(l, r) + limit` and the min sum that we can get is `min(l, r) + 1`.\n3. When the target sum out of the range `[min(l, r) + 1, max(l, r) + limit]`, two modifications are required.\n4. We start with `n` modifications which is the max number that we need. And we store the action: `+1` or `-1` in each key point, then we could compute prefix sum to find the optimized number of modification that we need.\n##### Here are all the key points need to be handled\n1. At `min(l, r) + 1` we do `-1`, since this is the lower bound for the one step modification.\n2. At `max(l, r) + limit + 1` we do `+1`, since we are out of the upper bound for the one step modification.\n3. At `l+r` we do `-1`, since no modifications are required.\n4. At `l+r+1` we do `+1`, since we are no more at the prefect position as `l+r`, one modification is required.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a list to store all the key points for each possible target sum.\n2. Find the min number of moves by computing prefix sum index by index.\n# Complexity\n- Time complexity: O(n + limit)\n- Creating the list takes O(n), computing prefix sum and find the min value takes O(limit).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(limit)\n- The size of the list only depends on the limit.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n # prepare the list for computing prefix sum\n n = len(nums)\n pre_sum = [0] * (2 * limit + 2)\n for i in range(n // 2):\n a, b = nums[i], nums[n - i - 1]\n min_val = min(a, b)\n max_val = max(a, b)\n pre_sum[min_val + 1] -= 1\n pre_sum[min_val + max_val] -= 1\n pre_sum[min_val + max_val + 1] += 1\n pre_sum[max_val + limit + 1] += 1\n # get the min number of moves by computing the prefix sum\n res = n\n cur = n\n for i in range(2, 2 * limit + 1):\n cur += pre_sum[i]\n res = min(res, cur)\n return res\n```
0
You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive. The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same number. For example, the array `[1,2,3,4]` is complementary because for all indices `i`, `nums[i] + nums[n - 1 - i] = 5`. Return the _**minimum** number of moves required to make_ `nums` _**complementary**_. **Example 1:** **Input:** nums = \[1,2,4,3\], limit = 4 **Output:** 1 **Explanation:** In 1 move, you can change nums to \[1,2,2,3\] (underlined elements are changed). nums\[0\] + nums\[3\] = 1 + 3 = 4. nums\[1\] + nums\[2\] = 2 + 2 = 4. nums\[2\] + nums\[1\] = 2 + 2 = 4. nums\[3\] + nums\[0\] = 3 + 1 = 4. Therefore, nums\[i\] + nums\[n-1-i\] = 4 for every i, so nums is complementary. **Example 2:** **Input:** nums = \[1,2,2,1\], limit = 2 **Output:** 2 **Explanation:** In 2 moves, you can change nums to \[2,2,2,2\]. You cannot change any number to 3 since 3 > limit. **Example 3:** **Input:** nums = \[1,2,1,2\], limit = 2 **Output:** 0 **Explanation:** nums is already complementary. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `1 <= nums[i] <= limit <= 105` * `n` is even.
Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?
clean code with good explanation
minimum-moves-to-make-array-complementary
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### Let `l` be the `nums[i]`, and `r` be the `nums[n-i-1]`\n1. All pair sum must in the range `[2, limit*2]`.\n2. By one step modification, the max sum that we can get is `max(l, r) + limit` and the min sum that we can get is `min(l, r) + 1`.\n3. When the target sum out of the range `[min(l, r) + 1, max(l, r) + limit]`, two modifications are required.\n4. We start with `n` modifications which is the max number that we need. And we store the action: `+1` or `-1` in each key point, then we could compute prefix sum to find the optimized number of modification that we need.\n##### Here are all the key points need to be handled\n1. At `min(l, r) + 1` we do `-1`, since this is the lower bound for the one step modification.\n2. At `max(l, r) + limit + 1` we do `+1`, since we are out of the upper bound for the one step modification.\n3. At `l+r` we do `-1`, since no modifications are required.\n4. At `l+r+1` we do `+1`, since we are no more at the prefect position as `l+r`, one modification is required.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a list to store all the key points for each possible target sum.\n2. Find the min number of moves by computing prefix sum index by index.\n# Complexity\n- Time complexity: O(n + limit)\n- Creating the list takes O(n), computing prefix sum and find the min value takes O(limit).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(limit)\n- The size of the list only depends on the limit.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n # prepare the list for computing prefix sum\n n = len(nums)\n pre_sum = [0] * (2 * limit + 2)\n for i in range(n // 2):\n a, b = nums[i], nums[n - i - 1]\n min_val = min(a, b)\n max_val = max(a, b)\n pre_sum[min_val + 1] -= 1\n pre_sum[min_val + max_val] -= 1\n pre_sum[min_val + max_val + 1] += 1\n pre_sum[max_val + limit + 1] += 1\n # get the min number of moves by computing the prefix sum\n res = n\n cur = n\n for i in range(2, 2 * limit + 1):\n cur += pre_sum[i]\n res = min(res, cur)\n return res\n```
0
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Solution
minimum-moves-to-make-array-complementary
1
1
```C++ []\nstatic const auto fast = []() {ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); return 0; } ();\nclass Solution {\npublic:\n int minMoves(vector<int>& nums, int limit) {\n int n=nums.size(),c2[2*limit+2],c3[2*limit+1],ans=n,t1,t2;\n memset(c2,0,sizeof(c2));\n memset(c3,0,sizeof(c3));\n for(int x=0;x<n/2;x++){\n t1=min(nums[x],nums[n-1-x]);\n t2=max(nums[x],nums[n-1-x]);\n c2[t1+1]--;\n c2[t2+limit+1]++;\n c3[t1+t2]++;\n }\n\n int cnt=n;\n for(int x=2;x<=2*limit;x++){\n cnt+=c2[x];\n ans=min(ans,cnt-c3[x]);\n }\n\n return ans;\n } \n};\n```\n\n```Python3 []\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n moves, n = [0] * (2 * limit), len(nums)\n for l, r in zip(nums[:n // 2], nums[::-1]):\n if l > r:\n l, r = r, l\n moves[l - 1] -= 1\n moves[l + r - 2] -= 1\n moves[l + r - 1] += 1\n moves[r + limit - 1] += 1\n return n + min(accumulate(moves))\n```\n\n```Java []\nclass Solution {\n public int minMoves(int[] nums, int limit) {\n int n = nums.length;\n int[] diff = new int[2 * limit + 2];\n for(int i = 0; i < n / 2; i++){\n int a = nums[i];\n int b = nums[n - 1 - i];\n diff[2] += 2;\n diff[Math.min(a, b) + 1]--;\n diff[a + b]--;\n diff[a + b + 1]++;\n diff[Math.max(a, b) + limit + 1]++;\n }\n int res = n;\n int curr = 0;\n for(int i = 2; i <= 2 * limit; i++){\n curr += diff[i];\n res = Math.min(res, curr);\n }\n return res;\n }\n}\n```\n
0
You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive. The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same number. For example, the array `[1,2,3,4]` is complementary because for all indices `i`, `nums[i] + nums[n - 1 - i] = 5`. Return the _**minimum** number of moves required to make_ `nums` _**complementary**_. **Example 1:** **Input:** nums = \[1,2,4,3\], limit = 4 **Output:** 1 **Explanation:** In 1 move, you can change nums to \[1,2,2,3\] (underlined elements are changed). nums\[0\] + nums\[3\] = 1 + 3 = 4. nums\[1\] + nums\[2\] = 2 + 2 = 4. nums\[2\] + nums\[1\] = 2 + 2 = 4. nums\[3\] + nums\[0\] = 3 + 1 = 4. Therefore, nums\[i\] + nums\[n-1-i\] = 4 for every i, so nums is complementary. **Example 2:** **Input:** nums = \[1,2,2,1\], limit = 2 **Output:** 2 **Explanation:** In 2 moves, you can change nums to \[2,2,2,2\]. You cannot change any number to 3 since 3 > limit. **Example 3:** **Input:** nums = \[1,2,1,2\], limit = 2 **Output:** 0 **Explanation:** nums is already complementary. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `1 <= nums[i] <= limit <= 105` * `n` is even.
Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ?
Solution
minimum-moves-to-make-array-complementary
1
1
```C++ []\nstatic const auto fast = []() {ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); return 0; } ();\nclass Solution {\npublic:\n int minMoves(vector<int>& nums, int limit) {\n int n=nums.size(),c2[2*limit+2],c3[2*limit+1],ans=n,t1,t2;\n memset(c2,0,sizeof(c2));\n memset(c3,0,sizeof(c3));\n for(int x=0;x<n/2;x++){\n t1=min(nums[x],nums[n-1-x]);\n t2=max(nums[x],nums[n-1-x]);\n c2[t1+1]--;\n c2[t2+limit+1]++;\n c3[t1+t2]++;\n }\n\n int cnt=n;\n for(int x=2;x<=2*limit;x++){\n cnt+=c2[x];\n ans=min(ans,cnt-c3[x]);\n }\n\n return ans;\n } \n};\n```\n\n```Python3 []\nclass Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n moves, n = [0] * (2 * limit), len(nums)\n for l, r in zip(nums[:n // 2], nums[::-1]):\n if l > r:\n l, r = r, l\n moves[l - 1] -= 1\n moves[l + r - 2] -= 1\n moves[l + r - 1] += 1\n moves[r + limit - 1] += 1\n return n + min(accumulate(moves))\n```\n\n```Java []\nclass Solution {\n public int minMoves(int[] nums, int limit) {\n int n = nums.length;\n int[] diff = new int[2 * limit + 2];\n for(int i = 0; i < n / 2; i++){\n int a = nums[i];\n int b = nums[n - 1 - i];\n diff[2] += 2;\n diff[Math.min(a, b) + 1]--;\n diff[a + b]--;\n diff[a + b + 1]++;\n diff[Math.max(a, b) + limit + 1]++;\n }\n int res = n;\n int curr = 0;\n for(int i = 2; i <= 2 * limit; i++){\n curr += diff[i];\n res = Math.min(res, curr);\n }\n return res;\n }\n}\n```\n
0
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Day 55 || Priority_Queue || Easiest Beginner Friendly Sol
minimize-deviation-in-array
1
1
# Intuition of this Problem:\nThe intuition behind this logic is to reduce the maximum difference between any two elements in the array by either decreasing the maximum value or increasing the minimum value.\n\nBy transforming all odd numbers to even numbers, we can always divide even numbers by 2, so the maximum value in the array can be reduced to its minimum possible value. We also keep track of the minimum value in the array, since we can only increase it by multiplying it by 2.\n\nWe then repeatedly pop the maximum value from the priority queue, which guarantees that we are always reducing the maximum value in the array. If the maximum value is odd, we can no longer divide it by 2, so we break out of the loop. Otherwise, we divide the maximum value by 2, which reduces the maximum value, and update the minimum value accordingly.\n\nBy doing this repeatedly, we can always reduce the maximum difference between any two elements in the array, and we keep track of the minimum deviation that we can achieve.\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Create a max heap and a variable to keep track of the minimum value in the array.\n2. For each number in the input array, if it is odd, multiply it by 2 and push it onto the heap. Otherwise, just push it onto the heap.\n3. Also, update the minimum value if necessary.\n4. Initialize a variable to keep track of the minimum deviation.\n5. While the maximum value in the heap is even, pop it off the heap, divide it by 2, and push it back onto the heap. Update the minimum deviation and the minimum value if necessary.\n6. If the maximum value in the heap is odd, we cannot reduce it any further by dividing by 2. In this case, break out of the loop.\n7. Return the minimum deviation.\n<!-- Describe your approach to solving the problem. -->\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int minimumDeviation(vector<int>& nums) {\n priority_queue<int> pq;\n int minVal = INT_MAX;\n for (int num : nums) {\n if (num % 2 == 1)\n num = num * 2;\n pq.push(num);\n minVal = min(minVal, num);\n }\n int minDeviation = INT_MAX;\n while (true) {\n int maxVal = pq.top();\n pq.pop();\n minDeviation = min(minDeviation, maxVal - minVal);\n //The reason we need to break out of the loop when the maximum value is odd is that we have already transformed all odd numbers in the input array to even numbers by multiplying them by 2. Therefore, if the maximum value in the priority queue is odd, it must have been obtained by performing the "multiply by 2" operation on some even number. We cannot undo this operation by performing the "divide by 2" operation, so we cannot reduce the maximum value any further.\n if (maxVal % 2 == 1)\n break;\n maxVal = maxVal / 2;\n minVal = min(minVal, maxVal);\n pq.push(maxVal);\n }\n return minDeviation;\n }\n};\n```\n```Java []\nclass Solution {\n public int minimumDeviation(int[] nums) {\n PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());\n int minVal = Integer.MAX_VALUE;\n for (int num : nums) {\n if (num % 2 == 1)\n num = num * 2;\n pq.offer(num);\n minVal = Math.min(minVal, num);\n }\n int minDeviation = Integer.MAX_VALUE;\n while (true) {\n int maxVal = pq.poll();\n minDeviation = Math.min(minDeviation, maxVal - minVal);\n if (maxVal % 2 == 1)\n break;\n maxVal = maxVal / 2;\n minVal = Math.min(minVal, maxVal);\n pq.offer(maxVal);\n }\n return minDeviation;\n }\n}\n\n```\n```Python []\n///Note : In the Python code, we use a min-heap instead of a max-heap because Python\'s heapq module only provides a min-heap implementation. Therefore, we negate the values in the heap to simulate a max-heap.\n\nimport heapq\n\nclass Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n pq = [-num*2 if num % 2 == 1 else -num for num in nums]\n heapq.heapify(pq)\n min_val = -float(\'inf\')\n for num in nums:\n min_val = min(min_val, -num if num % 2 == 0 else -num*2)\n min_deviation = float(\'inf\')\n while True:\n max_val = -heapq.heappop(pq)\n min_deviation = min(min_deviation, max_val - min_val)\n if max_val % 2 == 1:\n break\n max_val //= 2\n min_val = min(min_val, -max_val)\n heapq.heappush(pq, -max_val)\n return min_deviation\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(nlogn)**\nThe algorithm involves inserting n elements(worst case) into a priority queue, which takes O(n log n) time. The while loop iterates at most log(maximum value in the array) times. In the worst case, the maximum value can be as large as 10^9, so the loop iterates log(10^9) times, which is a constant value. The operations inside the loop take O(log n) time, which is the time required to insert or delete an element from the priority queue. Therefore, the overall time complexity of the algorithm is O(n log n).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\nThe algorithm uses a priority queue to store the elements, which takes O(n) space. Additionally, it uses a few constant-size variables to keep track of the minimum and maximum values, as well as the answer. Therefore, the overall space complexity of the algorithm is O(n).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
306
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Day 55 || Priority_Queue || Easiest Beginner Friendly Sol
minimize-deviation-in-array
1
1
# Intuition of this Problem:\nThe intuition behind this logic is to reduce the maximum difference between any two elements in the array by either decreasing the maximum value or increasing the minimum value.\n\nBy transforming all odd numbers to even numbers, we can always divide even numbers by 2, so the maximum value in the array can be reduced to its minimum possible value. We also keep track of the minimum value in the array, since we can only increase it by multiplying it by 2.\n\nWe then repeatedly pop the maximum value from the priority queue, which guarantees that we are always reducing the maximum value in the array. If the maximum value is odd, we can no longer divide it by 2, so we break out of the loop. Otherwise, we divide the maximum value by 2, which reduces the maximum value, and update the minimum value accordingly.\n\nBy doing this repeatedly, we can always reduce the maximum difference between any two elements in the array, and we keep track of the minimum deviation that we can achieve.\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Create a max heap and a variable to keep track of the minimum value in the array.\n2. For each number in the input array, if it is odd, multiply it by 2 and push it onto the heap. Otherwise, just push it onto the heap.\n3. Also, update the minimum value if necessary.\n4. Initialize a variable to keep track of the minimum deviation.\n5. While the maximum value in the heap is even, pop it off the heap, divide it by 2, and push it back onto the heap. Update the minimum deviation and the minimum value if necessary.\n6. If the maximum value in the heap is odd, we cannot reduce it any further by dividing by 2. In this case, break out of the loop.\n7. Return the minimum deviation.\n<!-- Describe your approach to solving the problem. -->\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int minimumDeviation(vector<int>& nums) {\n priority_queue<int> pq;\n int minVal = INT_MAX;\n for (int num : nums) {\n if (num % 2 == 1)\n num = num * 2;\n pq.push(num);\n minVal = min(minVal, num);\n }\n int minDeviation = INT_MAX;\n while (true) {\n int maxVal = pq.top();\n pq.pop();\n minDeviation = min(minDeviation, maxVal - minVal);\n //The reason we need to break out of the loop when the maximum value is odd is that we have already transformed all odd numbers in the input array to even numbers by multiplying them by 2. Therefore, if the maximum value in the priority queue is odd, it must have been obtained by performing the "multiply by 2" operation on some even number. We cannot undo this operation by performing the "divide by 2" operation, so we cannot reduce the maximum value any further.\n if (maxVal % 2 == 1)\n break;\n maxVal = maxVal / 2;\n minVal = min(minVal, maxVal);\n pq.push(maxVal);\n }\n return minDeviation;\n }\n};\n```\n```Java []\nclass Solution {\n public int minimumDeviation(int[] nums) {\n PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());\n int minVal = Integer.MAX_VALUE;\n for (int num : nums) {\n if (num % 2 == 1)\n num = num * 2;\n pq.offer(num);\n minVal = Math.min(minVal, num);\n }\n int minDeviation = Integer.MAX_VALUE;\n while (true) {\n int maxVal = pq.poll();\n minDeviation = Math.min(minDeviation, maxVal - minVal);\n if (maxVal % 2 == 1)\n break;\n maxVal = maxVal / 2;\n minVal = Math.min(minVal, maxVal);\n pq.offer(maxVal);\n }\n return minDeviation;\n }\n}\n\n```\n```Python []\n///Note : In the Python code, we use a min-heap instead of a max-heap because Python\'s heapq module only provides a min-heap implementation. Therefore, we negate the values in the heap to simulate a max-heap.\n\nimport heapq\n\nclass Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n pq = [-num*2 if num % 2 == 1 else -num for num in nums]\n heapq.heapify(pq)\n min_val = -float(\'inf\')\n for num in nums:\n min_val = min(min_val, -num if num % 2 == 0 else -num*2)\n min_deviation = float(\'inf\')\n while True:\n max_val = -heapq.heappop(pq)\n min_deviation = min(min_deviation, max_val - min_val)\n if max_val % 2 == 1:\n break\n max_val //= 2\n min_val = min(min_val, -max_val)\n heapq.heappush(pq, -max_val)\n return min_deviation\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(nlogn)**\nThe algorithm involves inserting n elements(worst case) into a priority queue, which takes O(n log n) time. The while loop iterates at most log(maximum value in the array) times. In the worst case, the maximum value can be as large as 10^9, so the loop iterates log(10^9) times, which is a constant value. The operations inside the loop take O(log n) time, which is the time required to insert or delete an element from the priority queue. Therefore, the overall time complexity of the algorithm is O(n log n).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(n)**\nThe algorithm uses a priority queue to store the elements, which takes O(n) space. Additionally, it uses a few constant-size variables to keep track of the minimum and maximum values, as well as the answer. Therefore, the overall space complexity of the algorithm is O(n).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
306
You are given two strings `firstString` and `secondString` that are **0-indexed** and consist only of lowercase English letters. Count the number of index quadruples `(i,j,a,b)` that satisfy the following conditions: * `0 <= i <= j < firstString.length` * `0 <= a <= b < secondString.length` * The substring of `firstString` that starts at the `ith` character and ends at the `jth` character (inclusive) is **equal** to the substring of `secondString` that starts at the `ath` character and ends at the `bth` character (inclusive). * `j - a` is the **minimum** possible value among all quadruples that satisfy the previous conditions. Return _the **number** of such quadruples_. **Example 1:** **Input:** firstString = "abcd ", secondString = "bccda " **Output:** 1 **Explanation:** The quadruple (0,0,4,4) is the only one that satisfies all the conditions and minimizes j - a. **Example 2:** **Input:** firstString = "ab ", secondString = "cd " **Output:** 0 **Explanation:** There are no quadruples satisfying all the conditions. **Constraints:** * `1 <= firstString.length, secondString.length <= 2 * 105` * Both strings consist only of lowercase English letters.
Assume you start with the minimum possible value for each number so you can only multiply a number by 2 till it reaches its maximum possible value. If there is a better solution than the current one, then it must have either its maximum value less than the current maximum value, or the minimum value larger than the current minimum value. Since that we only increase numbers (multiply them by 2), we cannot decrease the current maximum value, so we must multiply the current minimum number by 2.
Python easy to understand | Max Heap
minimize-deviation-in-array
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n###### Create a `Max_Heap` having maximum possible value for each element. Repeatedly pop the `top` (max element) of the heap and divide it by 2 until the `top` of the heap is even and update the minimum deviation for each step.\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n maxHeap = [-x*2 if x % 2 != 0 else -x for x in nums]\n heapify(maxHeap)\n ans, minItem = maxsize, -max(maxHeap)\n while maxHeap[0] % 2 == 0:\n maxItem = -heappop(maxHeap)\n ans = min(ans, maxItem - minItem)\n maxItem //= 2\n minItem = min(minItem, maxItem)\n heappush(maxHeap, -maxItem)\n ans = min(ans, -maxHeap[0] - minItem)\n return ans\n```
1
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Python easy to understand | Max Heap
minimize-deviation-in-array
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n###### Create a `Max_Heap` having maximum possible value for each element. Repeatedly pop the `top` (max element) of the heap and divide it by 2 until the `top` of the heap is even and update the minimum deviation for each step.\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n maxHeap = [-x*2 if x % 2 != 0 else -x for x in nums]\n heapify(maxHeap)\n ans, minItem = maxsize, -max(maxHeap)\n while maxHeap[0] % 2 == 0:\n maxItem = -heappop(maxHeap)\n ans = min(ans, maxItem - minItem)\n maxItem //= 2\n minItem = min(minItem, maxItem)\n heappush(maxHeap, -maxItem)\n ans = min(ans, -maxHeap[0] - minItem)\n return ans\n```
1
You are given two strings `firstString` and `secondString` that are **0-indexed** and consist only of lowercase English letters. Count the number of index quadruples `(i,j,a,b)` that satisfy the following conditions: * `0 <= i <= j < firstString.length` * `0 <= a <= b < secondString.length` * The substring of `firstString` that starts at the `ith` character and ends at the `jth` character (inclusive) is **equal** to the substring of `secondString` that starts at the `ath` character and ends at the `bth` character (inclusive). * `j - a` is the **minimum** possible value among all quadruples that satisfy the previous conditions. Return _the **number** of such quadruples_. **Example 1:** **Input:** firstString = "abcd ", secondString = "bccda " **Output:** 1 **Explanation:** The quadruple (0,0,4,4) is the only one that satisfies all the conditions and minimizes j - a. **Example 2:** **Input:** firstString = "ab ", secondString = "cd " **Output:** 0 **Explanation:** There are no quadruples satisfying all the conditions. **Constraints:** * `1 <= firstString.length, secondString.length <= 2 * 105` * Both strings consist only of lowercase English letters.
Assume you start with the minimum possible value for each number so you can only multiply a number by 2 till it reaches its maximum possible value. If there is a better solution than the current one, then it must have either its maximum value less than the current maximum value, or the minimum value larger than the current minimum value. Since that we only increase numbers (multiply them by 2), we cannot decrease the current maximum value, so we must multiply the current minimum number by 2.
Minimize Deviation in Array - Python Heap solution
minimize-deviation-in-array
0
1
# Approach\nWe will use priority heap.\n\n1. Multiply all odd numbers by 2 => we get maximum possible values of all numbers in nums. Now all numbers are even.\n\n2. We will use priotrity heap. But we need multiply all numbers by (-1), because we will take maximum element of heap, not minimum.\n\n3. Keep track min number in heap. Don\'t forget to multiply it by (-1).\n\n4. Take max number from heap(remember about (-1)). While it is even, divide it by 2 and put it back to heap. Since max number is odd we stop.\n\n5. Keep the min difference between max number and min number as a result. And update min number every step.\n\n# Complexity\n- Time complexity: $$O(n logn)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nfrom heapq import heappop, heappush\n\n\nclass Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n result = float(\'inf\')\n heap = [] \n for n in set(nums):\n if n % 2 == 0:\n heappush(heap, (-1) * n)\n else:\n heappush(heap, (-2) * n)\n heap_min = (-1) * max(heap)\n while heap[0] % 2 == 0:\n heap_max = (-1) * heappop(heap)\n heappush(heap, (-1) * heap_max // 2)\n result = min(result, heap_max - heap_min)\n heap_min = min(heap_min, heap_max // 2)\n heap_max = (-1) * heappop(heap)\n result = min(result, heap_max - heap_min)\n return result\n \n```
1
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Minimize Deviation in Array - Python Heap solution
minimize-deviation-in-array
0
1
# Approach\nWe will use priority heap.\n\n1. Multiply all odd numbers by 2 => we get maximum possible values of all numbers in nums. Now all numbers are even.\n\n2. We will use priotrity heap. But we need multiply all numbers by (-1), because we will take maximum element of heap, not minimum.\n\n3. Keep track min number in heap. Don\'t forget to multiply it by (-1).\n\n4. Take max number from heap(remember about (-1)). While it is even, divide it by 2 and put it back to heap. Since max number is odd we stop.\n\n5. Keep the min difference between max number and min number as a result. And update min number every step.\n\n# Complexity\n- Time complexity: $$O(n logn)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nfrom heapq import heappop, heappush\n\n\nclass Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n result = float(\'inf\')\n heap = [] \n for n in set(nums):\n if n % 2 == 0:\n heappush(heap, (-1) * n)\n else:\n heappush(heap, (-2) * n)\n heap_min = (-1) * max(heap)\n while heap[0] % 2 == 0:\n heap_max = (-1) * heappop(heap)\n heappush(heap, (-1) * heap_max // 2)\n result = min(result, heap_max - heap_min)\n heap_min = min(heap_min, heap_max // 2)\n heap_max = (-1) * heappop(heap)\n result = min(result, heap_max - heap_min)\n return result\n \n```
1
You are given two strings `firstString` and `secondString` that are **0-indexed** and consist only of lowercase English letters. Count the number of index quadruples `(i,j,a,b)` that satisfy the following conditions: * `0 <= i <= j < firstString.length` * `0 <= a <= b < secondString.length` * The substring of `firstString` that starts at the `ith` character and ends at the `jth` character (inclusive) is **equal** to the substring of `secondString` that starts at the `ath` character and ends at the `bth` character (inclusive). * `j - a` is the **minimum** possible value among all quadruples that satisfy the previous conditions. Return _the **number** of such quadruples_. **Example 1:** **Input:** firstString = "abcd ", secondString = "bccda " **Output:** 1 **Explanation:** The quadruple (0,0,4,4) is the only one that satisfies all the conditions and minimizes j - a. **Example 2:** **Input:** firstString = "ab ", secondString = "cd " **Output:** 0 **Explanation:** There are no quadruples satisfying all the conditions. **Constraints:** * `1 <= firstString.length, secondString.length <= 2 * 105` * Both strings consist only of lowercase English letters.
Assume you start with the minimum possible value for each number so you can only multiply a number by 2 till it reaches its maximum possible value. If there is a better solution than the current one, then it must have either its maximum value less than the current maximum value, or the minimum value larger than the current minimum value. Since that we only increase numbers (multiply them by 2), we cannot decrease the current maximum value, so we must multiply the current minimum number by 2.
String Replacement Approach in Python
goal-parser-interpretation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem by replacing specific substrings in the input string with their corresponding interpretations.\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 replaced by new using the following method available for strings in Python:\n\n> str.replace(old, new)\n\n1. Replace all occurrences of `()` with `o` in the input string.\n2. Replace all occurrences of `(al)` with `al` in the modified string.\n3. Return the final modified string as the Goal Parser\'s interpretation.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the input IP address string. In the worst case, we may need to traverse the whole string.\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the input IP address string. The space required for the output string is proportional to the length of the input IP address as we create a modified copy of the input string.\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n command = command.replace("()", "o")\n command = command.replace("(al)", "al")\n return command\n```
2
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
String Replacement Approach in Python
goal-parser-interpretation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem by replacing specific substrings in the input string with their corresponding interpretations.\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 replaced by new using the following method available for strings in Python:\n\n> str.replace(old, new)\n\n1. Replace all occurrences of `()` with `o` in the input string.\n2. Replace all occurrences of `(al)` with `al` in the modified string.\n3. Return the final modified string as the Goal Parser\'s interpretation.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the input IP address string. In the worst case, we may need to traverse the whole string.\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the input IP address string. The space required for the output string is proportional to the length of the input IP address as we create a modified copy of the input string.\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n command = command.replace("()", "o")\n command = command.replace("(al)", "al")\n return command\n```
2
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
my variant
goal-parser-interpretation
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)$$ -->\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n command = command.replace(\'()\', \'o\').replace(\'(al)\', \'al\')\n return command\n```
0
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
my variant
goal-parser-interpretation
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)$$ -->\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n command = command.replace(\'()\', \'o\').replace(\'(al)\', \'al\')\n return command\n```
0
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
Goal Parser Interpretation (string replacement )
goal-parser-interpretation
0
1
# No Loops - using in-built Methods\n\n\n# Complexity\n- Time complexity:\n- O(n)\nn is the length of the input IP address string. In the worst case, we may need to traverse the whole string.\n\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n)\nn is the length of the input IP address string. The space required for the output string is proportional to the length of the input IP address as we create a modified copy of the input string.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n command=command.replace("G","G")\n command=command.replace("()","o")\n command=command.replace("(al)","al")\n return command\n```
1
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Goal Parser Interpretation (string replacement )
goal-parser-interpretation
0
1
# No Loops - using in-built Methods\n\n\n# Complexity\n- Time complexity:\n- O(n)\nn is the length of the input IP address string. In the worst case, we may need to traverse the whole string.\n\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n)\nn is the length of the input IP address string. The space required for the output string is proportional to the length of the input IP address as we create a modified copy of the input string.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n command=command.replace("G","G")\n command=command.replace("()","o")\n command=command.replace("(al)","al")\n return command\n```
1
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
Python solution using regex
goal-parser-interpretation
0
1
# Regex\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n\n def replacing(_str: str) -> str:\n content = _str.group(1)\n \n if content == "()":\n return "o"\n else:\n return "al"\n\n return sub(r"(\\(.*?\\))", replacing, command)\n```\n\n\n# Regular (no methods or modules)\n\n# Code\n\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n _str: str = ""\n \n for index, letter in enumerate(command):\n if letter == "(" and command[index + 1] == ")":\n _str += "o"\n elif letter == "(":\n _str += "al"\n elif letter == "G":\n _str += letter\n\n return _str\n```
2
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Python solution using regex
goal-parser-interpretation
0
1
# Regex\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n\n def replacing(_str: str) -> str:\n content = _str.group(1)\n \n if content == "()":\n return "o"\n else:\n return "al"\n\n return sub(r"(\\(.*?\\))", replacing, command)\n```\n\n\n# Regular (no methods or modules)\n\n# Code\n\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n _str: str = ""\n \n for index, letter in enumerate(command):\n if letter == "(" and command[index + 1] == ")":\n _str += "o"\n elif letter == "(":\n _str += "al"\n elif letter == "G":\n _str += letter\n\n return _str\n```
2
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
Python3 easiest and understable solution FIZMAT ON TOP
goal-parser-interpretation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> I started to think that i need to append smth to my string, after i did code with "for", but it didnt work as well, bc there was default count i, like i+=1, so i did with while, that work enough well.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe thing is, we have string, and every time we check if there elements like ["(al)", "G", "()"], so i im going trough th array, and check this elements, and after if there is, i append elements withoun scopes to my new array(s1), and thats it, i used to try code with replace, but time was too much, and it wouldnt work in interview.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) , we are going through the array only 1 time\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\naround 15-20 MB\n# Code\n```\nclass Solution:\n def interpret(self, s: str) -> str:\n s1 = ""\n i = 0\n while(i<len(s)):\n if s[i:i+2] == "()":\n s1+="o"\n i+=2\n elif s[i:i+4] == "(al)":\n s1+="al"\n i+=4\n elif s[i] == "G":\n s1+="G"\n i+=1\n elif s[i:i+2] == "al":\n s1+="al"\n i+=2\n elif s[i] == "o":\n s1+="o"\n i+=1\n else:\n i+=1\n return s1\n```
2
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Python3 easiest and understable solution FIZMAT ON TOP
goal-parser-interpretation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> I started to think that i need to append smth to my string, after i did code with "for", but it didnt work as well, bc there was default count i, like i+=1, so i did with while, that work enough well.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe thing is, we have string, and every time we check if there elements like ["(al)", "G", "()"], so i im going trough th array, and check this elements, and after if there is, i append elements withoun scopes to my new array(s1), and thats it, i used to try code with replace, but time was too much, and it wouldnt work in interview.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) , we are going through the array only 1 time\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\naround 15-20 MB\n# Code\n```\nclass Solution:\n def interpret(self, s: str) -> str:\n s1 = ""\n i = 0\n while(i<len(s)):\n if s[i:i+2] == "()":\n s1+="o"\n i+=2\n elif s[i:i+4] == "(al)":\n s1+="al"\n i+=4\n elif s[i] == "G":\n s1+="G"\n i+=1\n elif s[i:i+2] == "al":\n s1+="al"\n i+=2\n elif s[i] == "o":\n s1+="o"\n i+=1\n else:\n i+=1\n return s1\n```
2
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
Python one-liner
goal-parser-interpretation
0
1
```\nclass Solution:\n def interpret(self, command: str) -> str:\n return command.replace(\'()\',\'o\').replace(\'(al)\',\'al\')\n```
119
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Python one-liner
goal-parser-interpretation
0
1
```\nclass Solution:\n def interpret(self, command: str) -> str:\n return command.replace(\'()\',\'o\').replace(\'(al)\',\'al\')\n```
119
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
[Python \ C++ ] Simple solution using dictionary
goal-parser-interpretation
0
1
Python\n```\n def interpret(self, s: str) -> str:\n d = {"(al)":"al", "()":"o","G":"G"}\n tmp= ""\n res=""\n for i in range(len(s)):\n tmp+=s[i]\n if(tmp in d):\n res+=d[tmp]\n tmp=""\n return res\n```\n\nC++\n\n```\nstring interpret(string s) {\n unordered_map<string, string> d = \n {\n { "(al)" , "al"},\n { "()" , "o" }, \n { "G" , "G" },\n };\n string tmp = "", res = "";\n for(char c: s){\n tmp+=c;\n if(d.find(tmp)!=d.end()){\n res += d[tmp] ;\n tmp = "" ;\n }\n }\n return res;\n }\n```
83
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
[Python \ C++ ] Simple solution using dictionary
goal-parser-interpretation
0
1
Python\n```\n def interpret(self, s: str) -> str:\n d = {"(al)":"al", "()":"o","G":"G"}\n tmp= ""\n res=""\n for i in range(len(s)):\n tmp+=s[i]\n if(tmp in d):\n res+=d[tmp]\n tmp=""\n return res\n```\n\nC++\n\n```\nstring interpret(string s) {\n unordered_map<string, string> d = \n {\n { "(al)" , "al"},\n { "()" , "o" }, \n { "G" , "G" },\n };\n string tmp = "", res = "";\n for(char c: s){\n tmp+=c;\n if(d.find(tmp)!=d.end()){\n res += d[tmp] ;\n tmp = "" ;\n }\n }\n return res;\n }\n```
83
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
A very simple approach in Python
goal-parser-interpretation
0
1
\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n newstr = command.replace(\'()\',\'o\')\n return newstr.replace(\'(al)\',\'al\')\n```
4
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
A very simple approach in Python
goal-parser-interpretation
0
1
\n\n# Code\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n newstr = command.replace(\'()\',\'o\')\n return newstr.replace(\'(al)\',\'al\')\n```
4
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
Python Solution 3 Ways!! For Loop | Regex | Replace Method
goal-parser-interpretation
0
1
# Using For Loops - No Modules, No Methods\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n \n message: str = ""\n \n for index, char in enumerate(command):\n if command[index: index + 4] == "(al)":\n message += "al"\n elif char == "(":\n message += "o"\n elif char == "G":\n message += char\n else: pass\n \n return message \n```\n\n# Using Regex\n```\nfrom re import sub\n\nclass Solution:\n def interpret(self, command: str) -> str:\n def check_command(char: str) -> str:\n option: str = char.group(1)\n return "o" if option == "()" else "al"\n\n return sub(r"(\\(.*?\\))", check_command, command)\n\n```\n\n# Using Replace Method\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n return command.replace("()","o").replace("(al)","al")\n```\n
2
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Python Solution 3 Ways!! For Loop | Regex | Replace Method
goal-parser-interpretation
0
1
# Using For Loops - No Modules, No Methods\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n \n message: str = ""\n \n for index, char in enumerate(command):\n if command[index: index + 4] == "(al)":\n message += "al"\n elif char == "(":\n message += "o"\n elif char == "G":\n message += char\n else: pass\n \n return message \n```\n\n# Using Regex\n```\nfrom re import sub\n\nclass Solution:\n def interpret(self, command: str) -> str:\n def check_command(char: str) -> str:\n option: str = char.group(1)\n return "o" if option == "()" else "al"\n\n return sub(r"(\\(.*?\\))", check_command, command)\n\n```\n\n# Using Replace Method\n```\nclass Solution:\n def interpret(self, command: str) -> str:\n return command.replace("()","o").replace("(al)","al")\n```\n
2
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire `timeToLive` seconds after the `currentTime`. If the token is renewed, the expiry time will be **extended** to expire `timeToLive` seconds after the (potentially different) `currentTime`. Implement the `AuthenticationManager` class: * `AuthenticationManager(int timeToLive)` constructs the `AuthenticationManager` and sets the `timeToLive`. * `generate(string tokenId, int currentTime)` generates a new token with the given `tokenId` at the given `currentTime` in seconds. * `renew(string tokenId, int currentTime)` renews the **unexpired** token with the given `tokenId` at the given `currentTime` in seconds. If there are no unexpired tokens with the given `tokenId`, the request is ignored, and nothing happens. * `countUnexpiredTokens(int currentTime)` returns the number of **unexpired** tokens at the given currentTime. Note that if a token expires at time `t`, and another action happens on time `t` (`renew` or `countUnexpiredTokens`), the expiration takes place **before** the other actions. **Example 1:** **Input** \[ "AuthenticationManager ", "`renew` ", "generate ", "`countUnexpiredTokens` ", "generate ", "`renew` ", "`renew` ", "`countUnexpiredTokens` "\] \[\[5\], \[ "aaa ", 1\], \[ "aaa ", 2\], \[6\], \[ "bbb ", 7\], \[ "aaa ", 8\], \[ "bbb ", 10\], \[15\]\] **Output** \[null, null, null, 1, null, null, null, 0\] **Explanation** AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with `timeToLive` = 5 seconds. authenticationManager.`renew`( "aaa ", 1); // No token exists with tokenId "aaa " at time 1, so nothing happens. authenticationManager.generate( "aaa ", 2); // Generates a new token with tokenId "aaa " at time 2. authenticationManager.`countUnexpiredTokens`(6); // The token with tokenId "aaa " is the only unexpired one at time 6, so return 1. authenticationManager.generate( "bbb ", 7); // Generates a new token with tokenId "bbb " at time 7. authenticationManager.`renew`( "aaa ", 8); // The token with tokenId "aaa " expired at time 7, and 8 >= 7, so at time 8 the `renew` request is ignored, and nothing happens. authenticationManager.`renew`( "bbb ", 10); // The token with tokenId "bbb " is unexpired at time 10, so the `renew` request is fulfilled and now the token will expire at time 15. authenticationManager.`countUnexpiredTokens`(15); // The token with tokenId "bbb " expires at time 15, and the token with tokenId "aaa " expired at time 7, so currently no token is unexpired, so return 0. **Constraints:** * `1 <= timeToLive <= 108` * `1 <= currentTime <= 108` * `1 <= tokenId.length <= 5` * `tokenId` consists only of lowercase letters. * All calls to `generate` will contain unique values of `tokenId`. * The values of `currentTime` across all the function calls will be **strictly increasing**. * At most `2000` calls will be made to all functions combined.
You need to check at most 2 characters to determine which character comes next.
[Python] 4 ways to attack
goal-parser-interpretation
0
1
Just while loop with carefully incrementing counter is good enough:\n```\n# runtime beats 32% ; memory beats 99.76%\ndef interpret(command):\n \n return_string = ""\n i = 0\n while i < len(command):\n if command[i] == "G":\n return_string += \'G\'\n i += 1\n elif command[i:i + 2] == \'()\':\n return_string += \'o\'\n i += 2\n else:\n \'\'\'when command[i:i+3] == "Cal)"\n or command[i] == \'(\'\n but command[i+1] != \')\'\n \'\'\'\n return_string += \'al\'\n i += 4\n \n return return_string\n```\nUse for loop if you want:\n```\n# runtime beats 64%; memory beats 66%\ndef interpret(command):\n \n return_string = ""\n tmp = ""\n for each in command:\n if each == "G":\n return_string += "G"\n tmp = ""\n else:\n tmp += each\n if tmp == \'()\':\n return_string += \'o\'\n tmp = ""\n if tmp == \'(al)\':\n return_string += \'al\'\n tmp = ""\n \n return return_string\n```\nWant to get fancier than that? Enter dictionary:\n```\n# runtime beats 19% ; memory beats 38%\ndef interpret(command):\n list1 = []\n str1 = ""\n parser_table = {\'G\':\'G\',\n \'()\':\'o\',\n \'(al)\':\'al\'\n }\n for each in command:\n str1 += each\n if str1 in parser_table:\n list1.append(parser_table[str1])\n str1 = ""\n \n return \'\'.join(list1)\n```\nOne must always know the builtins of one\'s language:\n```\n# runtime beats 68% ; memory beats 38%\ndef interpret(command): \n command = command.replace("()","o")\n command = command.replace(\'(al)\',\'al\')\n return command\n\t\t# try one liner with this\n```
38
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?