title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
[Python3] dp
first-day-where-you-have-been-in-all-the-rooms
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/84115397f703f3005c3ae0d5d759f4ac64f65de4) for solutions of weekly 257.\n```\nclass Solution:\n def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:\n odd = [0]\n even = [1]\n for i in range(1, len(nextVisit)):...
3
There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day. Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `...
Is it possible to swap one character in the first half of the palindrome to make the next one? Are there different cases for when the length is odd and even?
Python Fastest Solution Beats 100% 29ms, help me debug!!!
24-game
0
1
# Help me debug!\nI\'ve hard coded some of the test cases that were failing, but am not sure where my logic is not working/why these test cases are failing. Please help me figure out what\'s wrong. The first for loop is used to just do the regular operations, and the next for loop is needed to imagine what happens if t...
0
You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24. You are restricted wi...
null
Python Simple 6 lines
minimum-ascii-delete-sum-for-two-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis solution aims to find the longest common subsequence of two strings while considering the ASCII values of the characters as their associated costs.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach ...
2
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_. **Example 1:** **Input:** s1 = "sea ", s2 = "eat " **Output:** 231 **Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum. Deleting "t " from "eat " adds 116 to ...
Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].
Beats 98% | CodeDominar Solution | solved using LCS_DP_B-U approach
minimum-ascii-delete-sum-for-two-strings
0
1
# Code\n```\nclass Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n dp = [[0 for j in range(len(s2)+1)] for i in range(len(s1)+1)]\n for i in range(len(s1)-1,-1,-1):\n for j in range(len(s2)-1,-1,-1):\n if s1[i] == s2[j]:\n dp[i][j] = ord(s...
2
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_. **Example 1:** **Input:** s1 = "sea ", s2 = "eat " **Output:** 231 **Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum. Deleting "t " from "eat " adds 116 to ...
Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].
Python easy solutions || time & memory efficient
minimum-ascii-delete-sum-for-two-strings
0
1
# Intuition\nThe problem is asking us to find the lowest ASCII sum of deleted characters required to make two strings equal. To solve this, we can use dynamic programming to find the longest common subsequence (LCS) between the two strings. The LCS represents the common characters between the two strings, and the chara...
1
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_. **Example 1:** **Input:** s1 = "sea ", s2 = "eat " **Output:** 231 **Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum. Deleting "t " from "eat " adds 116 to ...
Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].
Modified Edit Distance Solution
minimum-ascii-delete-sum-for-two-strings
0
1
B# Code\n```\nclass Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n v=[]\n for i in range(len(s1)+1):\n l=[]\n for j in range(len(s2)+1):\n l.append(0)\n v.append(l)\n s=0\n for i in range(len(s1)):\n s+=ord(s1[...
1
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_. **Example 1:** **Input:** s1 = "sea ", s2 = "eat " **Output:** 231 **Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum. Deleting "t " from "eat " adds 116 to ...
Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].
DP | MEMOIZATION | python3 | O(MN)
minimum-ascii-delete-sum-for-two-strings
0
1
# Complexity\n- Time complexity:\nO(M.N)\n\n- Space complexity:\nO(M.N)\n\n# Code\n```\nclass Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n\n def dfs(i, j):\n # suppose we reach the end of one string, the we have to delete the chars from other string\n if i == len(s1...
1
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_. **Example 1:** **Input:** s1 = "sea ", s2 = "eat " **Output:** 231 **Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum. Deleting "t " from "eat " adds 116 to ...
Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].
Python solution using right min and current max
max-chunks-to-make-sorted-ii
0
1
**Algorithm and Intuition:** We have to maximize the number of chunks or partitions we can make. The idea is suppose we are at index i and we know that the minimum element from i+1 to last element is greater than or equal to the maximum element till index i then we can say that this partition between index i and i+1 is...
8
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Python solution using right min and current max
max-chunks-to-make-sorted-ii
0
1
**Algorithm and Intuition:** We have to maximize the number of chunks or partitions we can make. The idea is suppose we are at index i and we know that the minimum element from i+1 to last element is greater than or equal to the maximum element till index i then we can say that this partition between index i and i+1 is...
8
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` r...
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
Solution
max-chunks-to-make-sorted-ii
1
1
```C++ []\nclass Solution {\npublic:\n int maxChunksToSorted(vector<int>& arr) {\n int n=arr.size();\n vector<int> rightMin(n+1,0);\n rightMin[n]=INT_MAX;\n for(int i=n-1;i>=0;i--){\n rightMin[i]=min(arr[i],rightMin[i+1]);\n }\n int leftMax=-1;\n int chunks...
2
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Solution
max-chunks-to-make-sorted-ii
1
1
```C++ []\nclass Solution {\npublic:\n int maxChunksToSorted(vector<int>& arr) {\n int n=arr.size();\n vector<int> rightMin(n+1,0);\n rightMin[n]=INT_MAX;\n for(int i=n-1;i>=0;i--){\n rightMin[i]=min(arr[i],rightMin[i+1]);\n }\n int leftMax=-1;\n int chunks...
2
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` r...
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
[Python3] Solution with using monotonic stack with comments
max-chunks-to-make-sorted-ii
0
1
```\n"""\nThe main idea is to get longest non-decreasing interval.\n\nFor decreasing interval (such an interval that we need to sort) we must the maximum of such interval.\n\nExample:\n\narr: [3,8,9,4,5]\n\n0. [] - empty stack\n1. [3] - it is non-decreasing interval\n2. [3,8] - it is non-decreasing interval\n3. [3,8,9]...
3
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
[Python3] Solution with using monotonic stack with comments
max-chunks-to-make-sorted-ii
0
1
```\n"""\nThe main idea is to get longest non-decreasing interval.\n\nFor decreasing interval (such an interval that we need to sort) we must the maximum of such interval.\n\nExample:\n\narr: [3,8,9,4,5]\n\n0. [] - empty stack\n1. [3] - it is non-decreasing interval\n2. [3,8] - it is non-decreasing interval\n3. [3,8,9]...
3
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` r...
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
DFS Marking Every Islands | Full Explanation + Hints | 99.87% faster
making-a-large-island
0
1
# Intuition\nWe can mark all the islands in one full loop. Then we can count all the unique changed indices around an unchanged (zeroes) index one by one and compare to return the maximum of all.\n\n# Approach\nTreat all these points as separate hints and try the problem again after reading a single point (for best res...
2
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of `1`s. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** ...
null
DFS Marking Every Islands | Full Explanation + Hints | 99.87% faster
making-a-large-island
0
1
# Intuition\nWe can mark all the islands in one full loop. Then we can count all the unique changed indices around an unchanged (zeroes) index one by one and compare to return the maximum of all.\n\n# Approach\nTreat all these points as separate hints and try the problem again after reading a single point (for best res...
2
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
Python || Easy || DSU
making-a-large-island
0
1
```\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n def find(u):\n if u==parent[u]:\n return u\n else:\n parent[u]=find(parent[u])\n return parent[u]\n def union(u,v):\n pu,pv=find(u),find(v)\n ...
4
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of `1`s. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** ...
null
Python || Easy || DSU
making-a-large-island
0
1
```\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n def find(u):\n if u==parent[u]:\n return u\n else:\n parent[u]=find(parent[u])\n return parent[u]\n def union(u,v):\n pu,pv=find(u),find(v)\n ...
4
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
89% TC and 50% SC easy python solution
making-a-large-island
0
1
```\ndef largestIsland(self, grid: List[List[int]]) -> int:\n\t@lru_cache(None)\n\tdef dfs(i, j, c):\n\t\tgrid[i][j] = c\n\t\ttemp = 1\n\t\tfor x, y in dir:\n\t\t\tif(0<=i+x<n and 0<=j+y<n and grid[i+x][j+y] == 1):\n\t\t\t\ttemp += dfs(i+x, j+y, c)\n\t\treturn temp\n\tn = len(grid)\n\tdir = [(1, 0), (-1, 0), (0, 1), (0...
1
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of `1`s. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** ...
null
89% TC and 50% SC easy python solution
making-a-large-island
0
1
```\ndef largestIsland(self, grid: List[List[int]]) -> int:\n\t@lru_cache(None)\n\tdef dfs(i, j, c):\n\t\tgrid[i][j] = c\n\t\ttemp = 1\n\t\tfor x, y in dir:\n\t\t\tif(0<=i+x<n and 0<=j+y<n and grid[i+x][j+y] == 1):\n\t\t\t\ttemp += dfs(i+x, j+y, c)\n\t\treturn temp\n\tn = len(grid)\n\tdir = [(1, 0), (-1, 0), (0, 1), (0...
1
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
Python short and clean. O(n * k). Functional programming.
verifying-an-alien-dictionary
0
1
# Approach\n1. Create an `ordinal` hashmap which maps alien characters to an integer such that `ordinal[x] < ordinal[y] implies x comes before y`.\nAdd an `EMPTY` character at the lowest ordinal to make comparisions easier.\n\n2. Define `is_lexico` which takes `s1` and `s2` and returns `true` if `s1` comes before `s2` ...
1
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `wor...
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Python short and clean. O(n * k). Functional programming.
verifying-an-alien-dictionary
0
1
# Approach\n1. Create an `ordinal` hashmap which maps alien characters to an integer such that `ordinal[x] < ordinal[y] implies x comes before y`.\nAdd an `EMPTY` character at the lowest ordinal to make comparisions easier.\n\n2. Define `is_lexico` which takes `s1` and `s2` and returns `true` if `s1` comes before `s2` ...
1
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names. ...
null
Easy Python Solution - Concatenation
concatenation-of-array
0
1
\n# Code\n```\nclass Solution:\n def getConcatenation(self, nums: List[int]) -> List[int]:\n return 2*nums\n```
3
Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**). Specifically, `ans` is the **concatenation** of two `nums` arrays. Return _the array_ `ans`. **Example 1:** **Input:** nums = \[1,2,1\...
What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is...
Two Python Solutions | Concatenate or Repeat
concatenation-of-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to return a new array that repeats the original array twice.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n### Approach 1\nWe can concatenate the original `nums` array with itself using the `+` operator.\...
6
Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**). Specifically, `ans` is the **concatenation** of two `nums` arrays. Return _the array_ `ans`. **Example 1:** **Input:** nums = \[1,2,1\...
What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is...
simple 2 lines code python
concatenation-of-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsimple multiply\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,...
0
Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**). Specifically, `ans` is the **concatenation** of two `nums` arrays. Return _the array_ `ans`. **Example 1:** **Input:** nums = \[1,2,1\...
What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is...
Python 9 line concise code With intuition explained using example.(Beats 87%)
unique-length-3-palindromic-subsequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo this problem might be difficult to grasp even after seeing the solution.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can observe that for a pallindrome with 3 length(note this)\nonly requirement is the fi...
4
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** ...
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
【Video】Give me 8 minutes - How we think about a solution
unique-length-3-palindromic-subsequences
1
1
# Intuition\nFind the same characters at the both sides.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/Tencj59MHAc\n\n\u203B Since I recorded that video last year, there might be parts that could be unclear. If you have any questions, feel free to leave a comment.\n\n\u25A0 Timeline of the video\n\n`0:00` Read the que...
82
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** ...
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || Easy Approaches || EXPLAINED🔥
unique-length-3-palindromic-subsequences
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n\n#### ***Approach 1(Counting in Between)***\n1. **Initialization and Index Storage:**\n\n - The code begins by initializing variables, such as `n` (size of the input string s) and `result` (the count of palindromic subsequenc...
2
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** ...
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
[Python, Rust] Elegant & Short | O(n) | 99.67% Faster | Left & Right Index
unique-length-3-palindromic-subsequences
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```python []\nclass Solution:\n def countPalindromicSubsequence(self, s: str) -> int:\n subsequences = 0\n\n for c in ascii_lowercase:\n left, right = s.find(c), s.rfind(c)\n if left != right:\n ...
2
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** ...
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
Python3 Solution
unique-length-3-palindromic-subsequences
0
1
\n```\nclass Solution:\n def countPalindromicSubsequence(self, s: str) -> int:\n ans=0\n for i in range(0,26):\n c=chr(i+ord(\'a\'))\n if c in s:\n first=s.index(c)\n last=s.rindex(c)\n if first!=last:\n u=set()\n ...
2
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** ...
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
Easy Solution with intuition in C++ and Python
unique-length-3-palindromic-subsequences
0
1
# Intuition\nWe only need palindromic subsequences of length three. Which means the first and last characters will be same and there is only one other character in between them. Our job is to find if two characters are same from the left and right end and if they are, add the unique characters (which will form unique p...
1
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** ...
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
Go/Python/JavaScript/Java O(n) time | O(1) space
unique-length-3-palindromic-subsequences
1
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```golang []\nfunc countPalindromicSubsequence(s string) int {\n pos := make(map[rune][]int)\n for i,letter := range(s...
2
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** ...
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
Python Solution
unique-length-3-palindromic-subsequences
0
1
# Approach\nTry to find the starting index and ending index of each letter and try to find the unique element between the indexes and add the that to the result this gives you the solution.\n\n# Code\n```\nclass Solution:\n def countPalindromicSubsequence(self, s: str) -> int:\n d=dict()\n for i in ran...
1
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** ...
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
O(1) time | O(1) space | solution explained
check-if-move-is-legal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA move is legal if after changing the color of the cell, the cell becomes the end point of a good line. \n\nA line can be vertical, horizontal, or diagonal. A line is a good line if:\n- has at least 3 blocks/cells\n- starting and ending c...
0
You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`. Each move in this game consists of choosing a free cell and changing i...
null
Best Python3 Solution. Beats 50%
check-if-move-is-legal
0
1
Just Enumerate all possible directions\n\n# Code\n```\nclass Solution:\n def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n m=len(board)\n n=len(board[0])\n \n lin=[[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,1],[-1,-1],[1,-1]]\n\n def other(x):\n ...
0
You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`. Each move in this game consists of choosing a free cell and changing i...
null
🧐 Try 8 possible directions
check-if-move-is-legal
0
1
# Intuition\nThe cell `board[rMove][cMove]` should be one of the endpoints, so we just try all possible paths(vertical, horizontal, and diagonal). There are 8 possible directions in total.\n\nAnd we **maintain an invariant that** - we only add the cell with opposite color along the direction.\n\n| go top-left | go u...
0
You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`. Each move in this game consists of choosing a free cell and changing i...
null
[c++ & Python] short and concise
find-greatest-common-divisor-of-array
0
1
\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n + log(phi)(min(min, max)))$$\n the log one is of Euclidean Algorithm for GCD\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)$$ -->\...
1
Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`. The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers. **Example 1:** **Input:** nums = \[2,5,6,9,10\] **Output:** 2 **Explanation:** ...
Try to use as much of the range of a person who is "it" as possible. Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet. If the person who is not "it" can be caught, pair them together and repeat the process. If the person who is not...
Simple Python Solution ||O(N)
find-greatest-common-divisor-of-array
0
1
Time Complexcity O(N)\nSpace complexcity O(1)\n```\nclass Solution:\n def findGCD(self, nums: List[int]) -> int:\n m=max(nums)\n n=min(nums)\n ans=1\n for i in range(2,n+1):\n print(i)\n if m%i==0 and n%i==0:\n ans=i\n return ans\n```
1
Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`. The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers. **Example 1:** **Input:** nums = \[2,5,6,9,10\] **Output:** 2 **Explanation:** ...
Try to use as much of the range of a person who is "it" as possible. Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet. If the person who is not "it" can be caught, pair them together and repeat the process. If the person who is not...
Python3 || 1 lined beginner solution || Beats 81.80%.
find-greatest-common-divisor-of-array
0
1
# Code\n```\nclass Solution:\n def findGCD(self, nums: List[int]) -> int:\n return gcd(min(nums),max(nums))\n\n```\n# Please upvote if you find the solution helpful.\uD83D\uDE4F
3
Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`. The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers. **Example 1:** **Input:** nums = \[2,5,6,9,10\] **Output:** 2 **Explanation:** ...
Try to use as much of the range of a person who is "it" as possible. Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet. If the person who is not "it" can be caught, pair them together and repeat the process. If the person who is not...
Math solution Python MAANG
find-greatest-common-divisor-of-array
0
1
# Intuition\nFor finding GCD we can use math formula: a * b // lcd(a, b)\n\n# Approach\nInitially finding min and max values in array. Then find LCD and return answer.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n# Code\n```\nclass Solution:\n def findGCD(self, nums: List[int]) -> int:\n ...
2
Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`. The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers. **Example 1:** **Input:** nums = \[2,5,6,9,10\] **Output:** 2 **Explanation:** ...
Try to use as much of the range of a person who is "it" as possible. Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet. If the person who is not "it" can be caught, pair them together and repeat the process. If the person who is not...
C++/Python bit Manip vs Cantor method||0ms beats 100%||w Math proof
find-unique-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere are 2 methods, 3 C++ & 1 python solutions, provided.\nOne is very standard. Define a function `int toInt(string& nums)` converting a binary string to its int number `x`.\n\nThere are numbers for choice, say `[0, 1,..., 2**len-1]`. \n...
9
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Elegant, greedy, short
find-unique-binary-string
0
1
# Approach\nGiven an array nums consisting of binary strings, we need to find a binary string that differs from all the binary strings in the array. We can achieve this by iterating through each position in the binary strings and flipping the bit at that position. This will ensure that the resulting binary string is di...
22
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
【Video】Give me 7 minutes - How we think about a solution
find-unique-binary-string
1
1
# Intuition\nConvert input strings to integer.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/tJ_Eu2S4334\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`1:39` Why you need to iterate through input array with len(nums) + 1?\n`2:25` Coding\n`3:56` Explain part of my solution code.\n`3:08`...
28
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
🚀 Sorting & Cantor's Diagonal Argument || Explained Intuition 🚀
find-unique-binary-string
1
1
# Problem Description\n\nWrite a function that takes an array of length `n` of **unique** **binary** strings, each of length `n`, as input. The task is to **find** and return a binary string of length `n` that does not **exist** in the given array. \nIn case there are multiple valid answers, the function is allowed to ...
37
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Python3 Solution
find-unique-binary-string
0
1
\n```\nclass Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n n=len(nums)\n s=set(int(x,2) for x in nums)\n def pod(x,n):\n n1=len(x)\n return ("0"*(n-n1))+x\n for x in range(1<<n):\n if x not in s:\n return pod(bin...
4
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
[Python, Java, Rust] Elegant & Short | O(n) | Cantor Diagonal Argument
find-unique-binary-string
1
1
# Approach\nGet more about Cantor diagonal argument [here](https://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument)\n![image.png](https://assets.leetcode.com/users/images/09abc2b3-3a3d-4182-b18d-6c668d4ed2f5_1700127465.9120343.png)\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Cod...
3
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
HEART BREAKiNG SOLUTiON by PRODONiK (Java, C#, Python, C++, Ruby)
find-unique-binary-string
1
1
![image.png](https://assets.leetcode.com/users/images/7f8a21d5-20cc-4b54-a8e6-734d8396f557_1700107165.1445866.png)\n\n# Intuition\nThe intuition behind this solution is to construct a binary string that is different from each binary string in the given array.\n\n# Approach\nIterate through the binary representations of...
2
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
faster than 100 percent solutions
find-unique-binary-string
0
1
# Intuition:\nThe goal is to find a binary string that does not appear in the given list of binary strings. One approach is to iterate through each position of the binary strings and choose the opposite digit. If the digit at position i is \'1\', we can choose \'0\', and if it\'s \'0\', we can choose \'1\'. This way, w...
2
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Simple Easy Python Solution | Beats 99% | Accepted 🔥🚀✅✅✅
find-unique-binary-string
0
1
# Code\n```\nclass Solution:\n def findDifferentBinaryString(self, x: List[str]) -> str:\n t,i,x=len(x[0]),0,sorted([int(j,2) for j in x])\n while i<len(x) and i==x[i]: i+=1\n return "0"*(t-len(bin(i))+2)+bin(i)[2:]\n```
1
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Simple solution in Python3
find-unique-binary-string
0
1
# Intuition\nHere we have:\n- `nums` as list of integers in **binary** representation\n- our goal is to find **the unique combination** of integers with length of `nums`\n\nThis\'s achievable with a **mathematical proof**: if you use for each bit **an opposite bit** by **XOR** operator, you\'ll get a unique combination...
1
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
[Python3] greedy
find-array-given-subset-sums
0
1
Please check this [commit](https://github.com/gaosanyong/leetcode/commit/12942515a0e681f7ed804e66ec8de2b3423cadb0) for solutions of weekly 255. \n```\nclass Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n sums.sort()\n ans = []\n for _ in range(n): \n diff ...
0
You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order). Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **mul...
Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number.
Python | Backtracking | 664ms | 100% time and space | Explanation
minimum-number-of-work-sessions-to-finish-the-tasks
0
1
* I think the test cases are little weak, because I just did backtracking and a little pruning and seems to be 4x faster than bitmask solutions.\n* The question boils down to finding minimum number of subsets such that each subset sum <= sessionTime. I maintain a list called subsets, where I track each subset sum. For ...
26
There are `n` tasks assigned to you. The task times are represented as an integer array `tasks` of length `n`, where the `ith` task takes `tasks[i]` hours to finish. A **work session** is when you work for **at most** `sessionTime` consecutive hours and then take a break. You should finish the given tasks in a way tha...
Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)
Python DP + Bitmask
minimum-number-of-work-sessions-to-finish-the-tasks
0
1
# Intuition\nTry to pack as many hours into a session as possible\nbitmasking: dp(space_left_in_cur_bag, mask): return the smallest n.o bags required to pack the remaning tasks, including the current bag.\n```\ndp(space_left_in_cur_bag, mask) = \n 1 if mask == 0, i.e no tasks left,\n 1 + dp(sessionTime, mask) if ...
0
There are `n` tasks assigned to you. The task times are represented as an integer array `tasks` of length `n`, where the `ith` task takes `tasks[i]` hours to finish. A **work session** is when you work for **at most** `sessionTime` consecutive hours and then take a break. You should finish the given tasks in a way tha...
Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)
Simple python backtrack, no bitmask
minimum-number-of-work-sessions-to-finish-the-tasks
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There are `n` tasks assigned to you. The task times are represented as an integer array `tasks` of length `n`, where the `ith` task takes `tasks[i]` hours to finish. A **work session** is when you work for **at most** `sessionTime` consecutive hours and then take a break. You should finish the given tasks in a way tha...
Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)
Python 30 ms: Sort task first and then Backtracking
minimum-number-of-work-sessions-to-finish-the-tasks
0
1
# Complexity\n- Time complexity:\nWorst case: O(n!)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def minSessions(self, tasks: List[int], sessionTime: int) -> int:\n self.tasks = sorted(tasks, reverse = True)\n self.nTasks = len(tasks)\n self.minSession = self.nTasks\n se...
0
There are `n` tasks assigned to you. The task times are represented as an integer array `tasks` of length `n`, where the `ith` task takes `tasks[i]` hours to finish. A **work session** is when you work for **at most** `sessionTime` consecutive hours and then take a break. You should finish the given tasks in a way tha...
Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)
Python (Simple Dynamic Programming)
first-day-where-you-have-been-in-all-the-rooms
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day. Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `...
Is it possible to swap one character in the first half of the palindrome to make the next one? Are there different cases for when the length is odd and even?
Python | Two Solutions
first-day-where-you-have-been-in-all-the-rooms
0
1
# Approach\nFirst approach (at the bottom of the code) was to directly simulate the process using caching. We keep track of the last day a room was visited in ```last_day``` and the number of times a room has been visited in ```visits```. The calculations performed coalesce into the dynamic programming solution at the ...
0
There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day. Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `...
Is it possible to swap one character in the first half of the palindrome to make the next one? Are there different cases for when the length is odd and even?
[Python3] union-find
gcd-sort-of-an-array
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/84115397f703f3005c3ae0d5d759f4ac64f65de4) for solutions of weekly 257.\n```\nclass UnionFind:\n \n def __init__(self, n): \n self.parent = list(range(n))\n self.rank = [1] * n\n \n def find(self, p): \n if ...
11
You are given an integer array `nums`, and you can perform the following operation **any** number of times on `nums`: * Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is the **greatest common divisor** of `nums[i]` and `nums[j]`. Return `true`...
null
Beats 88%, solution with detailed explanation and intuition!
gcd-sort-of-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We can exchange 2 numbers if and only if they have gcd > 1\n- If we want the minimum number in the array to reach the 0 index we need to be able to do a sequence of swaps which results in the min number and the present number in index 0...
0
You are given an integer array `nums`, and you can perform the following operation **any** number of times on `nums`: * Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is the **greatest common divisor** of `nums[i]` and `nums[j]`. Return `true`...
null
Easiest and Fast Python Solution
reverse-prefix-of-word
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
python | Two pointers - easy solution
reverse-prefix-of-word
0
1
```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n ## Two pointers\n res = list(word)\n left = 0\n \n for i in range(len(word)):\n if res[i] == ch:\n while left <= i:\n res[i], res[left] = res[left], res[i]\n ...
1
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
reverse prefix python3
reverse-prefix-of-word
0
1
# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n prefix = \'\'\n for i, c in enumerate(word):\n if c == ch:\n return (prefix + c)[::-1] + word[i+1:]\n prefix +...
4
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
two methods || python || easy to understand
reverse-prefix-of-word
0
1
\n\n# Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n """\n #method 1:\n for i in range(len(word)):\n if word[i]==ch:\n return word[:i+1][::-1]+word[i+1:]\n return word"""\n #method 2:\n l=0\n r=word.find(ch...
8
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
[Python3] Math GCD + Hash Table - Concise and Simple
number-of-pairs-of-interchangeable-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the `ith` rectangle. Two rectangles `i` and `j` (`i < j`) are considered **interchangeable** if they have the **same** width-to-height ratio. More formall...
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
O(n) time and O(1) space complexity
number-of-pairs-of-interchangeable-rectangles
0
1
class Solution:\n def interchangeableRectangles(self, nums: List[List[int]]) -> int:\n \n for i in range(0,len(nums)):\n nums[i]=nums[i][0]/nums[i][1]\n \n dic={}\n for i in nums:\n if i in dic:\n dic[i]+=1\n else:\n di...
0
You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the `ith` rectangle. Two rectangles `i` and `j` (`i < j`) are considered **interchangeable** if they have the **same** width-to-height ratio. More formall...
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
Python HashMap Solution
number-of-pairs-of-interchangeable-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the `ith` rectangle. Two rectangles `i` and `j` (`i < j`) are considered **interchangeable** if they have the **same** width-to-height ratio. More formall...
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
Python3 solution, beats 100%, 2 solutions.
number-of-pairs-of-interchangeable-rectangles
0
1
\n\n# Code\n```\nclass Solution:\n def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n # solution 1 (w math formula)\n res = 0\n hashmap = {}\n for r in rectangles:\n rate = r[0] / r[1]\n hashmap[rate] = hashmap.get(rate, 0) + 1\n for c ...
0
You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the `ith` rectangle. Two rectangles `i` and `j` (`i < j`) are considered **interchangeable** if they have the **same** width-to-height ratio. More formall...
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
O(n) beats 99.75% single for loop no if statements needed
number-of-pairs-of-interchangeable-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKeep track of how many ratios we have seen. This can be used to calculate how many pairs of interchangeable rectangles.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCalculate the ratio for a given rectangle. Updat...
0
You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the `ith` rectangle. Two rectangles `i` and `j` (`i < j`) are considered **interchangeable** if they have the **same** width-to-height ratio. More formall...
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
Easy Understand | Simple Method | Java | Python ✅
maximum-product-of-the-length-of-two-palindromic-subsequences
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse mask to save all combination in hashmap and use "&" bit manipulation to check if two mask have repeated letter.\n\n# Complexity\n- Time complexity:\n<!-- Add your ...
9
Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index. Return _the **maximum** possible **product** of the lengths of the two palindromic subsequ...
Let's note that the only thing that matters is how many stones were removed so we can maintain dp[numberOfRemovedStones] dp[x] = max(sum of all elements up to y - dp[y]) for all y > x
Brute Force Appro
maximum-product-of-the-length-of-two-palindromic-subsequences
0
1
\n\n# Code\n```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n N,pali = len(s),{} # bitmask = length\n\n for mask in range(1,1<<N): # 1 << N == 2**N\n subseq = ""\n for i in range(N):\n if mask & (1<<i):\n subseq+=s[i]\n\n if...
1
Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index. Return _the **maximum** possible **product** of the lengths of the two palindromic subsequ...
Let's note that the only thing that matters is how many stones were removed so we can maintain dp[numberOfRemovedStones] dp[x] = max(sum of all elements up to y - dp[y]) for all y > x
Unleash the Power of Bit Manipulation: Maximize Product of Palindromic Subsequences!
maximum-product-of-the-length-of-two-palindromic-subsequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking to find the maximum product of the lengths of two non-intersecting palindromic subsequences. My first thought is to generate all possible subsequences and check which ones are palindromes. Then, I can iterate over al...
0
Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index. Return _the **maximum** possible **product** of the lengths of the two palindromic subsequ...
Let's note that the only thing that matters is how many stones were removed so we can maintain dp[numberOfRemovedStones] dp[x] = max(sum of all elements up to y - dp[y]) for all y > x
Python3 DP solution, faster than 99% Python3
maximum-product-of-the-length-of-two-palindromic-subsequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the maximum string length is just 12, we can generate all possible subsequence then calculate the longest Palindromic Subsequences\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use DP to find the longest...
0
Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index. Return _the **maximum** possible **product** of the lengths of the two palindromic subsequ...
Let's note that the only thing that matters is how many stones were removed so we can maintain dp[numberOfRemovedStones] dp[x] = max(sum of all elements up to y - dp[y]) for all y > x
Python Solution
maximum-product-of-the-length-of-two-palindromic-subsequences
0
1
# Complexity\n- Time complexity: O(2 ** N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(2 ** N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n N, pali = len(s), {} # bitmask: length\n\n ...
0
Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index. Return _the **maximum** possible **product** of the lengths of the two palindromic subsequ...
Let's note that the only thing that matters is how many stones were removed so we can maintain dp[numberOfRemovedStones] dp[x] = max(sum of all elements up to y - dp[y]) for all y > x
Python (Simple DFS + Union Find)
smallest-missing-genetic-value-in-each-subtree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There is a **family tree** rooted at `0` consisting of `n` nodes numbered `0` to `n - 1`. You are given a **0-indexed** integer array `parents`, where `parents[i]` is the parent for node `i`. Since node `0` is the **root**, `parents[0] == -1`. There are `105` genetic values, each represented by an integer in the **inc...
Keep a frequency map of the elements in each window. When the frequency of the element is 0, remove it from the map. The answer to each window is the size of the map.
[Python3] dfs
smallest-missing-genetic-value-in-each-subtree
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/0de189059bd6af4dabe23d9066dde1655f3334fc) for solutions of weekly 258. \n```\nclass Solution:\n def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:\n ans = [1] * len(parents)\n if 1 in nums...
1
There is a **family tree** rooted at `0` consisting of `n` nodes numbered `0` to `n - 1`. You are given a **0-indexed** integer array `parents`, where `parents[i]` is the parent for node `i`. Since node `0` is the **root**, `parents[0] == -1`. There are `105` genetic values, each represented by an integer in the **inc...
Keep a frequency map of the elements in each window. When the frequency of the element is 0, remove it from the map. The answer to each window is the size of the map.
[Python] Clean & concise. Dictionary T.C O(N)
count-number-of-pairs-with-absolute-difference-k
0
1
```\nclass Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n counter = 0\n for num in nums:\n tmp, tmp2 = num - k, num + k\n if tmp in seen:\n counter += seen[tmp]\n if tmp2 in seen:\n ...
47
Given an integer array `nums` and an integer `k`, return _the number of pairs_ `(i, j)` _where_ `i < j` _such that_ `|nums[i] - nums[j]| == k`. The value of `|x|` is defined as: * `x` if `x >= 0`. * `-x` if `x < 0`. **Example 1:** **Input:** nums = \[1,2,2,1\], k = 1 **Output:** 4 **Explanation:** The pairs wit...
Subtract the sum of chalk[i] from k until k is less than that sum Now just iterate over the array if chalk[i] is less thank k this is your answer otherwise this i is the answer
2 Approach Python Solution O(n) & O(n2)
count-number-of-pairs-with-absolute-difference-k
0
1
O(n)\n```\nclass Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n count = 0\n \n hash = {}\n \n for i in nums:\n if i in hash:\n hash[i] +=1\n else:\n hash[i] = 1\n \n for i in hash:\...
8
Given an integer array `nums` and an integer `k`, return _the number of pairs_ `(i, j)` _where_ `i < j` _such that_ `|nums[i] - nums[j]| == k`. The value of `|x|` is defined as: * `x` if `x >= 0`. * `-x` if `x < 0`. **Example 1:** **Input:** nums = \[1,2,2,1\], k = 1 **Output:** 4 **Explanation:** The pairs wit...
Subtract the sum of chalk[i] from k until k is less than that sum Now just iterate over the array if chalk[i] is less thank k this is your answer otherwise this i is the answer
Python3, Time: O(n), Using dictionary
count-number-of-pairs-with-absolute-difference-k
0
1
```\nclass Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n count=0\n from collections import Counter\n mydict=Counter(nums) \n for i in mydict:\n if i+k in mydict:\n count=count+ mydict[i]*mydict[i+k] \n return count\n```
5
Given an integer array `nums` and an integer `k`, return _the number of pairs_ `(i, j)` _where_ `i < j` _such that_ `|nums[i] - nums[j]| == k`. The value of `|x|` is defined as: * `x` if `x >= 0`. * `-x` if `x < 0`. **Example 1:** **Input:** nums = \[1,2,2,1\], k = 1 **Output:** 4 **Explanation:** The pairs wit...
Subtract the sum of chalk[i] from k until k is less than that sum Now just iterate over the array if chalk[i] is less thank k this is your answer otherwise this i is the answer
Python3 || 9 lines, Counter, with explanation || T/M: 99.6%/81%
find-original-array-from-doubled-array
0
1
Pretty much explains itself. It uses a Counter, handles the zeros separately, then iterates\nthrough the keys of the Counter to check the doubles and to build the answer array.\n\nI\'m no expert, but I guess time/space to be *O*(*n*)/*O*(*n*). (Counter is *O*(*n*) on both I believe.)\n[edit: @jacobquicksilver--oops, y...
5
An integer array `original` is transformed into a **doubled** array `changed` by appending **twice the value** of every element in `original`, and then randomly **shuffling** the resulting array. Given an array `changed`, return `original` _if_ `changed` _is a **doubled** array. If_ `changed` _is not a **doubled** arr...
null
Python Solution
find-original-array-from-doubled-array
0
1
### 1\n```py\nclass Solution:\n def findOriginalArray(self, changed: List[int]) -> List[int]:\n if len(changed) % 2 == 1:\n return []\n data = Counter(changed)\n result = []\n for k in sorted(data):\n if data[k] < 0:\n return []\n elif k == ...
3
An integer array `original` is transformed into a **doubled** array `changed` by appending **twice the value** of every element in `original`, and then randomly **shuffling** the resulting array. Given an array `changed`, return `original` _if_ `changed` _is a **doubled** array. If_ `changed` _is not a **doubled** arr...
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
find-original-array-from-doubled-array
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R...
46
An integer array `original` is transformed into a **doubled** array `changed` by appending **twice the value** of every element in `original`, and then randomly **shuffling** the resulting array. Given an array `changed`, return `original` _if_ `changed` _is a **doubled** array. If_ `changed` _is not a **doubled** arr...
null
Python | Math + Sort + Counter
find-original-array-from-doubled-array
0
1
## Intuition\nAll numbers are non-negative, so if a double is present, it must be greater than or equal. We can sort the numbers from greatest to least, and pair the numbers with their doubles greedily.\n\n## Approach\nWe will use a `collections.Counter()` to keep track of how many of each number we have not paired yet...
3
An integer array `original` is transformed into a **doubled** array `changed` by appending **twice the value** of every element in `original`, and then randomly **shuffling** the resulting array. Given an array `changed`, return `original` _if_ `changed` _is a **doubled** array. If_ `changed` _is not a **doubled** arr...
null
python3 sorting+dynamic programming(with explicit explanation + test case)
maximum-earnings-from-taxi
0
1
# Intuition\nthis question is similar to [leetcode 80: maximum number of events that can be attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/), the two question uses simiar sorting and usage of stack/heap. In this solution, I used dynamic programming to use an array to keep track of...
2
There are `n` points on a road you are driving your taxi on. The `n` points on the road are labeled from `1` to `n` in the direction you are going, and you want to drive from point `1` to point `n` to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a ...
How many possible states are there for a given expression? Is there a data structure that we can use to solve the problem optimally?
[Python] Solution - Maximum Earnings from Taxi
maximum-earnings-from-taxi
0
1
\n**Problem** : To find the maximum earnings.\n\n**Idea** : Start to think in this way that we can track the maximum earning at each point .\neg : n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]\n\nWe want to loop from i = 1 to n and at each step check if this i is an end point or not .\nif...
4
There are `n` points on a road you are driving your taxi on. The `n` points on the road are labeled from `1` to `n` in the direction you are going, and you want to drive from point `1` to point `n` to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a ...
How many possible states are there for a given expression? Is there a data structure that we can use to solve the problem optimally?
DP solution | O(m+n) | Python Kotlin Javascript Java
maximum-earnings-from-taxi
1
1
# Intuition\nUse dynamic programming to solve this problem. \n\n# Approach\nUse a array dp to record best solution. dp[i] means the best solution end with index i. dp[i] >= dp[i-1]. If there is a ride end with index i, if we take this, the money we can get is `dp[start_i] + end_i - start_i + tip_i` , if it is greater t...
0
There are `n` points on a road you are driving your taxi on. The `n` points on the road are labeled from `1` to `n` in the direction you are going, and you want to drive from point `1` to point `n` to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a ...
How many possible states are there for a given expression? Is there a data structure that we can use to solve the problem optimally?
From Dumb to Pro with Just One Visit-My Promise to You with A Smart Approach to Minimize Operations
minimum-number-of-operations-to-make-array-continuous
1
1
# Intuition\n\nThe goal is to determine the minimum number of operations needed to make the numbers consecutive. To do this, we want to find the maximum unique element within a certain range, specifically from \'n\' to \'n + nums.size() - 1\', where \'n\' can be any element from the array. \n\nThe idea is that if we ch...
12
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
Easy To Understand || Sliding Window || C++ || Java
minimum-number-of-operations-to-make-array-continuous
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSorting and Removing Duplicates:\nFirst, the code sorts the input array nums in ascending order. This is done to make it easier to find the maximum and minimum elements.\nIt also removes any duplicate elements, ensuring that...
6
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
Simple Solution || Beginner Friendly || Easy to Understand ✅
minimum-number-of-operations-to-make-array-continuous
1
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- Sort the input array `nums` in ascending order.\n- Traverse the sorted array to remove duplicates and count unique elements in `uniqueLen`.\n- Initialize `ans` to the length of the input array, representing the maximum operations initially.\n- Itera...
82
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
[Python] Simple sort & queue, 2-liner
minimum-number-of-operations-to-make-array-continuous
0
1
# Intuition\n\nThe continuous array that the problem asks for is simply an array with the form `[x, x + 1, x + 2, x + 3, ..., x + n - 1]`, but scrambled. Let\'s call that original sorted form **sorted continuous**.\n\nTo simplify the problem, we simply need to find the longest incomplete **sorted continuous** array fro...
8
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
【Video】Give me 15 minutes - How we think about a solution
minimum-number-of-operations-to-make-array-continuous
1
1
Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nSorting input array...
85
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
Video Solution | Explanation With Drawings | In Depth | Java | C++ | Python 3
minimum-number-of-operations-to-make-array-continuous
1
1
# Intuition, approach and complexity dicsussed in detail in video solution\nhttps://youtu.be/W_2-2Ee7y-s\n# Code\nPython 3\n```\nclass Solution:\n def minOperations(self, nums):\n unqEles = set()\n unqs = []\n for num in nums:\n if num not in unqEles:\n unqs.append(num)...
1
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
✅☑[C++/C/Java/Python/JavaScript] || O(nlogn) || Sliding Window || EXPLAINED🔥
minimum-number-of-operations-to-make-array-continuous
1
1
# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n\n# Approaches\n***(Also explained in the code)***\n1. The code aims to find the minimum operations required to make the array "consecutive," where consecutive elements have a difference of at most `n-1`.\n\n1. We first insert all unique elements from the input array `nums` into...
2
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
Easy Solution using python
minimum-number-of-operations-to-make-array-continuous
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
Python super easy solution with intuition. Concept( set & binary search)
minimum-number-of-operations-to-make-array-continuous
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n If you observe the question carefully you can see that\n1. the frequency of the numbers does not matter the same number comes up once or many times does not matter in the end you just need to find maximum **unique** numbers that are agre...
1
You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. `nums` is considered **continuous** if both of the following conditions are fulfilled: * All elements in `nums` are **unique**. * The difference between the **maximum** element and the **minimu...
Add all the words to a trie. Check the longest path where all the nodes are words.
Python3 - Easy Solution for Beginners!
final-value-of-variable-after-performing-operations
0
1
\n# Code\n```\nclass Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n result = 0\n for i in range(len(operations)):\n if(operations[i] == \'++X\' or operations[i] == \'X++\'):\n result = result + 1\n else:\n result = re...
1
There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. Given an array of strings `operations` containi...
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
Solution of final value of variable after performing operations problem
final-value-of-variable-after-performing-operations
0
1
# Complexity\n- Time complexity:\n$$O(n)$$ - as loop takes linear time\n\n- Space complexity:\n$$O(1)$$ - as we use extra space for answer equal to a constant\n\n# Solution_1\n```\nclass Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n answer = 0\n for i in operations:\n...
1
There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. Given an array of strings `operations` containi...
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
Simple Solutions in Py and Cpp😉
final-value-of-variable-after-performing-operations
0
1
# Solution in C++\n```\nclass Solution {\npublic:\n int finalValueAfterOperations(vector<string>& operations) {\n int answer = 0;\n for (int i = 0; i < operations.size(); i++ ){\n if (operations[i] == "X++" || operations[i] == "++X"){answer++;}\n else if (operations[i] == "--X" ||...
2
There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. Given an array of strings `operations` containi...
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
Very easy solution
final-value-of-variable-after-performing-operations
0
1
# Best Solution very Easy\n\n# Code\n```\nclass Solution:\n def finalValueAfterOperations(self, arr: List[str]) -> int:\n a=0\n for i in arr:\n if i[0]=="+" or i[-1]=="+":\n a+=1\n else:\n a-=1\n return a\n```
1
There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. Given an array of strings `operations` containi...
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
Very Easy Python3 Count Function Use 5 Lines Codes
final-value-of-variable-after-performing-operations
0
1
We can use simple python count function to get count value of given conditions\nand solve it very easily and with compact solution :\n\n```class Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n \n \n A=operations.count("++X")\n B=operations.count("X++")\n ...
37
There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. Given an array of strings `operations` containi...
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
Easy 💥 C++ Solution [ TESLA 🚘 SDE Intern Interview😳 ]
final-value-of-variable-after-performing-operations
1
1
\n## Please Upvote if it Helps \uD83D\uDE4F\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int finalValueAfterOperations(vector<string>& opera...
9
There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. Given an array of strings `operations` containi...
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
[Python 3] Using reduce, 1 line
final-value-of-variable-after-performing-operations
0
1
```\nclass Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n return reduce(lambda a, b: a + (1 if b[1] == \'+\' else -1) , operations, 0)\n```
13
There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. Given an array of strings `operations` containi...
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].