question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
remove-adjacent-almost-equal-characters
|
Java Greedy O(N)
|
java-greedy-on-by-hobiter-6rog
|
Intuition\n Describe your first thoughts on how to solve this problem. \nBe Greedy, when word[i] is almost the same with word[i - 1], always change word[i], whi
|
hobiter
|
NORMAL
|
2023-12-26T00:17:15.451873+00:00
|
2023-12-26T00:17:15.451890+00:00
| 29 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBe Greedy, when word[i] is almost the same with word[i - 1], always change word[i], which makes sure word[i] is never almost the same with word[i + 1]. It is always possible since we have 26 candidates. Then i += 2 to continue the loop. \n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n char[] arr = word.toCharArray();\n int i = 1, res = 0; \n while (i < arr.length) {\n if (isAlmost(arr[i], arr[i - 1])) {\n res++;\n i += 2;\n } else {\n i++;\n }\n }\n return res;\n }\n\n private boolean isAlmost(char a, char b) {\n return a == b || a - b == 1 || a - b == -1;\n }\n}\n```
| 3 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Remove Adjacent Almost-Equal Characters - 30 ms Beats 99.11% of users with Python3
|
remove-adjacent-almost-equal-characters-g4nk9
|
Complexity\n- Time complexity: The time complexity is O(n), where n is the length of the input string. The loop iterates through each character once.\n Add your
|
shaanshaban400
|
NORMAL
|
2023-12-24T11:15:43.828475+00:00
|
2023-12-24T11:15:43.828498+00:00
| 48 | false |
# Complexity\n- Time complexity: The time complexity is O(n), where n is the length of the input string. The loop iterates through each character once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The space complexity is O(1) as the additional space used (variables n, count, and i) does not depend on the size of the input.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n # Get the length of the input string\n n = len(word)\n\n # Initialize the count of pairs with almost equal characters\n count = 0\n\n # Start iterating from the second character\n i = 1\n\n # Iterate through the characters of the string\n while i < n:\n # Check if the absolute difference in ASCII values is less than or equal to 1\n if abs(ord(word[i-1]) - ord(word[i])) <= 1:\n # Increment the count if the condition is met\n count += 1\n # Move to the next pair by skipping one character\n i += 1\n\n # Move to the next character for the next iteration\n i += 1\n\n # Return the final count\n return count\n \n```
| 3 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
✅ Beats 100% | Greedy is faster.
|
beats-100-greedy-is-faster-by-abdelazizs-28ug
|
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n All we need is to check if the difference between the characters is not greater
|
abdelazizSalah
|
NORMAL
|
2023-12-24T05:00:19.530284+00:00
|
2023-12-24T05:00:19.530301+00:00
| 135 | false |
\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* All we need is to check if the difference between the characters is not greater than 1\n* if true, just increment the counter, and go for the next character. \n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. initialize a counter in which we store the result with 0.\n2. iterate over the given string for i = 1 to length of the string. \n 1. if the current character is greater than the previous character alphabetically\n 1. check if the difference between the greater - smaller <= 1 (near close)\n 1. increment the ans\n 2. increment i to avoid redundant evaluations.\n 2. do exactly the same if the character was less, but the greater charachter will now be the previous one.\n3. return the result.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. O(N) , where n is the length of the given string. \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. O(1) -> no auxilary space is needed.\n# Code\n```\n#pragma GCC optimize("O3")\n#pragma GCC optimize("Ofast", "inline", "ffast-math", "unroll-loops", "no-stack-protector")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native", "f16c")\nstatic const auto DPSolver = []()\n{ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return \'c\'; }();\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n DPSolver; \n int ans = 0;\n for(int i = 1;i<word.length();i++){\n \n if(word[i]>=word[i-1] && word[i]-word[i-1]<=1)\n {\n ans++;\n i++;\n }\n else if(word[i]<word[i-1] && word[i-1]-word[i]<=1){\n ans++;\n i++;\n }\n }\n return ans;\n }\n};\n```
| 3 | 0 |
['String', 'Dynamic Programming', 'Greedy', 'C++']
| 1 |
remove-adjacent-almost-equal-characters
|
O(N) TC & O(1) SC solution || easy and Intuitive || Explained
|
on-tc-o1-sc-solution-easy-and-intuitive-1wdyq
|
Intuition\nHere all we needed was how many such group (adjacent almost equal) are occuring & what is there size\n> once we have the size of such group we need c
|
gaurav-x5
|
NORMAL
|
2023-12-09T16:06:06.014798+00:00
|
2023-12-09T16:12:43.767489+00:00
| 158 | false |
# Intuition\nHere all we needed was how many such group (adjacent almost equal) are occuring & what is there size\n> once we have the size of such group we need count of replacement that can be calculated by an easy formula\nExamine the pattern\n\n> if group size is 2 we need 1 replacement -> 1\nif 3 we still need one which is middle element should be replaced -> 1\nsimilarly 4 alternate element should be replaced -> 2\nsame goes with 5 -> 2\n6 -> 3\n7 -> 3\n\nhence what we needed was group size/2 replacements.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int ans = 0;\n \n int currAdj = 1;\n for(int i = 1; i < word.length(); i++) {\n if(Math.abs(word.charAt(i) - word.charAt(i-1)) <= 1) {\n currAdj++;\n } else{\n ans += currAdj/2;\n currAdj = 1;\n }\n }\n \n if(currAdj > 1) {\n ans += currAdj/2;\n }\n return ans;\n }\n}\n```
| 3 | 0 |
['Math', 'Greedy', 'Java']
| 1 |
remove-adjacent-almost-equal-characters
|
O(N) Simple Easy Solution || Two Pointer || C++
|
on-simple-easy-solution-two-pointer-c-by-c5wv
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
puneet_3225
|
NORMAL
|
2024-12-30T10:57:33.573122+00:00
|
2024-12-30T10:57:33.573122+00:00
| 79 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int removeAlmostEqualCharacters(string word) {
int ans = 0;
int i = 0, j = 1;
int n = word.length();
if(n == 1)return 0;
while(j < n){
int a = word[i] - '0', b = word[j] - '0';
if(a == b || a + 1 == b || a == b + 1){
ans++;
i += 2, j += 2;
}
else {
i++;
j++;
}
}
return ans;
}
};
```
| 2 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
100% Beats || Easy to Understand with Intuition and Approach || Linear Complexity and Constant Space
|
100-beats-easy-to-understand-with-intuit-efaf
|
Intuition\n Describe your first thoughts on how to solve this problem. \nProblem straight forward tells us what we have to do, if we find any index such that it
|
Arrrrrpit
|
NORMAL
|
2023-12-11T07:43:54.369097+00:00
|
2023-12-11T07:43:54.369115+00:00
| 24 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nProblem straight forward tells us what we have to do, if we find any index such that it\'s adjacent character is either equal or different by one from the current index\'s character then we have to change it.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe start traversing our string from $index = 1$, and we initialise the variable $count = 0$, if we find a index where $s[index - 1] = s[index]$ or $abs(s[index] - s[index - 1]) = 1$ then we increment the $count$ variable and jump 2 indexes as the previous one and current one and the one next to it have already been taken care of. If we do not find this condition then we simply increment the $index$.\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Please Upvote!\n\n\n# Beats\n\n\n\n# Code\n```\nclass Solution\n{\npublic:\n int removeAlmostEqualCharacters(string word)\n {\n int count = 0, index = 1;\n while (index < word.size())\n {\n if (word[index] == word[index - 1] || abs(word[index] - word[index - 1]) == 1)\n {\n count++;\n index += 2;\n continue;\n }\n index++;\n }\n return count;\n }\n};\n```\n
| 2 | 0 |
['C++']
| 1 |
remove-adjacent-almost-equal-characters
|
6 lines Of Java Code Beats 100% || Best answer
|
6-lines-of-java-code-beats-100-best-answ-8duu
|
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
|
jashan_pal_singh_sethi
|
NORMAL
|
2023-12-10T08:18:36.039621+00:00
|
2023-12-10T08:18:36.039646+00:00
| 13 | false |
# 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 public int removeAlmostEqualCharacters(String word) {\n int op = 0;\n for(int i=1;i<word.length();i++) {\n if(isAlmostEqual(word.charAt(i-1),word.charAt(i))){\n op++;\n i++;\n }\n }\n return op;\n }\n private boolean isAlmostEqual(char a,char b) {\n return a==b || Math.abs(a-b)==1;\n }\n}\n\n```
| 2 | 0 |
['Math', 'String', 'Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Basic approach using cpp
|
basic-approach-using-cpp-by-pra__kash-lllt
|
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
|
pra__kash
|
NORMAL
|
2023-12-10T05:30:37.425907+00:00
|
2023-12-10T05:30:37.425935+00:00
| 11 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string x) {\n int ans = 0;\n for(int i = 1 ; i < x.size() ; i++){\n if(x[i] == x[i-1] || x[i]+1 == x[i-1] || x[i-1]+1 == x[i]){\n ans++;\n i++;\n }\n }\n return ans;\n }\n};\n```
| 2 | 0 |
['String', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Beats 100%. Efficient solution
|
beats-100-efficient-solution-by-farouk-d-yci4
|
Approach\n Describe your approach to solving the problem. \nFrom the problem, we only need to change a character to one that is not "almost equal" to its neighb
|
farouk-dev
|
NORMAL
|
2023-12-09T16:54:11.467081+00:00
|
2023-12-09T16:54:11.467106+00:00
| 30 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nFrom the problem, we only need to change a character to one that is not "almost equal" to its neighbouring characters (i.e, it\'s left and right). We only need to add 1 to our current answer and move 2 steps ahead. Why? it is assumed that anytime we change a character, we change it to one that is not close to any of its neighbours. Eg, "zzz" could be assumed as "zaz"\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n ans = 0\n \n i = 1\n while i < len(word):\n if abs(ord(word[i])-ord(word[i-1])) <= 1:\n ans += 1\n i += 2\n else:\n i += 1\n \n return ans\n \n```
| 2 | 0 |
['Greedy', 'Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple Java Solution || O(N) ⭐⭐⭐
|
simple-java-solution-on-by-shoryasharda0-elxo
|
Time complexity:O(n)\n\n# Code\n\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n \n StringBuilder str = new String
|
ShoryaSharda028
|
NORMAL
|
2023-12-09T16:02:41.832329+00:00
|
2023-12-09T16:02:41.832350+00:00
| 125 | false |
- Time complexity:O(n)\n\n# Code\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n \n StringBuilder str = new StringBuilder("");\n int n= word.length();\n str.append(word.charAt(0));\n \n for(int i=1;i<n;i++)\n {\n char curr= word.charAt(i);\n char prev= str.charAt(i-1);\n if(prev==\'#\')str.append(curr);\n else{\n if(prev!=\'#\' && Math.abs(curr-prev)!=1 && Math.abs(curr-prev)!=0) str.append(curr);\n else\n str.append("#");\n }\n }\n int count=0;\n for(int i=0;i<str.length();i++)\n {\n if(str.charAt(i)==\'#\') count++;\n }\n return count;\n \n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
BEATS 100%
|
beats-100-by-dummy_nick-gtf3
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Dummy_Nick
|
NORMAL
|
2025-04-09T18:58:17.347318+00:00
|
2025-04-09T18:58:17.347318+00:00
| 9 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int removeAlmostEqualCharacters(String word) {
int count = 0;
int n = word.length();
int i = 0;
while(i<n-1) {
char cur = word.charAt(i);
char next = word.charAt(i+1);
if(cur==next || Math.abs(cur-next) == 1) {
count++;
i += 2;
}
else
i++;
}
return count;
}
}
```
| 1 | 0 |
['Java']
| 1 |
remove-adjacent-almost-equal-characters
|
Solution in Rust without DP
|
solution-in-rust-without-dp-by-jeetkaren-6b7y
|
IntuitionThe main idea is to identify and change characters in the string such that no two adjacent characters are almost-equal. Almost-equal characters are eit
|
jeetkarena3
|
NORMAL
|
2025-01-04T09:13:18.988040+00:00
|
2025-01-04T09:13:18.988040+00:00
| 17 | false |
# Intuition
The main idea is to identify and change characters in the string such that no two adjacent characters are almost-equal. Almost-equal characters are either the same or adjacent in the alphabet.
# Approach
1. **Track Adjacent and Same Characters**:
- Iterate through the string and keep track of the characters and their positions.
- Check for adjacent almost-equal characters and record their positions.
2. **Modify Characters**:
- To remove adjacent almost-equal characters, we count the minimum number of operations needed to change one of the characters to a different letter that does not create new adjacent almost-equal pairs.
# Complexity
- **Time complexity**: $$O(n)$$, where 'n' is the length of the string. This is because we iterate through the string a constant number of times.
- **Space complexity**: $$O(1)$$, as we are using a constant amount of extra space.
# Code
```rust []
impl Solution {
pub fn remove_almost_equal_characters(word: String) -> i32 {
let word = word.as_bytes();
let mut operations = 0;
let mut i = 0;
while i < word.len() - 1 {
if word[i] == word[i + 1] || (word[i] as i32 - word[i + 1] as i32).abs() == 1 {
operations += 1;
i += 2;
} else {
i += 1;
}
}
operations
}
}
```
| 1 | 0 |
['String', 'Rust']
| 0 |
remove-adjacent-almost-equal-characters
|
C++|| DP|| RECURSION + MEMOIZATION
|
c-dp-recursion-memoization-by-user0353u-lrli
|
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
|
user0353U
|
NORMAL
|
2024-05-31T07:43:20.105098+00:00
|
2024-05-31T07:43:20.105130+00:00
| 25 | false |
# 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 {\npublic:\n\n int f(int ind, int prev, string s, int n, vector<vector<int>> &dp)\n {\n if(ind >= n)\n {\n return 0;\n }\n if(dp[ind][prev] != -1)\n {\n return dp[ind][prev];\n }\n if(abs(s[ind] - s[prev]) <= 1)\n {\n return dp[ind][prev] = 1 + f(ind + 2, ind + 1, s, n, dp);\n }\n else\n {\n return dp[ind][prev] = f(ind + 1, ind, s, n, dp);\n }\n }\n int removeAlmostEqualCharacters(string word) {\n int n = word.size();\n vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1));\n return f(1, 0, word, n, dp);\n }\n};\n```
| 1 | 0 |
['Dynamic Programming', 'Greedy', 'Recursion', 'Memoization', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Beats 100% of users with C++ || Simple and easy solution || Full explanation || O(n) time complexity
|
beats-100-of-users-with-c-simple-and-eas-nirj
|
Easy solution with C++ || Beats 100%\n# Intuition\n Describe your first thoughts on how to solve this problem. \nCheck for the difference between adjacent eleme
|
j_aryannn
|
NORMAL
|
2024-03-11T20:32:50.992655+00:00
|
2024-03-11T20:32:50.992677+00:00
| 2 | false |
# Easy solution with C++ || Beats 100%\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck for the difference between adjacent elements. The count of difference is the answer to the problem.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the absolute difference between every two adjacent elements. If the difference is less than or equal to 1, this means that the elements are almost-equal-adjacent so increment the count/ans.\nFinally return the answer.\n\n# Complexity\n- Time complexity:\n **O(n)**\n- Space complexity:\n **O(1)**\n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int ans = 0;\n for(int i =1; i< word.size(); i++){\n if(abs(word[i] - word[i-1]) <= 1){\n ans++;\n i++;\n }\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['String', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
BEATS 100% EASY JAVA SOLN
|
beats-100-easy-java-soln-by-bhagampriyal-ult4
|
Intuition\nThe code aims to count pairs of characters that are equal, have a difference of 1, or a difference of -1 in their ASCII values, as they can be remove
|
Bhagampriyal
|
NORMAL
|
2023-12-24T13:37:07.072147+00:00
|
2023-12-24T13:37:07.072173+00:00
| 41 | false |
# Intuition\nThe code aims to count pairs of characters that are equal, have a difference of 1, or a difference of -1 in their ASCII values, as they can be removed to make the word nearly equal.\n\n# Approach\nBy iterating through the word and comparing adjacent characters based on their ASCII values, the code counts pairs that can be removed to make the word nearly identical.\n\n# Complexity\nThe time complexity is O(n), where \'n\' is the length of the input word. The algorithm iterates through the word once to compare adjacent characters.\n\nThe space complexity is O(1) since the algorithm uses a constant amount of extra space regardless of the input size, maintaining only a few variables for counting and iteration.\n# Code\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int ct=0;\n for(int i=0;i<word.length()-1;i++)\n {\n if(word.charAt(i)+1==word.charAt(i+1)||word.charAt(i)==word.charAt(i+1)||word.charAt(i)-1==word.charAt(i+1))\n {\n ct++;\n i++;\n }\n }\n return ct;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Shortest, Easiest & Well Explained || To the Point & Beginners Friendly Approach (❤️ ω ❤️)
|
shortest-easiest-well-explained-to-the-p-ubwt
|
Welcome to My Coding Family\u30FE(\u2267 \u25BD \u2266)\u309D\nThis is my shortest, easiest & to the point approach. This solution mainly aims for purely beginn
|
Nitansh_Koshta
|
NORMAL
|
2023-12-17T13:29:14.088811+00:00
|
2023-12-17T13:29:14.088837+00:00
| 4 | false |
# Welcome to My Coding Family\u30FE(\u2267 \u25BD \u2266)\u309D\n*This is my shortest, easiest & to the point approach. This solution mainly aims for purely beginners so if you\'re new here then too you\'ll be very easily be able to understand my this code. If you like my code then make sure to UpVOTE me. Let\'s start^_~*\n\n# Approach:-\n\n1. Firstly, create integer \'x\' to store answer.\n2. Now by using for loop, iterate from the 0th till the last index of given string \'s\' and check that the difference of ith index character\'s ASCII Value & (i+1)th index character\'s ASCII Value inside string \'s\' is smaller than or equal to 1.\n3. If yes then increment your answer \'x\' by 1 & also as we\'re checking two characters at the same time so we\'ve to also increment the following index \'i\' by 1.\n4. Lastly we return our answer \'x\'.\n\n**The code is given below for further understanding(p\u2267w\u2266q)**\n\n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string s) {\n int x=0;\n for(int i=0;i<s.length();i++){\n if(abs((int)s[i]-(int)s[i+1])<=1){x++;i++;}\n }\n return x;\n\n// if my code helped you then please UpVOTE me, an UpVOTE encourages me to bring some more exciting codes for my coding family. Thank You o((>\u03C9< ))o\n }\n};\n```\n\n\n
| 1 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
1 pass clean solution.
|
1-pass-clean-solution-by-uday510-qf6y
|
Intuition\nIf two letters are really close in the alphabet (like \'a\' and \'b\' or \'x\' and \'y\'),increment count. Then it moves to the next pair of letters
|
uday510
|
NORMAL
|
2023-12-16T09:50:05.716570+00:00
|
2023-12-16T09:58:43.644729+00:00
| 28 | false |
# Intuition\nIf two letters are really close in the alphabet (like \'a\' and \'b\' or \'x\' and \'y\'),increment count. Then it moves to the next pair of letters and does the same thing until it finishes checking all pairs.\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- O(N), N is the input length\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int cnt = 0;\n\n for (int i = 1; i < word.length();) {\n char prev = word.charAt(i-1);\n char curr = word.charAt(i);\n if (Math.abs(curr - prev) <= 1) {\n cnt++;\n ++i;\n }\n ++i;\n }\n return cnt;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
BEATS 100 % || HEAVILY COMMENTED
|
beats-100-heavily-commented-by-abhishekk-916p
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to determine the minimum number of operations required to remove adjacent a
|
Abhishekkant135
|
NORMAL
|
2023-12-14T16:56:12.589247+00:00
|
2023-12-14T16:56:12.589282+00:00
| 109 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to determine the minimum number of operations required to remove adjacent almost-equal characters. By iterating through the string and checking for equality or adjacency in the alphabet, we can identify and handle pairs of almost-equal characters. Incrementing the counter for each such pair ensures that we account for the necessary operations. The use of a StringBuilder allows us to make modifications in-place, contributing to the efficiency of the solution.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate through the characters of the input string using a loop.\n2. Check if the current character is the same as the previous one or adjacent in the alphabet.\n3. If the condition is met, increment the counter and skip the next character to avoid double counting.\n4. Continue this process until the end of the string is reached.\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```\n/**\n * The function removes almost-equal characters from the given string.\n * Two characters are almost-equal if they are the same or adjacent in the alphabet.\n * @param word The input string\n * @return The minimum number of operations needed to remove almost-equal characters\n */\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n // Initialize a counter for the number of operations\n int count = 0;\n \n // Create a StringBuilder from the input string\n StringBuilder sb = new StringBuilder(word);\n \n // Iterate through the characters in the string\n for (int i = 1; i < word.length(); i++) {\n // Check if the current character is the same as the previous one or adjacent in the alphabet\n if (sb.charAt(i) == sb.charAt(i - 1) || Math.abs(sb.charAt(i) - sb.charAt(i - 1)) == 1) {\n // If true, increment the counter and skip the next character to avoid double counting\n count++;\n i++;\n }\n }\n \n // Return the minimum number of operations needed\n return count;\n }\n}\n\n```
| 1 | 0 |
['Dynamic Programming', 'Greedy', 'Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple java solution
|
simple-java-solution-by-user0557m-p00x
|
\n\n# Code\n\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int sol = 0;\n for(int i = 0 ; i < word.length()-1 ; i
|
user0557m
|
NORMAL
|
2023-12-11T04:44:20.049401+00:00
|
2023-12-11T04:44:20.049424+00:00
| 12 | false |
\n\n# Code\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int sol = 0;\n for(int i = 0 ; i < word.length()-1 ; i++){\n if(word.charAt(i) == word.charAt(i+1)|| word.charAt(i)-1 == word.charAt(i+1)\n ||word.charAt(i) == word.charAt(i+1)-1){\n sol++;\n i++;\n }\n }\n return sol;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
BEATS 100% IN PYTHON IN BOTH SPACE AND TIME
|
beats-100-in-python-in-both-space-and-ti-z6kd
|
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
|
subhash_2004
|
NORMAL
|
2023-12-10T10:49:29.394509+00:00
|
2023-12-10T10:49:29.394529+00:00
| 228 | false |
# 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:\nbeats 100% in python\n46ms\n\n- Space complexity:\nbeats 100% in python\n16.3 mb\n# Code\n```\nclass Solution:\n def func(self,a,b):\n if(a==b):\n return True\n elif(abs(ord(a)-ord(b))==1):\n return True\n return False\n def removeAlmostEqualCharacters(self, word: str) -> int:\n i=0\n n=len(word)-1\n word=list(word)\n ans=0\n while(i<=n-1):\n if(self.func(word[i],word[i+1])):\n word[i+1]="~"\n ans+=1\n i+=1\n print(word)\n return ans\n```
| 1 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
JAVA SOLUTION || 100% FASTER || 100% MEMORY EFFICIENT || 1MS SOLUTION
|
java-solution-100-faster-100-memory-effi-hp1u
|
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
|
viper_01
|
NORMAL
|
2023-12-10T07:01:48.232203+00:00
|
2023-12-10T07:01:48.232241+00:00
| 12 | false |
# 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 public int removeAlmostEqualCharacters(String word) {\n \n int ans = 0;\n int c = 1;\n \n for(int i = 0; i < word.length() - 1; i++) {\n if(Math.abs(word.charAt(i) - word.charAt(i + 1)) <= 1) c++;\n else {\n ans += c / 2;\n c = 1;\n }\n }\n \n ans += c / 2;\n \n return ans;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy Java Solution || Beats 100%
|
easy-java-solution-beats-100-by-ravikuma-o90t
|
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
|
ravikumar50
|
NORMAL
|
2023-12-10T04:33:13.184877+00:00
|
2023-12-10T04:33:13.184895+00:00
| 7 | false |
# 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 public int removeAlmostEqualCharacters(String s) {\n\n int ans = 0;\n for(int i=1; i<s.length(); i++){\n if(Math.abs(s.charAt(i)-s.charAt(i-1))<=1){\n ans++;\n i++;\n }\n }\n return ans;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Java simple O(n) solution beats 100%
|
java-simple-on-solution-beats-100-by-tec-w2ba
|
Simple idea is that if we see characters like almosteq1 almosteq2 almosteq3 pattern then we will pick almosteq2 to change, and resume from almosteq3. \n If we s
|
techguy
|
NORMAL
|
2023-12-09T22:37:25.149063+00:00
|
2023-12-09T22:37:47.221832+00:00
| 2 | false |
Simple idea is that if we see characters like `almosteq1 almosteq2 almosteq3` pattern then we will pick `almosteq2` to change, and resume from `almosteq3`. \n If we see characters like `almosteq1 almosteq2 notequalchar` pattern then we again need to change one character, but we can only jump one index i.e. change to`almosteq2`.\n\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int tot = 0;\n for (int i = 0; i+1 < word.length(); i++) {\n if (isAlmostEqual(word.charAt(i), word.charAt(i+1))) {\n if (i+2 < word.length() && isAlmostEqual(word.charAt(i+1), word.charAt(i+2))) {\n i++;\n }\n tot++;\n }\n }\n return tot;\n }\n \n boolean isAlmostEqual(char c1, char c2) {\n return (c1 == c2) || (c1-c2 == 1) || (c2-c1 == 1);\n }\n}\n```
| 1 | 0 |
[]
| 0 |
remove-adjacent-almost-equal-characters
|
Swift solution
|
swift-solution-by-azm819-q6zk
|
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# Co
|
azm819
|
NORMAL
|
2023-12-09T21:16:37.021994+00:00
|
2023-12-09T21:16:37.022022+00:00
| 5 | false |
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n func removeAlmostEqualCharacters(_ word: String) -> Int {\n var ind = word.startIndex\n var result = 0\n var prev: Character?\n while ind < word.endIndex {\n if let prevCh = prev, abs(Int(prevCh.asciiValue!) - Int(word[ind].asciiValue!)) <= 1 {\n result += 1\n prev = nil\n } else {\n prev = word[ind]\n }\n ind = word.index(after: ind)\n }\n return result\n }\n}\n\n```
| 1 | 0 |
['String', 'Swift', 'String Matching']
| 0 |
remove-adjacent-almost-equal-characters
|
O(N) Time Complexity DP Solution
|
on-time-complexity-dp-solution-by-racemi-8rt4
|
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
|
raceMight
|
NORMAL
|
2023-12-09T19:49:32.922467+00:00
|
2023-12-09T19:49:32.922493+00:00
| 50 | false |
# 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 public int removeAlmostEqualCharacters(String word) {\n int dp[] = new int[word.length()+1];\n\n Arrays.fill(dp,-1);\n return helper(1,word,dp);\n \n }\n \n int helper(int i , String word, int[] dp){\n if(i >= word.length()){\n return 0;\n }\n if(dp[i] != -1) return dp[i];\n \n if(Math.abs(word.charAt(i) - word.charAt(i-1)) < 2){\n dp[i] = 1 + helper(i+2,word,dp);\n }else{\n dp[i] = helper(i+1,word,dp);\n }\n\n return dp[i];\n }\n}\n```
| 1 | 0 |
['Dynamic Programming', 'Recursion', 'Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy C++ Intuitive Solution
|
easy-c-intuitive-solution-by-baquer-ojrd
|
Code\n\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n \n int ans = 0;\n for(int i = 1; i < word.size(); )
|
baquer
|
NORMAL
|
2023-12-09T19:19:26.285039+00:00
|
2023-12-09T19:19:26.285061+00:00
| 130 | false |
# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n \n int ans = 0;\n for(int i = 1; i < word.size(); ) {\n if(abs(word[i] - word[i-1]) <= 1) {\n ans++;\n i += 2;\n } else {\n i++;\n }\n } \n \n return ans;\n \n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
O(n) Solution 😀
|
on-solution-by-subashc_07-shjw
|
\n\n# Code\n\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n ans=0\n ind=1\n def com(a,b):\n if
|
subashc_07
|
NORMAL
|
2023-12-09T19:10:43.775372+00:00
|
2023-12-09T19:10:43.775405+00:00
| 77 | false |
\n\n# Code\n```\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n ans=0\n ind=1\n def com(a,b):\n if a==b or abs(ord(a)-ord(b))==1:return True\n return False\n while ind<len(word):\n if com(word[ind],word[ind-1]):\n ind+=2\n ans+=1\n else:ind+=1\n return ans\n```
| 1 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple Greedy Approach in O(n) time complexity
|
simple-greedy-approach-in-on-time-comple-zuj2
|
Objective: Count the occurrences of nearly equal consecutive characters in a given string.\n- Approach:\n - Iterate through the string, comparing adjacent char
|
aanya_969
|
NORMAL
|
2023-12-09T17:15:47.085780+00:00
|
2023-12-09T17:15:47.085802+00:00
| 49 | false |
- **Objective**: Count the occurrences of nearly equal consecutive characters in a given string.\n- **Approach**:\n - Iterate through the string, comparing adjacent characters.\n - Increment the count when the absolute difference between characters is 0 or 1.\n - Skip the next character to avoid double-counting.\n- **Implementation**:\n - Use `abs(word[i+1] - word[i]) <= 1` as the condition for near equality.\n - Return the final count as the result.\n\n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int n=word.length();\n int result=0;\n for(int i=0; i<n; i++){\n if(abs(word[i+1]-word[i]) <= 1){\n result++;\n i++;\n }\n }\n return result;\n }\n};\n```
| 1 | 0 |
['Greedy', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
100% faster || Stack || simple C++ code
|
100-faster-stack-simple-c-code-by-alokpa-2zmr
|
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
|
Alokpatel88
|
NORMAL
|
2023-12-09T16:53:23.035935+00:00
|
2023-12-09T16:53:23.035962+00:00
| 33 | false |
# 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 {\npublic:\n int removeAlmostEqualCharacters(string str) {\n stack<pair<char, int>> st;\n int cnt = 0;\n st.push({str[0], 0});\n for(int i = 1; i< str.size(); i++){\n if( (str[i] == st.top().first && st.top().second == 0 ) \n || (str[i] == st.top().first + 1 && st.top().second == 0 )\n || (str[i] +1 == st.top().first && st.top().second == 0) ){\n cnt ++;\n st.push(make_pair(str[i], 1));\n }\n else{\n st.push(make_pair(str[i], 0));\n }\n }\n return cnt;\n }\n};\n```
| 1 | 0 |
['Stack', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Super fast simple solution | Greedy
|
super-fast-simple-solution-greedy-by-mk2-k915
|
Intuition\njust updated with next possible valid char and counted such index which does not satisfy the condtiton \n# Code\n\nclass Solution {\npublic:\n int
|
TIME2LIVE
|
NORMAL
|
2023-12-09T16:52:22.914448+00:00
|
2023-12-10T03:46:42.215044+00:00
| 10 | false |
# Intuition\njust updated with next possible valid char and counted such index which does not satisfy the condtiton \n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int cnt = 0 ;\n for(int i = 1 ; i< word.size(); i++){\n if(abs(word[i]-word[i-1]) <=1){\n cnt++;\n word[i]=(word[i]-\'a\'+2);\n }\n }\n return cnt ; \n }\n};\n\n \n\n\n```
| 1 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Greedy--onePass--C++|| 100% faster🔥|| easy to understand
|
greedy-onepass-c-100-faster-easy-to-unde-vdn6
|
Intuition\n Describe your first thoughts on how to solve this problem. \njust check the given condition is valid or not. if not increase count.\n\n# Approach\n
|
monchi02
|
NORMAL
|
2023-12-09T16:12:04.465452+00:00
|
2023-12-09T16:12:04.465477+00:00
| 5 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\njust check the given condition is valid or not. if not increase count.\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 O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int cnt = 0;\n \n for (int i = 1; i < word.length(); ++i) {\n if (word[i] == word[i - 1] || abs(word[i] - word[i - 1]) == 1) {\n cnt++;\n i++;\n }\n }\n\n return cnt;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
🔥✅2 Approaches || DP(Memoization) + 🌟Greedy || 💯Clean Code
|
2-approaches-dpmemoization-greedy-clean-w7pnr
|
\n# Complexity\n\n- Time complexity:\nO(n)\n\n- Space complexity:\n- O(1) for Approach 1\n- O(n) for Approach 2\n\n\n# Code\n## Please Upvote if it helps\uD83E\
|
aDish_21
|
NORMAL
|
2023-12-09T16:06:04.257112+00:00
|
2023-12-09T20:50:20.985801+00:00
| 155 | false |
\n# Complexity\n```\n- Time complexity:\nO(n)\n\n- Space complexity:\n- O(1) for Approach 1\n- O(n) for Approach 2\n```\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n# 1st Approach(GREEDY):-\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int n = word.size(), ans = 0, cnt = 0;\n for(int i = 0 ; i < n - 1 ; i++){\n cnt++;\n int diff = abs(word[i] - word[i + 1]);\n if(diff > 1){\n ans += cnt / 2;\n cnt = 0;\n }\n }\n cnt++;\n ans += cnt / 2;\n return ans;\n }\n};\n```\n# 2nd Approach(DP):-\n```\nclass Solution {\npublic:\n int dp[101];\n int helper(int ind, int n, string& word){\n if(ind >= n)\n return 0;\n if(dp[ind] != -1)\n return dp[ind];\n int mini = n;\n int diff1 = abs(word[ind] - word[ind - 1]), diff2 = -1;\n if(ind + 1 < n)\n diff2 = abs(word[ind] - word[ind + 1]);\n if(diff1 == 0 || diff1 == 1)\n mini = min(mini , 1 + helper(ind + 2, n, word));\n else{\n if(diff2 == 0 || diff2 == 1){\n mini = min(mini , 1 + helper(ind + 2, n, word));\n mini = min(mini , helper(ind + 1, n, word));\n }\n else\n mini = min(mini, helper(ind + 2, n, word));\n }\n return dp[ind] = mini;\n }\n \n int removeAlmostEqualCharacters(string word) {\n int n = word.size();\n memset(dp, -1, sizeof(dp));\n return helper(1, n , word);\n }\n};\n```
| 1 | 0 |
['Dynamic Programming', 'Memoization', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
[C++] Top Down DP
|
c-top-down-dp-by-timchen10001-xels
|
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
|
timchen10001
|
NORMAL
|
2023-12-09T16:02:35.320894+00:00
|
2023-12-09T16:18:32.150957+00:00
| 174 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int n = word.size();\n \n vector<int> memo(n, -1);\n \n function<int(int)> dp = [&](int i) {\n if (i >= n) return 0;\n \n if (memo[i] != -1)\n return memo[i];\n \n if (abs((word[i]-\'a\') - (word[i+1]-\'a\')) <= 1) {\n return memo[i] = 1 + min(dp(i+1), dp(i+2));\n }\n \n return memo[i] = dp(i+1);\n };\n \n return dp(0);\n }\n};\n```
| 1 | 0 |
['Dynamic Programming', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy solution 100% faster
|
easy-solution-100-faster-by-shihab_hossa-05af
|
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
|
Shihab_Hossain_038
|
NORMAL
|
2023-12-09T16:02:02.767107+00:00
|
2023-12-09T16:02:02.767134+00:00
| 10 | false |
# 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 {\npublic:\n int removeAlmostEqualCharacters(string s) {\n int c=0;\n for(int i=0; i<s.size(); i++)\n {\n int a=s[i]-\'a\';\n int j=i+1;\n int d=0;\n while(abs((s[j]-\'a\')-a)<=1)\n {\n d++;\n a=s[j]-\'a\';\n j++;\n \n }\n c+=d/2;\n if(d%2)\n c++;\n i=j-1;\n \n }\n return c;\n \n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
O(n) | 0ms | beating 100%
|
on-0ms-beating-100-by-lilongxue-f3j9
|
IntuitionApproachComplexity
Time complexity:
O(n)
Space complexity:
O(1)
Code
|
lilongxue
|
NORMAL
|
2025-03-27T16:17:50.266567+00:00
|
2025-03-27T16:17:50.266567+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(1)
# Code
```javascript []
/**
* @param {string} word
* @return {number}
*/
var removeAlmostEqualCharacters = function(word) {
const len = word.length
let result = 0
for (let i = 1; i < len; ) {
const code = word.charCodeAt(i), prev = word.charCodeAt(i - 1)
const diff = Math.abs(code - prev)
if (diff <= 1) {
result++
i += 2
} else {
i++
}
}
return result
};
```
| 0 | 0 |
['JavaScript']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy greedy approach
|
easy-greedy-approach-by-_jyoti_geek-oauw
|
Code
|
_jyoti_geek
|
NORMAL
|
2025-03-08T14:27:20.879207+00:00
|
2025-03-08T14:27:20.879207+00:00
| 4 | false |
# Code
```java []
class Solution {
public int removeAlmostEqualCharacters(String s) {
int n = s.length();
int ans = 0;
char prev = s.charAt(0);
for (int i = 1; i < n; i++) {
char ch = s.charAt(i);
if (ch == prev || ch + 1 == prev || prev + 1 == ch) {
ans++;
prev = '@';
} else {
prev = ch;
}
}
return ans;
}
}
```
| 0 | 0 |
['String', 'Greedy', 'Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Python3 O(N) Solution with two pointers (100.00% Runtime)
|
python3-on-solution-with-two-pointers-10-977u
|
IntuitionApproach
Iteratively compare ith and i-1th elements:
If ith and i-1th elements are differnent by ord() of 2, continue (i += 1).
If not, then it is a si
|
missingdlls
|
NORMAL
|
2025-02-23T14:14:06.335103+00:00
|
2025-02-23T14:15:02.320865+00:00
| 5 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->
- Iteratively compare ith and i-1th elements:
- If ith and i-1th elements are differnent by ord() of 2, continue (i += 1).
- If not, then it is a situation like "...acdx...":
- Current is "d".
- In this case, we change "d" to something else that both "c" and "x" not overlap.
- Then we move by i += 2 since we already dealt with for "x" too.
- Increment the operation count.
- Return the final operation count.
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
If this solution is similar to yours or helpful, upvote me if you don't mind
```python3 []
class Solution:
def removeAlmostEqualCharacters(self, word: str) -> int:
i = 1
l = len(word)
c = 0
while i < l:
o1 = abs(ord(word[i])-ord(word[i-1]))
if o1 < 2:
c += 1
i += 1
i += 1
return c
```
| 0 | 0 |
['Array', 'Math', 'Two Pointers', 'String', 'Greedy', 'String Matching', 'Counting', 'Enumeration', 'Python', 'Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
Compare adjacent chars
|
compare-adjacent-chars-by-linda2024-zt3w
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
linda2024
|
NORMAL
|
2025-02-12T23:31:15.709238+00:00
|
2025-02-12T23:31:15.709238+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public int RemoveAlmostEqualCharacters(string word) {
int idx = 1, len = word.Length, res = 0;
if(len <= 1)
return 0;
while(idx < len)
{
if(Math.Abs(word[idx] - word[idx-1]) <= 1)
{
res++;
idx++;
}
idx++;
}
return res;
}
}
```
| 0 | 0 |
['C#']
| 0 |
remove-adjacent-almost-equal-characters
|
Beats 100%. Easy to understand for beginners.
|
beats-100-easy-to-understand-for-beginne-qm6r
|
IntuitionKeep track if last character is almost equal to current char.ApproachComplexity
Time complexity:
O(n)
Space complexity:
Code
|
Mishra_Asmit
|
NORMAL
|
2025-01-27T08:58:14.655155+00:00
|
2025-01-27T08:58:14.655155+00:00
| 2 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

Keep track if last character is almost equal to current char.
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
static int solutionII(String s) {
StringBuilder sb = new StringBuilder();
int ans = 0;
// Intialize a StringBuilder sb and int ans.
sb.append(s.charAt(0));
// Add first character of word to sb.
for (int i = 1; i < s.length(); i++) {
// Check if current char is almost equal to last char.
if (Math.abs(s.charAt(i) - sb.charAt(i - 1)) > 1) {
sb.append(s.charAt(i));
// Add current char to sb if not equal.
} else {
sb.append('0');
ans++;
// Add any non-alphabetic char to sb if not equal.
// Increase ans by one.
}
}
return ans;
}
public int removeAlmostEqualCharacters(String word) {
return solutionII(word);
}
}
```
| 0 | 0 |
['String', 'Counting', 'Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy to Understand For Beginners using Stack.
|
easy-to-understand-for-beginners-using-s-lb0c
|
IntuitionMaintain a stack and check if last character is "Almost Equal"ApproachComplexity
Time complexity:
O(n)
Space complexity:
Code
|
Mishra_Asmit
|
NORMAL
|
2025-01-27T08:45:53.120656+00:00
|
2025-01-27T08:45:53.120656+00:00
| 3 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Maintain a stack and check if last character is "Almost Equal"
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int removeAlmostEqualCharacters(String s) {
int ans = 0;
Stack<Character> stack = new Stack<>();
// Intialize a character stack and int ans to store ans.
for (char c : s.toCharArray()) {
// If stack is empty add c to stack.
if (stack.empty()) {
stack.push(c);
} else {
// Check if c is Almost Equal to top char in stack.
if (Math.abs(c - stack.peek()) > 1) {
// If not almost equal add to stack.
stack.push(c);
} else {
// If it is almost equal add a non-aplhabetic character eg: '0'.
// Increase ans by one.
stack.push('0');
ans++;
}
}
}
return ans;
}
}
```
| 0 | 0 |
['String', 'Stack', 'Counting', 'Java']
| 0 |
remove-adjacent-almost-equal-characters
|
C++ O(n)/O(1) concise code
|
c-ono1-concise-code-by-tiejun-xlt7
|
IntuitionTwo pointers variantWe try to find substring starting from index i, as long as possible to make sure the substring consist of almost-equal characters o
|
tiejun
|
NORMAL
|
2025-01-08T11:48:23.668977+00:00
|
2025-01-08T11:48:23.668977+00:00
| 3 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Two pointers variant
We try to find substring starting from index `i`, as long as possible to make sure the substring consist of almost-equal characters only.
Then, if the length of the substring is `len`, its contribution to the final answer will be `ceil((len-1)/2.0)`
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
int removeAlmostEqualCharacters(string word) {
int ans = 0, N = word.size();
for (int i=0, j=0; i<N; ) {
for (j=i+1; j<N; j++) {
if (word[j-1] != word[j] && abs(word[j] - word[j-1]) != 1)
break;
}
ans += ceil((j - i - 1) / 2.0);
i = j;
}
return ans;
}
```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Python3 -- Easy Solution -- Beats 100%
|
python3-easy-solution-beats-100-by-kativ-341n
|
IntuitionUsing a Sliding Window of size two and saving a set of the position we updated as the res (so if we need to update it twice it doesn't count more than
|
kativen
|
NORMAL
|
2025-01-06T22:21:22.650316+00:00
|
2025-01-06T22:21:22.650316+00:00
| 5 | false |
# Intuition
Using a **Sliding Window** of size two and saving a set of the position we updated as the res (so if we need to update it twice it doesn't count more than once in the result)
# Code
```python3 []
class Solution:
def removeAlmostEqualCharacters(self, word: str) -> int:
res = set()
word_list = [ord(w) for w in word.lower()] # so we can use ascii easily
for index in range(len(word)-1):
if abs(word_list[index]- word_list[index+1])<=1:
target = index +1
if index in res:
target -= 1
word_list[target] += 2
res.add(target)
return len(res)
```
| 0 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
Java || Kotlin
|
java-kotlin-by-ritabrata_1080-t9r7
|
CodeCode
|
Ritabrata_1080
|
NORMAL
|
2024-12-30T19:09:43.396160+00:00
|
2024-12-30T19:09:43.396160+00:00
| 3 | false |
# Code
```java []
class Solution {
public int removeAlmostEqualCharacters(String s) {
int res = 0;
for(int i = 1; i < s.length(); ++i){
if(Math.abs(s.charAt(i) - s.charAt(i-1)) <= 1) {
res++;
i++;
}
}
return res;
}
}
```
# Code
``` kotlin []
class Solution {
fun removeAlmostEqualCharacters(word: String): Int {
var res = 0
var i = 1
while (i < word.length) {
if (kotlin.math.abs(word[i] - word[i - 1]) <= 1) {
res++
i++
}
i++
}
return res
}
}
```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Java | beats 100%
|
java-beats-100-by-deadvikash-nfwh
|
Code
|
deadvikash
|
NORMAL
|
2024-12-18T04:42:47.491127+00:00
|
2024-12-18T04:42:47.491127+00:00
| 5 | false |
\n\n# Code\n```java []\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int len = word.length();\n char[] ch = word.toCharArray();\n int[] dp = new int[len];\n\n int count = 0;\n\n for(int i = 1; i < len; i+=2) {\n int prev = i - 1;\n int next = i + 1;\n \n char c = ch[i];\n char p = ch[prev];\n\n\n if(dp[i] == 0 && dp[i - 1] == 0 && (c == p || Math.abs(p - c) == 1)) {\n count++;\n dp[i] = 1;\n dp[i - 1] = 1;\n continue;\n }\n\n if(next < len && dp[i] == 0 && dp[i + 1] == 0) {\n char n = ch[next];\n if(c == n || Math.abs(n - c) == 1) {\n count++;\n dp[i] = 1;\n dp[i + 1] = 1;\n }\n }\n }\n\n return count;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Sliding window java solution
|
sliding-window-java-solution-by-vonrosen-yksv
|
IntuitionUse sliding window to find length of each subarray which has adjacent
characters. Increment answer every time we find a length of a subarray
with adjac
|
vonrosen
|
NORMAL
|
2024-12-15T22:09:10.615275+00:00
|
2024-12-15T22:09:10.615275+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse sliding window to find length of each subarray which has adjacent\ncharacters. Increment answer every time we find a length of a subarray\nwith adjacent character by half the length since that is minimum\nnumber of modifications to make to ensure the word has no\nadjacent characters.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSliding window. Left pointer is at the start of \nsubarray with adjacent characters and right pointer is one character\nbeyond the end of the subarray so we can use right - left + 1 to calculate\nthe length. The last character in the word is a special case where\nwe take length / 2 instead (length - 1) / 2 since there will not\nbe another character.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```java []\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int left = 0;\n int curLength = 1;\n int ans = 0;\n for(int right = 0; right < word.length(); ++right){ \n curLength = right - left + 1;\n if(adjacent(word, Math.max(0, right - 1), right)){\n if(word.length() - 1 == right){\n ans += curLength / 2;\n } \n }else{\n ans += (curLength - 1) / 2;\n left = right;\n }\n }\n return ans;\n }\n\n boolean adjacent(String word, int left, int right){\n char leftChar = word.charAt(left);\n char rightChar = word.charAt(right);\n return leftChar == rightChar || Math.abs((int)leftChar - (int)rightChar) == 1;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
clean code
|
clean-code-by-maheshsaini88-1hcv
|
python3 []\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n count = 0\n i = 0\n while i < len(word) - 1:\n
|
maheshsaini88
|
NORMAL
|
2024-12-06T18:17:04.717201+00:00
|
2024-12-06T18:17:04.717284+00:00
| 2 | false |
```python3 []\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n count = 0\n i = 0\n while i < len(word) - 1:\n if abs(ord(word[i]) - ord(word[i+1])) <= 1:\n count += 1\n i += 2\n else:\n i += 1\n return count\n```
| 0 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
Java O(1) solution very simple
|
java-o1-solution-very-simple-by-hello8-8h0k
|
\n---\n\n Describe your first thoughts on how to solve this problem. \n\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
HELLO8
|
NORMAL
|
2024-12-06T16:34:00.289108+00:00
|
2024-12-06T16:34:00.289147+00:00
| 2 | false |
\n---\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1)\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```java []\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n \n int ans=0;\n int n=word.length();\n int i=1;\n\n while(i<n) {\n char c1=word.charAt(i);\n char c2=word.charAt(i-1);\n\n if(c1==c2 || Math.abs(c1-\'0\'+1)==Math.abs(c2-\'0\') || Math.abs(c1-\'0\')==Math.abs(c2-\'0\'+1)) {\n ans++;\n i+=2;\n }else i++;\n }\n return ans;\n }\n}\n\n\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
simple c++ solution beats 100%
|
simple-c-solution-beats-100-by-zeas-wjl7
|
Intuition\nThe idea is to use a flag and traverse along the length of the string.\n\n# Approach\n\n\n\n# Complexity\n- Time complexity: O(n)\n Add your time com
|
zeas
|
NORMAL
|
2024-11-05T13:24:11.333536+00:00
|
2024-11-05T13:24:11.333572+00:00
| 1 | false |
# Intuition\nThe idea is to use a flag and traverse along the length of the string.\n\n# Approach\n\n\n\n# Complexity\n- Time complexity: O(n)\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```cpp []\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int operations = 0;\n bool flag = false;\n \n for(int i = 1; i<word.size(); i++){\n if(!flag && (abs(word[i] - word[i-1]) <= 1)){\n flag = true;\n operations++;\n }\n else{\n flag = false;\n }\n }\n return operations;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
[Python3] Good enough
|
python3-good-enough-by-parrotypoisson-riza
|
python3 []\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n remove = 0\n\n i = 1\n while i<len(word):\n
|
parrotypoisson
|
NORMAL
|
2024-10-27T14:16:40.729036+00:00
|
2024-10-27T14:16:40.729070+00:00
| 3 | false |
```python3 []\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n remove = 0\n\n i = 1\n while i<len(word):\n if abs(ord(word[i])-ord(word[i-1]))<=1:\n remove +=1\n i += 2\n else:\n i += 1\n\n return remove\n```
| 0 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
Beats 100 % greedy
|
beats-100-greedy-by-gokul1922-fnez
|
Intuition\n Describe your first thoughts on how to solve this problem. \nGreedy, only check the alternate character, for change\n\n# Approach\n Describe your ap
|
gokul1922
|
NORMAL
|
2024-10-19T11:29:53.886872+00:00
|
2024-10-19T11:29:53.886933+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGreedy, only check the alternate character, for change\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(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```python3 []\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n\n alp = [\'a\', \'b\', \'c\', \'d\', \'e\', \'f\', \'g\', \'h\', \'i\', \'j\', \'k\', \'l\', \'m\', \'n\', \'o\', \'p\', \'q\', \'r\', \'s\', \'t\', \'u\', \'v\', \'w\', \'x\', \'y\', \'z\']\n alp_dict = {}\n alp_index_dict = {}\n\n for i, value in enumerate(alp):\n alp_dict[value] = i\n\n for i, value in enumerate(alp):\n alp_index_dict[i] = value\n \n result = 0\n\n length = len(word)\n start = 1\n while start < length:\n value = word[start]\n prev = word[start - 1]\n\n index= alp_dict[value]\n prev_index= alp_dict[prev]\n if value == prev or value == alp_index_dict.get(prev_index -1) or value == alp_index_dict.get(prev_index + 1):\n print("value--",start, value, prev)\n result += 1\n start += 2\n else:\n start += 1\n\n return result\n\n```
| 0 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
☕ Java solution ✅ || 😼 Beats 100.00% ✨
|
java-solution-beats-10000-by-barakamon-ocj8
|
\n\njava []\nclass Solution {\n public int removeAlmostEqualCharacters(String s) {\n int count = 0, i = 1;\n while (i < s.length()) {\n
|
Barakamon
|
NORMAL
|
2024-10-08T15:42:19.534814+00:00
|
2024-10-08T15:42:19.534854+00:00
| 1 | false |
\n\n```java []\nclass Solution {\n public int removeAlmostEqualCharacters(String s) {\n int count = 0, i = 1;\n while (i < s.length()) {\n if (Math.abs(s.charAt(i) - s.charAt(i - 1)) <= 1) {\n count++;\n i += 2;\n } else {\n i++;\n }\n }\n return count;\n }\n}\n\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
C# Linq Greedy 1 line
|
c-linq-greedy-1-line-by-gbamqzkdyg-z2f7
|
Approach\nGreedy\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\ncsharp []\npublic class Solution {\n public int RemoveAlmo
|
gbamqzkdyg
|
NORMAL
|
2024-10-07T15:51:41.131686+00:00
|
2024-10-07T15:51:41.131707+00:00
| 2 | false |
# Approach\nGreedy\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```csharp []\npublic class Solution {\n public int RemoveAlmostEqualCharacters(string word) => word.Aggregate((prev: \'O\', skip: false, res: 0), (a, ch) => a.skip || Math.Abs(ch - a.prev) > 1 ? (ch, false, a.res) : (ch, true, a.res + 1)).res;\n}\n```
| 0 | 0 |
['C#']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy for loop approach
|
easy-for-loop-approach-by-harbedi13-ka8u
|
\n# Code\njava []\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int count = 0;\n for (int i = 0; i < word.length(
|
harbedi13
|
NORMAL
|
2024-10-04T20:37:33.940523+00:00
|
2024-10-04T20:37:33.940557+00:00
| 2 | false |
\n# Code\n```java []\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int count = 0;\n for (int i = 0; i < word.length();) {\n char c = word.charAt(i);\n if (i < word.length() - 1) {\n char p = word.charAt(i + 1);\n if (c == p || (c + 1) == p || (c - 1) == p) {\n count++;\n i += 2;\n } else {\n i++;\n }\n } else {\n break;\n }\n }\n return count;\n }\n}\n\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
DP Solution || From (Recursion) TLE to (DP) O(N)
|
dp-solution-from-recursion-tle-to-dp-on-piryg
|
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
|
AdityaRay_1528
|
NORMAL
|
2024-09-25T20:28:46.118852+00:00
|
2024-09-25T20:28:46.118876+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\nRECURSION(TLE)\n\nclass Solution {\npublic:\n int solve(string word,int n,int index,int &ans){\n if(index>=n)return 0;\n\n int include=0;\n if(index+1 != n && (abs(word[index]-word[index+1])<=1)){\n include=1+solve(word,n,index+2,ans);\n }\n int exclude=solve(word,n,index+1,ans);\n ans=max(include,exclude);\n return ans;\n }\n int removeAlmostEqualCharacters(string word) {\n \n int ans=0;\n int n=word.size();\n solve(word,n,0,ans);\n return ans;\n }\n};\n\nRECURSION + MEMOIZATION\nclass Solution {\npublic:\n int solve(string word,int n,int index,int &ans,vector<int>&dp){\n if(index>=n)return 0;\n if(dp[index]!=-1)return dp[index];\n int include=0;\n if(index+1 != n && (abs(word[index]-word[index+1])<=1)){\n include=1+solve(word,n,index+2,ans,dp);\n }\n int exclude=solve(word,n,index+1,ans,dp);\n \n return dp[index]=max(include,exclude);\n }\n int removeAlmostEqualCharacters(string word) {\n \n int ans=0;\n int n=word.size();\n vector<int>dp(n+1,-1);\n return solve(word,n,0,ans,dp);\n }\n};\n\n\nBOTTOM-UP DP\nclass Solution {\npublic:\n \n int removeAlmostEqualCharacters(string word) {\n int n=word.size();\n vector<int>dp(n+1,0);\n \n for(int i=n-2;i>=0;i--){\n int include=0;\n if(i+1 != n && (abs(word[i]-word[i+1])<=1)){\n include=1+dp[i+2];\n }\n int exclude=dp[i+1];\n dp[i]=max(include,exclude);\n } \n \n return dp[0];\n }\n};\n\nSPACE OPTIMZATION\n\nclass Solution {\npublic:\n \n int removeAlmostEqualCharacters(string word) {\n int n=word.size();\n int next=0;\n int curr=0;\n \n for(int i=n-2;i>=0;i--){\n int include=0;\n if(i+1 != n && (abs(word[i]-word[i+1])<=1)){\n include=1+next;\n }\n int exclude=curr;\n next=curr;\n curr=max(include,exclude);\n } \n \n return curr;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy python solution
|
easy-python-solution-by-harieshsr-5qg0
|
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
|
harieshsr
|
NORMAL
|
2024-09-22T05:17:37.962615+00:00
|
2024-09-22T05:17:37.962638+00:00
| 2 | false |
# 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```python3 []\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n prev=0\n c=0\n for i in word:\n cur=ord(i)\n if cur==prev or cur==prev+1 or cur==prev-1:\n c+=1\n prev=0\n \n else:\n prev=cur\n return c\n \n```
| 0 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
Where is DP...
|
where-is-dp-by-dnanper-lgzs
|
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
|
dnanper
|
NORMAL
|
2024-09-18T14:14:12.335392+00:00
|
2024-09-18T14:14:12.335436+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n/*\n\n*/\n\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) \n {\n int n = word.size(), res = 0;\n for (int i = 0; i < n-1; i++)\n {\n if (abs(word[i] - word[i+1]) <= 1)\n {\n res ++;\n i = i+1;\n }\n }\n return res;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Beats 100%
|
beats-100-by-vatan999-xbdi
|
Intuition\nTo remove adjacent almost-equal characters from the string, you need to perform the minimum number of operations. An operation involves replacing a c
|
vatan999
|
NORMAL
|
2024-09-09T20:09:53.901843+00:00
|
2024-09-09T20:09:53.901873+00:00
| 0 | false |
### Intuition\nTo remove adjacent almost-equal characters from the string, you need to perform the minimum number of operations. An operation involves replacing a character to eliminate adjacent pairs of almost-equal characters. Characters are almost-equal if they are either the same or adjacent in the alphabet.\n\n### Approach\n1. **Use a Stack:** \n - Traverse the string character by character.\n - Use a stack to keep track of characters that haven\'t been removed.\n - For each character in the string:\n - If the stack is empty, push the character onto the stack.\n - If the stack is not empty, check the top of the stack:\n - If the top character is almost-equal to the current character (i.e., either the same or adjacent in the alphabet), it means a removal is needed.\n - Push a placeholder value (\'1\') to indicate that a removal has occurred, increment the count of operations, and push the current character onto the stack.\n - If not almost-equal, push the current character onto the stack.\n \n2. **Count the Operations:** \n - Every time a pair of almost-equal characters is removed, increment the operation count.\n\n### Complexity\n- **Time complexity:** \n The solution involves a single traversal of the string and stack operations, which are O(1) on average. Therefore, the time complexity is **O(n)**, where `n` is the length of the string.\n\n- **Space complexity:** \n The space complexity is **O(n)**, as in the worst case, all characters are pushed onto the stack.\n\n### Code\n```cpp\n#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n stack<char> st;\n int ans = 0;\n for (auto i : word) {\n if (st.empty()) {\n st.push(i);\n } \n else {\n if (st.top() == i || st.top() == i - 1 || st.top() == i + 1) {\n st.push(\'1\');\n ans++;\n } \n else {\n st.push(i);\n }\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
just use greedy to solve this problem
|
just-use-greedy-to-solve-this-problem-by-qkss
|
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
|
jpppyadav1234
|
NORMAL
|
2024-09-08T13:03:34.265679+00:00
|
2024-09-08T13:03:34.265723+00:00
| 0 | false |
# 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```cpp []\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string s) {\n int count=0;\n for(int i=1;i<s.size();i++)\n {\n int t=abs(int(s[i]-\'a\')-int(s[i-1]-\'a\'));\n if(s[i]==s[i-1]||(t==1))\n {\n count++;\n i++;\n }\n }\n return count;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple Greedy Solution
|
simple-greedy-solution-by-sumit_minz24-c0ki
|
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
|
sumit_minz24
|
NORMAL
|
2024-09-07T13:06:16.705452+00:00
|
2024-09-07T13:06:16.705490+00:00
| 0 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int n = word.size();\n int count = 0;\n for(int i = 1; i < n; i++){\n if(word[i-1] == word[i] || word[i-1] + 1 == word[i] || word[i-1] == word[i] + 1){\n i++;\n count++;\n }\n }\n return count;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Beats 100.0%...
|
beats-1000-by-selvakarthiga-hw7u
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nExplanation\nComparison
|
Selvakarthiga
|
NORMAL
|
2024-09-07T10:38:28.243233+00:00
|
2024-09-07T10:38:28.243255+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nExplanation\nComparison: c[i] == c[i - 1] checks if the characters are the same.\nAlmost-Equal Check: Math.abs(c[i] - c[i - 1]) == 1 checks if the characters are adjacent in the alphabet.\nSkip Next Character: i++ ensures that the next character is skipped after an operation.\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\n 0(1)\n# Code\n```java []\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n\n\n char[] c = word.toCharArray();\n int n = c.length;\n int operations=0;\n for(int i=1;i<n;i++){\n if((c[i] == c[i-1]) || Math.abs(c[i] - c[i-1])==1){\n operations++;\n i++;\n }\n } \n return operations;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Beats 100% - Easy Self Explanatory Solution
|
beats-100-easy-self-explanatory-solution-moz5
|
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
|
sachinab
|
NORMAL
|
2024-09-06T14:59:48.387707+00:00
|
2024-09-06T14:59:48.387748+00:00
| 0 | false |
# 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```java []\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n \n int res = 0;\n boolean pc = false;\n for(int i=1; i<word.length(); i++){\n if(!pc && Math.abs(word.charAt(i)-word.charAt(i-1))<=1){\n res++;\n pc = true;\n }else{\n pc = false;\n }\n }\n return res;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
O(n)
|
on-by-robin1302-g150
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nConvert characters with
|
robin1302
|
NORMAL
|
2024-08-26T08:47:05.644276+00:00
|
2024-08-26T08:47:05.644304+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nConvert characters with both side equals, then only the ones with one side equal\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```csharp []\npublic class Solution {\n public int RemoveAlmostEqualCharacters(string word) {\n char[] ar = word.ToCharArray();\n int op = 0;\n for(int i=1; i<ar.Length-1; i++)\n {\n if (IsEqual(ar[i-1], ar[i]) && IsEqual(ar[i], ar[i+1]))\n {\n op++;\n ar[i] = \'A\';\n }\n }\n\n for(int i=1; i<ar.Length; i++)\n {\n if (IsEqual(ar[i-1], ar[i]))\n {\n op++;\n ar[i] = \'B\';\n }\n }\n \n return op;\n }\n\n private bool Valid(char[] ar)\n {\n for(int i=1; i<ar.Length; i++)\n {\n if (IsEqual(ar[i-1], ar[i]))\n {\n return false;\n }\n }\n return true;\n }\n\n private bool IsEqual(char a, char b)\n {\n if (a == b)\n {\n return true;\n }\n int x = (int)(a - \'a\');\n int y = (int)(b - \'a\');\n return Math.Abs(x-y) == 1;\n }\n}\n```
| 0 | 0 |
['C#']
| 0 |
remove-adjacent-almost-equal-characters
|
C++ solution ( Beats 100%)
|
c-solution-beats-100-by-anu_ravish-z1at
|
\n\n# Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n
|
Anu_ravish
|
NORMAL
|
2024-08-23T06:14:09.518920+00:00
|
2024-08-23T06:14:09.518948+00:00
| 1 | false |
\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int count=0;\n vector<int> integer;\n for(int i=0;i< word.length();i++ ){\n char x = word.at(i);\n integer.push_back(int(x));\n }\n for(int i=0;i<integer.size()-1;i++){\n if(integer[i]==integer[i+1]||(integer[i]==(integer[i+1]-1))||(integer[i]-1)==integer[i+1]){\n count++;\n i++;\n }\n }\n return count;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
O(n) sliding window
|
on-sliding-window-by-ch0pstickerism-fgkd
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe first concern is that performing the operation on one character might accidentall
|
ch0pstickerism
|
NORMAL
|
2024-08-17T17:33:33.204465+00:00
|
2024-08-17T17:33:33.204493+00:00
| 4 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe first concern is that performing the operation on one character might accidentally make it almost equal to another character, but this was quickly dismissed -- we just need to make the value different than both neighbors. \n\nThe other thought is that the answer is relatively clear if we have a string of length n where all the characters are almost equal to each other, the answer should be floor(n / 2), since we can change every other value, starting at the second character.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nWe use a sliding window to keep track of the current length of the substring where the ith character is almost equal to the (i+1)th character. Once we find a character that is not almost equal to the previous, we add floor(right - left / 2).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def removeAlmostEqualCharacters(self, word: str) -> int:\n def almost_equal(a,b):\n return abs(ord(a)-ord(b)) < 2\n #if there is a chain of length n, need to change n // 2?\n ans = 0\n left = 0\n prev = word[left]\n for right in range(1,len(word)):\n if not almost_equal(word[right], prev):\n ans += (right - left) // 2\n left = right\n prev = word[right]\n ans += (len(word) - left) // 2\n return ans\n\n \n```
| 0 | 0 |
['Python3']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy and Straight forward Java Solution with explanation.(Greedy)
|
easy-and-straight-forward-java-solution-1t985
|
APPROACH\n- if two characters has conflicts then changing the right-most character is the most optimal (if you are traversing left to right).\nfor eg:\n\t[a,b,c
|
vishwajeet_rauniyar
|
NORMAL
|
2024-08-13T12:29:14.225331+00:00
|
2024-08-13T12:29:14.225365+00:00
| 2 | false |
**APPROACH**\n- if two characters has conflicts then changing the right-most character is the most optimal (if you are traversing left to right).\nfor eg:\n\t[a,b,c]\n\there is conflit between a and b so we should change \'b\' and it will automatically resolve the conflit with c.\n- we can change to any character to resolve conflict so we will choose a character which don\'t create a new conflict with nearby character.\n- choosing from a to z may be overhelming so we will replace each conflicting character with \'*\' since we don\'t have to return the actual string.\n- each change will increase the count.\n- return count\n\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int size = word.length();\n int count = 0;\n char ch[] = word.toCharArray();\n for(int i = 1;i<size;i++)\n {\n if((Math.abs(ch[i]-ch[i-1])<=1))\n {\n \tch[i] = \'*\';\n count++;\n }\n\n }\n return count;\n }\n}\n```
| 0 | 0 |
['Greedy', 'Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple C++| Beat 100%
|
simple-c-beat-100-by-nguyentientrung204-872u
|
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
|
nguyentientrung204
|
NORMAL
|
2024-08-11T16:48:47.113049+00:00
|
2024-08-11T16:48:47.113081+00:00
| 1 | false |
# 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 {\npublic:\n int removeAlmostEqualCharacters(string word) {\n word = \'@\' + word + \'@\';\n vector<int> temp(word.size(), 0);\n int res = 0;\n for (int i = 1; i < word.size() - 1; i++) {\n if (abs(word[i+1] - word[i]) <= 1 && temp[i-1] != 1) {\n temp[i] = 1;\n } \n else if (abs(word[i+1] - word[i]) <= 1 && temp[i-1] == 1) {\n temp[i] = 2;\n temp[i-1] = 0;\n }\n }\n for (int i=0; i< temp.size() ; i++) {\n if (temp[i] == 1 || temp[i] == 2) {\n res++;\n }\n }\n return res;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple java solution beats 100% without DP
|
simple-java-solution-beats-100-without-d-apdw
|
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
|
user5475a
|
NORMAL
|
2024-08-10T11:06:11.937527+00:00
|
2024-08-10T11:06:11.937569+00:00
| 1 | false |
# 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 public int removeAlmostEqualCharacters(String word) {\n \n int count=0;\n for(int i=0;i<word.length()-1;)\n {\n if(word.charAt(i)==word.charAt(i+1) || Math.abs( word.charAt(i) -word.charAt(i+1) )==1 ){\n count++; i=i+2;\n }\n else\n i++;\n }\n return count;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy to understand solution
|
easy-to-understand-solution-by-masacr-0bcj
|
Intuition\n Describe your first thoughts on how to solve this problem. \nIntuition told me there was a pretty simple solution to this problem, and after thiking
|
Masacr
|
NORMAL
|
2024-08-09T09:38:39.172508+00:00
|
2024-08-09T09:38:39.172536+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition told me there was a pretty simple solution to this problem, and after thiking about it for a bit arrived at the conclusion that the amount of changes needed is gonna be the sum of the rounded down division of the size of each group of letters divided by 2. For example if we have a group of 3 similar letters (a,b,c) we only need to change b for the string to no longer have 3 similar letters in a row.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust thinking of an easy to implement and easy to read solution I decided on simply looping through the string once, storing the last char into a variable and comparing the last char with the current one, adding the number of almost equal letters to a counter and, whenever the chars are not almost equal or we finish the string, we add the counter / 2 to the total result.\n\n# Complexity\n- Time complexity: O(n) we loop only once the string, so n is the size of the string\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) we only use the given string and 3 other variables\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimpl Solution {\n pub fn remove_almost_equal_characters(word: String) -> i32 {\n let mut last_char = \' \';\n let mut counter = 1;\n let mut total_result = 0;\n for char in word.chars() {\n if last_char.to_digit(36) != None && char.to_digit(36).unwrap().abs_diff(last_char.to_digit(36).unwrap()) <= 1{\n counter += 1;\n }else{\n if counter > 1{\n total_result += counter / 2;\n }\n\n counter = 1;\n }\n last_char = char;\n }\n\n if counter > 1{\n total_result += counter / 2;\n }\n\n return total_result;\n }\n}\n```
| 0 | 0 |
['Rust']
| 0 |
remove-adjacent-almost-equal-characters
|
Go 0ms O(n) solution
|
go-0ms-on-solution-by-tjucoder-slqv
|
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nfunc removeAlmostEqualCharacters(word string) int {\n op := 0\n for i := 0;
|
tjucoder
|
NORMAL
|
2024-08-08T17:24:49.533973+00:00
|
2024-08-08T17:24:49.533994+00:00
| 7 | false |
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nfunc removeAlmostEqualCharacters(word string) int {\n op := 0\n for i := 0; i+1 < len(word); i++ {\n if word[i] == word[i+1] || word[i] + 1 == word[i+1] || word[i] == word[i+1] + 1 {\n op++\n i++\n }\n }\n return op\n}\n```
| 0 | 0 |
['Go']
| 0 |
remove-adjacent-almost-equal-characters
|
Python || Easy || 4 lines code || Beats 98%
|
python-easy-4-lines-code-beats-98-by-pkj-1z7u
|
\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n Add your space complexity here, e.g. O(n) \n\n# Code\n\nclass Solution(object):\n def removeAlmostEqualChara
|
pkjha992004
|
NORMAL
|
2024-08-05T10:18:53.958128+00:00
|
2024-08-05T10:18:53.958162+00:00
| 2 | false |
\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def removeAlmostEqualCharacters(self, word):\n """\n :type word: str\n :rtype: int\n """\n count = 0\n x = list(word)\n for i in range(1,len(word)):\n if ord(x[i]) == ord(x[i-1]) + 1 or ord(x[i]) == ord(x[i-1]) - 1 or ord(x[i]) == ord(x[i-1]):\n count +=1\n x[i] = "*"\n return count\n \n```
| 0 | 0 |
['Python']
| 0 |
remove-adjacent-almost-equal-characters
|
Linear Check
|
linear-check-by-2pp0ereztt68w6n-gthb
|
We can go over the characters in a single iteration (linear solution) and check if two consecutive characters are adjacent. We would always update the later one
|
2PP0erEZTT68w6N
|
NORMAL
|
2024-08-02T06:22:42.429360+00:00
|
2024-08-02T06:22:42.429395+00:00
| 3 | false |
We can go over the characters in a single iteration (`linear` solution) and check if two consecutive characters are adjacent. We would always update the later one, as there is no benefit or updating the earlier one. Assuming there are more characters in the string (e.g. idx `2`), and we are upadting the middle (idx `1`) one between any two (e.g. `0` and `2`). There is always a possibe update among the 26 possible values that we can chose (for idx `1`) that will be not adjacent with the 2 characters (at idx `0` and `2`). This means that if we find adjacent characers at index `0` and `1`, we can skip comparing the next pair (at index `1` and `2`).\n\n# Code\n```\nclass Solution {\nprivate:\nbool isAdjacent (char a, char b) {\n return abs (a - b) < 2;\n}\n\npublic:\n int removeAlmostEqualCharacters(string word) {\n \n int changeCount = 0;\n \n for (int idx = 0; idx < word.length() - 1; idx++) {\n char first = word[idx];\n char second = word[idx + 1];\n \n if (isAdjacent(first, second)) {\n changeCount++;\n idx++; // skip the next check. IF we have "xyz" we can modify "y" to avoid being adjacent with "z", too. No need to check the next position.\n }\n }\n\n return changeCount;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Java Solution
|
java-solution-by-ceosricharan-8ut9
|
Code\n\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n char a,b;\n int res=0;\n for(int i=0;i<word.length()-
|
CEOSRICHARAN
|
NORMAL
|
2024-07-29T17:17:28.266683+00:00
|
2024-07-29T17:17:28.266699+00:00
| 0 | false |
# Code\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n char a,b;\n int res=0;\n for(int i=0;i<word.length()-1;){\n a=word.charAt(i);\n b=word.charAt(i+1);\n if(a==b || (a+1)==b || (a-1)==b){\n res++;\n i+=2;\n }\n else{\n i++;\n }\n }\n return res;\n }\n}\n```
| 0 | 0 |
['Two Pointers', 'Java']
| 0 |
remove-adjacent-almost-equal-characters
|
DP (for fun)
|
dp-for-fun-by-macrohard-64js
|
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
|
macrohard
|
NORMAL
|
2024-07-29T07:40:32.502586+00:00
|
2024-07-29T07:40:32.502614+00:00
| 0 | false |
# 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 public int removeAlmostEqualCharacters(String word) {\n int[] dp = new int[128];\n for(int i = 0; i < word.length(); i++) {\n char c = word.charAt(i);\n int[] dp2 = new int[128];\n for(char j = \'a\'; j <= \'z\'; j++) {\n int min = word.length();\n for(char k = \'a\'; k <= \'z\'; k++) {\n if(j - 1 <= k && k <= j + 1) continue;\n min = Math.min(min, dp[k]);\n }\n if(c != j) min++;\n dp2[j] = min;\n }\n dp = dp2;\n }\n int res = word.length();\n for(char a = \'a\'; a <= \'z\'; a++) {\n res = Math.min(res, dp[a]);\n }\n return res;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
using Recursion
|
using-recursion-by-harshitajn25-et7w
|
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
|
harshitajn25
|
NORMAL
|
2024-07-27T08:47:26.332842+00:00
|
2024-07-27T08:47:26.332878+00:00
| 1 | false |
# 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 {\npublic:\n int t[102];\n //Arrays.fill(t,-1);\n Solution() {\n memset(t, -1, sizeof(t));\n }\n int func(string word , int n){\n if(n<=0) return 0;\n if(t[n]!=-1){\n return t[n];\n }\n if(word[n]==word[n-1] || word[n]-word[n-1]==1 || word[n]- word[n-1]==-1){\n return t[n]=max(1+func(word , n-2) , func(word , n-1));\n }\n else {\n return t[n]=func(word , n-1);\n }\n\n }\n int removeAlmostEqualCharacters(string word) {\n return func(word , word.length()-1);\n }\n\n //return t[n];\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple and Easy JAVA solution beats 100%
|
simple-and-easy-java-solution-beats-100-af1oq
|
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
|
Triyaambak
|
NORMAL
|
2024-07-17T11:37:28.815408+00:00
|
2024-07-17T11:37:55.891908+00:00
| 0 | false |
# 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 public int removeAlmostEqualCharacters(String word) {\n StringBuilder sb = new StringBuilder(word);\n int res = 0;\n for(int i=1;i<sb.length();i++){\n if(Math.abs(sb.charAt(i) - sb.charAt(i-1))<=1){\n sb.setCharAt(i,\'*\');\n res++;\n }\n }\n return res;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy Solution
|
easy-solution-by-rijitb-zqth
|
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
|
rijitb
|
NORMAL
|
2024-07-17T08:38:59.793933+00:00
|
2024-07-17T08:38:59.793955+00:00
| 4 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int ans=0;\n int n=word.size();\n for(int i=1;i<n;){\n if (abs(word[i]-word[i-1])<=1){\n ans++;\n i+=2;\n }\n else i++;\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
scala pattern match
|
scala-pattern-match-by-vititov-mklh
|
scala\nobject Solution {\n def removeAlmostEqualCharacters(word: String): Int =\n def f(l: List[Char], acc: Int): Int = l match {\n case _ :: Nil | Nil
|
vititov
|
NORMAL
|
2024-07-16T12:58:55.035397+00:00
|
2024-07-16T12:59:59.517022+00:00
| 0 | false |
```scala\nobject Solution {\n def removeAlmostEqualCharacters(word: String): Int =\n def f(l: List[Char], acc: Int): Int = l match {\n case _ :: Nil | Nil => acc\n case a::b::t if (a-b).abs<=1 => f(t,acc+1)\n case _ :: t => f(t,acc)\n }\n f(word.toList,0)\n}\n```
| 0 | 0 |
['Linked List', 'String', 'Greedy', 'Scala']
| 0 |
remove-adjacent-almost-equal-characters
|
easy and fastest solution in c++|| beats 100% codes
|
easy-and-fastest-solution-in-c-beats-100-z6v4
|
\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(N)\n\n- Space complexity:\n Add your space complexity here, e.g. O(n) \nO(1)\n
|
shubhamraj2002
|
NORMAL
|
2024-07-15T00:00:19.168915+00:00
|
2024-07-15T00:00:19.168942+00:00
| 0 | false |
\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) \n {\n int change=0;\n int ans=0;\n if((abs(word[0]-word[1]))<=1)\n {\n change=1;\n ans=1;\n }\n\n int n=word.length();\n for(int i=2; i<word.length(); i+=2)\n {\n // cout<<i<<" ";\n if((i+1<n)&&((i-1)==change)&&((abs(word[i]-word[i+1]))<=1))\n {\n // cout<<"Hello"<<endl;\n change=i+1;\n ans++;\n }\n else if((i-1)!=change)\n {\n if((abs(word[i]-word[i-1]))<=1)\n {\n // cout<<i<<" ";\n ans+=1;\n change=i;\n }\n else if((i+1<n)&&(abs(word[i]-word[i+1])<=1))\n {\n change=i+1;\n ans++;\n }\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Easiest solution in CPP
|
easiest-solution-in-cpp-by-adityadolui-e6iv
|
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
|
AdityaDolui
|
NORMAL
|
2024-07-12T12:08:15.504049+00:00
|
2024-07-12T12:08:15.504115+00:00
| 0 | false |
# 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 {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int n=word.length();\n int ans=0;\n for(int i=1;i<n;i++){\n if(abs(word[i-1]-word[i])<=1){\n word[i]=\'A\';\n ans++;\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['String', 'Greedy', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple Greedy Solution
|
simple-greedy-solution-by-parth_hem04-10vn
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nFor ith character, check if it is equal to the adjacent element or alphab
|
PH_0904
|
NORMAL
|
2024-06-29T03:27:33.450973+00:00
|
2024-06-29T03:27:33.450995+00:00
| 0 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nFor ith character, check if it is equal to the adjacent element or alphabetically adjacent, if so, **update it to some other alphabet such that word[i]!=word[i+1] (i<word.length()-1) and word[i]!= word[i-1] (i>0). Increment the count by 1 and also,increment i by 2**, because we have already updated the string for two adjacent characters.\nOtherwise increment i by 1 only.\nHope this helps!\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 {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int i,op=0;\n if(word.length()==1) return 0;\n for(i=0;i<word.length()-1;){\n if(word[i]==word[i+1] || word[i]==(char)(word[i+1]+1)|| word[i]==(char)(word[i+1]-1)){\n if(i>0 && i<word.length()-1){\n for(char ch=\'a\';ch<=\'z\';ch++){\n if(ch!=word[i+1] && ch!=word[i-1]){\n word[i]=ch;\n break;}}}\n else if(i==0){\n for(char ch=\'a\';ch<=\'z\';ch++){\n if(ch!=word[i+1]){\n word[i]=ch;\n break;}}}\n op++;\n i+=2;}\n else{\n i++;}}\n return op;}};\n```
| 0 | 0 |
['Greedy', 'C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Disjoint Set Union, Beats 100% of submissions
|
disjoint-set-union-beats-100-of-submissi-2tqb
|
Intuition\n Describe your first thoughts on how to solve this problem. \nProblem constraints are like DSU may not be be the best idea to solve it. But DSU solut
|
toyash
|
NORMAL
|
2024-06-26T14:54:45.617166+00:00
|
2024-06-27T00:04:49.969462+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nProblem constraints are like DSU may not be be the best idea to solve it. But DSU solution may work equally well for n being 10^5. Each component of size k may require k/2 operations:\na-> 0\naa-> 1 (ac)\naaa-> 1 (aca)\naaaa-> 2 (acac)\naaaaa-> 2 (acaca)\n.......\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe iterate over each character and do union operation with the left and right characters if the absolute difference between the ASCII values is less than or equal to 1. Then we iterate over the elements of the DSU array to get the components size from the root node and increment componentSize/2 to the result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*\u03B1(n))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass UnionFind\n{\n public:\n vector<int> id, sz;\n UnionFind(int n) : id(vector<int>(n)), sz(vector<int>(n, 1))\n {\n iota(id.begin(), id.end(), 0);\n }\n int find(int p)\n {\n int root = id[p];\n while(root != id[root]) root = id[root];\n while(root != p)\n {\n int k = id[p];\n id[p] = root;\n p = k;\n }\n return root;\n }\n void getUnion(int p, int q)\n {\n int root1 = find(p);\n int root2 = find(q);\n if(root1 == root2) return;\n if(sz[root1] > sz[root2])\n {\n id[root2] = root1;\n sz[root1] += sz[root2];\n }\n else\n {\n id[root1] = root2;\n sz[root2] += sz[root1];\n }\n }\n};\nclass Solution {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int n = word.length();\n UnionFind obj(n);\n for(int i = 0; i < n; i++)\n {\n if(i+1 < n && abs(word[i+1] - word[i]) <= 1) obj.getUnion(i, i+1);\n if(i-1 >= 0 && abs(word[i-1] - word[i]) <= 1) obj.getUnion(i, i-1);\n }\n int res = 0;\n for(int i = 0; i < n; i++)\n if(obj.id[i] == i) res += obj.sz[i] / 2;\n return res;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Simple Solution
|
simple-solution-by-rk0-p1d5
|
Intuition\nJust think about prev, curr and next(for this question we can ignore next) element of the string\n\n# Approach\nCheck both conditions to make string
|
rk0
|
NORMAL
|
2024-06-16T11:17:30.424602+00:00
|
2024-06-16T11:17:30.424627+00:00
| 10 | false |
# Intuition\nJust think about prev, curr and next(for this question we can ignore next) element of the string\n\n# Approach\nCheck both conditions to make string beautiful, on prev and curr character. We don\'t have to worry about modifying the character as we only have to return the count. if condition does not match we hypothetically need to modify current character, and we have 22 possible character to choose from, leaving string[i-1] and string[i+1] and there sequestial character.\nso just increase the index from i+1 to i+2 as we have taken care of both i-1, i, i+1.\n\n\n# Code\n```\n/**\n * @param {string} word\n * @return {number}\n */\nvar removeAlmostEqualCharacters = function(word) {\n let count=0;\n const n=word.length;\n for(let i=1;i<n;i++) {\n const isNotBeautiful1 = word[i-1]===word[i];\n const isNotBeautiful2 = Math.abs(word[i-1].charCodeAt(0)-word[i].charCodeAt(0))<=1;\n if(isNotBeautiful1 || isNotBeautiful2) {\n count++;\n i++;\n }\n }\n return count;\n};\n```
| 0 | 0 |
['JavaScript']
| 0 |
remove-adjacent-almost-equal-characters
|
100% CPP
|
100-cpp-by-deshmukhrao-0s8n
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\nIf an "almost equal" pair is found, ans is incremented by 1.\nThe index
|
DeshmukhRao
|
NORMAL
|
2024-06-15T16:18:27.108195+00:00
|
2024-06-15T16:18:27.108214+00:00
| 0 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nIf an "almost equal" pair is found, ans is incremented by 1.\nThe index i is incremented by 1 again (total increment by 2 for this iteration) to skip to the next non-overlapping pair. This prevents counting overlapping pairs.\nFor example, in the string "ab", after counting the pair (\'a\', \'b\'), the loop skips over \'b\' to avoid checking overlapping pairs like (\'b\', \'c\') if \'c\' were the next character.\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 {\npublic:\n int removeAlmostEqualCharacters(string s) {\n int ans = 0;\n for(int i = 0; i < s.size() - 1; i ++) {\n if(abs(s[i] - s[i + 1]) <= 1) {\n ans += 1;\n i += 1;\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
remove-adjacent-almost-equal-characters
|
Java
|
java-by-sumeetrayat-wsz5
|
Code\n\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int count=0;\n\t\tfor (int i = 0; i<=word.length()-1; i++) {\n\t\t\
|
sumeetrayat
|
NORMAL
|
2024-06-15T03:17:47.626478+00:00
|
2024-06-15T03:17:47.626504+00:00
| 1 | false |
# Code\n```\nclass Solution {\n public int removeAlmostEqualCharacters(String word) {\n int count=0;\n\t\tfor (int i = 0; i<=word.length()-1; i++) {\n\t\t\t\n\t\t\tif(i==word.length()-1)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(Math.abs((int)word.charAt(i)-(int)word.charAt(i+1))==0 ||Math.abs((int)word.charAt(i)-(int)word.charAt(i+1))==1 )\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\ti=i+1;\n\t\t\t\t\n\t\t\t}\n\t\t}\n return count;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
Easy
|
easy-by-xtreamhd1478-tyr7
|
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
|
xtreamhd1478
|
NORMAL
|
2024-06-07T01:14:18.469107+00:00
|
2024-06-07T01:14:18.469141+00:00
| 0 | false |
# 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 public int removeAlmostEqualCharacters(String s) {\n int ans = 0;\n int i = 0;\n while (i < s.length() - 1) {\n if (Math.abs((int) s.charAt(i) - (int) s.charAt(i + 1)) ==1 || \n Math.abs((int) s.charAt(i) - (int) s.charAt(i + 1)) ==0) {\n i += 2;\n ans++;\n } else\n i++;\n }\n return ans;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
remove-adjacent-almost-equal-characters
|
cpp
|
cpp-by-pankajkumar101-z4re
|
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
|
PankajKumar101
|
NORMAL
|
2024-05-29T02:38:03.123034+00:00
|
2024-05-29T02:38:03.123053+00:00
| 0 | false |
# 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 {\npublic:\n int removeAlmostEqualCharacters(string word) {\n int ans = 0;\n for(int i = 1;i<word.length();i++){\n \n if(word[i]>=word[i-1] && word[i]-word[i-1]<=1)\n {\n ans++;\n i++;\n }\n else if(word[i]<word[i-1] && word[i-1]-word[i]<=1){\n ans++;\n i++;\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
maximal-rectangle
|
Share my DP solution
|
share-my-dp-solution-by-morrischen2008-nq4a
|
The DP solution proceeds row by row, starting from the first row. Let the maximal rectangle area at row i and column j be computed by [right(i,j) - left(i,j)]he
|
morrischen2008
|
NORMAL
|
2015-01-02T20:48:08+00:00
|
2018-10-25T18:56:37.062211+00:00
| 228,147 | false |
The DP solution proceeds row by row, starting from the first row. Let the maximal rectangle area at row i and column j be computed by [right(i,j) - left(i,j)]*height(i,j).\n\nAll the 3 variables left, right, and height can be determined by the information from previous row, and also information from the current row. So it can be regarded as a DP solution. The transition equations are:\n\n> left(i,j) = max(left(i-1,j), cur_left), cur_left can be determined from the current row\n\n> right(i,j) = min(right(i-1,j), cur_right), cur_right can be determined from the current row \n\n> height(i,j) = height(i-1,j) + 1, if matrix[i][j]=='1'; \n\n> height(i,j) = 0, if matrix[i][j]=='0'\n\n\n\nThe code is as below. The loops can be combined for speed but I separate them for more clarity of the algorithm.\n\n class Solution {public:\n int maximalRectangle(vector<vector<char> > &matrix) {\n if(matrix.empty()) return 0;\n const int m = matrix.size();\n const int n = matrix[0].size();\n int left[n], right[n], height[n];\n fill_n(left,n,0); fill_n(right,n,n); fill_n(height,n,0);\n int maxA = 0;\n for(int i=0; i<m; i++) {\n int cur_left=0, cur_right=n; \n for(int j=0; j<n; j++) { // compute height (can do this from either side)\n if(matrix[i][j]=='1') height[j]++; \n else height[j]=0;\n }\n for(int j=0; j<n; j++) { // compute left (from left to right)\n if(matrix[i][j]=='1') left[j]=max(left[j],cur_left);\n else {left[j]=0; cur_left=j+1;}\n }\n // compute right (from right to left)\n for(int j=n-1; j>=0; j--) {\n if(matrix[i][j]=='1') right[j]=min(right[j],cur_right);\n else {right[j]=n; cur_right=j;} \n }\n // compute the area of rectangle (can do this from either side)\n for(int j=0; j<n; j++)\n maxA = max(maxA,(right[j]-left[j])*height[j]);\n }\n return maxA;\n }\n};\n\n\nIf you think this algorithm is not easy to understand, you can try this example:\n\n 0 0 0 1 0 0 0 \n 0 0 1 1 1 0 0 \n 0 1 1 1 1 1 0\n\nThe vector "left" and "right" from row 0 to row 2 are as follows\n\nrow 0:\n \n\n l: 0 0 0 3 0 0 0\n r: 7 7 7 4 7 7 7\n\nrow 1:\n\n l: 0 0 2 3 2 0 0\n r: 7 7 5 4 5 7 7 \n\nrow 2:\n\n l: 0 1 2 3 2 1 0\n r: 7 6 5 4 5 6 7\n\nThe vector "left" is computing the left boundary. Take (i,j)=(1,3) for example. On current row 1, the left boundary is at j=2. However, because matrix[1][3] is 1, you need to consider the left boundary on previous row as well, which is 3. So the real left boundary at (1,3) is 3. \n\nI hope this additional explanation makes things clearer.
| 1,419 | 24 |
[]
| 155 |
maximal-rectangle
|
A O(n^2) solution based on Largest Rectangle in Histogram
|
a-on2-solution-based-on-largest-rectangl-gh0v
|
This question is similar as [\[Largest Rectangle in Histogram\]][1]:\n\nYou can maintain a row length of Integer array H recorded its height of '1's, and scan a
|
wangyushawn
|
NORMAL
|
2014-05-11T22:25:45+00:00
|
2018-10-24T01:14:45.568107+00:00
| 115,615 | false |
This question is similar as [\\[Largest Rectangle in Histogram\\]][1]:\n\nYou can maintain a row length of Integer array H recorded its height of '1's, and scan and update row by row to find out the largest rectangle of each row.\n\nFor each row, if matrix[row][i] == '1'. H[i] +=1, or reset the H[i] to zero.\nand accroding the algorithm of [Largest Rectangle in Histogram], to update the maximum area.\n\n public class Solution {\n public int maximalRectangle(char[][] matrix) {\n if (matrix==null||matrix.length==0||matrix[0].length==0)\n return 0;\n int cLen = matrix[0].length; // column length\n int rLen = matrix.length; // row length\n // height array \n int[] h = new int[cLen+1];\n h[cLen]=0;\n int max = 0;\n \n \n for (int row=0;row<rLen;row++) {\n Stack<Integer> s = new Stack<Integer>();\n for (int i=0;i<cLen+1;i++) {\n if (i<cLen)\n if(matrix[row][i]=='1')\n h[i]+=1;\n else h[i]=0;\n \n if (s.isEmpty()||h[s.peek()]<=h[i])\n s.push(i);\n else {\n while(!s.isEmpty()&&h[i]<h[s.peek()]){\n int top = s.pop();\n int area = h[top]*(s.isEmpty()?i:(i-s.peek()-1));\n if (area>max)\n max = area;\n }\n s.push(i);\n }\n }\n }\n return max;\n }\n }\n\n [1]: http://oj.leetcode.com/problems/largest-rectangle-in-histogram/
| 453 | 5 |
[]
| 57 |
maximal-rectangle
|
AC Python DP solutioin 120ms based on largest rectangle in histogram
|
ac-python-dp-solutioin-120ms-based-on-la-evxb
|
def maximalRectangle(self, matrix):\n if not matrix or not matrix[0]:\n return 0\n n = len(matrix[0])\n height = [0] * (n + 1)\n
|
dietpepsi
|
NORMAL
|
2015-10-23T17:36:29+00:00
|
2018-10-24T18:24:19.114011+00:00
| 41,133 | false |
def maximalRectangle(self, matrix):\n if not matrix or not matrix[0]:\n return 0\n n = len(matrix[0])\n height = [0] * (n + 1)\n ans = 0\n for row in matrix:\n for i in xrange(n):\n height[i] = height[i] + 1 if row[i] == '1' else 0\n stack = [-1]\n for i in xrange(n + 1):\n while height[i] < height[stack[-1]]:\n h = height[stack.pop()]\n w = i - 1 - stack[-1]\n ans = max(ans, h * w)\n stack.append(i)\n return ans\n\n # 65 / 65 test cases passed.\n # Status: Accepted\n # Runtime: 120 ms\n # 100%\n\nThe solution is based on [largest rectangle in histogram][1] solution. Every row in the matrix is viewed as the ground with some buildings on it. The building height is the count of consecutive 1s from that row to above rows. The rest is then the same as [this solution for largest rectangle in histogram][2]\n\n\n [1]: https://leetcode.com/problems/largest-rectangle-in-histogram/\n [2]: https://leetcode.com/discuss/65647/ac-python-clean-solution-using-stack-76ms
| 433 | 3 |
['Dynamic Programming', 'Python']
| 40 |
maximal-rectangle
|
✅ [C++] Simple Solution w/ Explanation | Optimizations from Brute-Force to DP
|
c-simple-solution-w-explanation-optimiza-bjf8
|
We are given a matrix M and required to find the area of largest rectangle having all "1" within it.\n\n---\n\n\u274C Solution - I (Brute-Force)\n\nThe most bru
|
archit91
|
NORMAL
|
2021-11-30T13:05:00.299666+00:00
|
2021-11-30T13:51:29.419316+00:00
| 21,381 | false |
We are given a matrix `M` and required to find the area of largest rectangle having all `"1"` within it.\n\n---\n\n\u274C ***Solution - I (Brute-Force)***\n\nThe most brute force way of solving this problem would be to simply consider each and every possible rectangle and consider the maximal out of the rectangles which only consists of `1` in them\n\n```cpp\nclass Solution {\npublic:\n int maximalRectangle(vector<vector<char>>& M) {\n if(!size(M)) return 0;\n int ans = 0, m = size(M), n = size(M[0]);\n for(int start_i = 0; start_i < m; start_i++) \n for(int start_j = 0; start_j < n; start_j++) \n for(int end_i = start_i; end_i < m; end_i++) \n for(int end_j = start_j; end_j < n; end_j++) {\n bool allOnes = true;\n for(int i = start_i; i <= end_i && allOnes; i++) \n for(int j = start_j; j <= end_j && allOnes; j++) \n if(M[i][j] != \'1\') allOnes = false; \n ans = max(ans, allOnes * (end_i - start_i + 1) * (end_j - start_j + 1));\n }\n\n return ans;\n }\n};\n```\n\n***Time Complexity :*** <code>O((MN)<sup>3</sup>)</code>\n***Space Complexity :*** <code>O(1)</code>\n\n---\n\n\n\u2714\uFE0F ***Solution - II (Optimized Brute-Force)***\n\nInstead of forming every rectangle, then checking validity of rectangle, we can optimize the brute-force by only considering valid rectangles. For this, we can start from every cell and consider valid rectangle starting from that cell. \n* Let the current cell be at `(i, j)`.\n* We first consider `i`th row and find maximum column length of 1s starting from `M[i][j]`.\n* Then move to `i+1`th row and find maximum column length of 1s starting from `M[i+1][j]`. Take minimum of all lengths and find the area and keep updating max area.\n* Continue similar process till you reach last row and then repeat the process for all other cells as well.\n* Finally return maximum area found from all valid rectangles.\n\nThe below image illustrates the process for first two cells of the grid -\n\n<img src="https://assets.leetcode.com/users/images/6a6c48d6-32be-4a61-8408-309b3217cb3c_1638279969.659467.png" />\n\n\n\n```cpp\nclass Solution {\npublic:\n int maximalRectangle(vector<vector<char>>& M) {\n if(!size(M)) return 0;\n int ans = 0, m = size(M), n = size(M[0]);\n for(int i = 0; i < m; i++) \n for(int j = 0; j < n; j++) \n for(int row = i, colLen = n, col; row < m && M[row][j] == \'1\'; row++) {\n for(col = j; col < n && M[row][col] == \'1\'; col++);\n colLen = min(colLen, col-j);\n ans = max(ans, (row-i+1) * colLen);\n }\n \n return ans;\n }\n};\n```\n\n***Time Complexity :*** <code>O((MN)<sup>2</sup>)</code>\n***Space Complexity :*** <code>O(1)</code>\n\n---\n\n\u2714\uFE0F ***Solution - III (Pre-compute consecutive 1s to the right / DP)***\n\nWe can improve previous solution if we pre-compute the maximum number of 1s to the right of each cell. This will allow us to save save the iteration for finding maximum column length of 1s starting from `M[i][j]` in the previous solution. After a pre-computation which requires `O(MN)` time, we can compute the maximum column length in just `O(1)` essentially eliminating a loop from above solution.\n\n```cpp\nclass Solution {\npublic:\n int maximalRectangle(vector<vector<char>>& M) {\n if(!size(M)) return 0;\n int ans = 0, m = size(M), n = size(M[0]);\n vector<vector<short>> dp(m+1, vector<short>(n+1));\n for(int i = m-1; ~i; i--) \n for(int j = n-1; ~j; j--) \n dp[i][j] = M[i][j] == \'1\' ? dp[i][j+1] + 1 : 0;\n \n for(int i = 0; i < m; i++) \n for(int j = 0; j < n; j++) \n for(int row = i, colLen = n; row < m && M[row][j] == \'1\'; row++)\n ans = max(ans, (row-i+1) * (colLen = min(colLen, dp[row][j]*1)));\n \n return ans;\n }\n};\n```\n\n***Time Complexity :*** <code>O(M<sup>2</sup>N)</code>\n***Space Complexity :*** <code>O(MN)</code>\n\n---\n\n\u2714\uFE0F ***Solution - IV (Pre-compute consecutive 1s to right + number of rows above & below having atleast same number of consecutive 1s / DP)***\n\nWe can eliminate one more loop in the above solution before we arrive at the optimal solution. In previous approach, we pre-computed the number of consecutive 1s to the right of each cell (referred as `dp[i][j]` henceforth) allowing us to eliminate iterate whole columns for each row. But, still we required to iterate from each row till bottom because we didnt know if other rows below had smaller `dp[i][j]` and thus we had to keep adjusting `colLen` to hold minimum `dp[i][j]` checking for each row till the bottom.\n\nTo avoid this, we can take a slightly different approach and only **check the consecutive number of rows above and below, that have the same or greater `dp[i][j]`**. This ensures that using the current cell, we can form a rectangle of width `dp[i][j]` and use current row + number of rows above & below having same or greater `dp[i][j]`. We must note that this approach ensures that we only considering maximal area rectangle having width `dp[i][j]`, for each cell under consideration, since we are also using the max possible height for that width.\n\n**Computing `up` and `down`:**\n\nNow, the only thing remaining is how to calculate number of rows above and below having atleast `dp[i][j]`. This can be calculated from `dp` using a monotonic stack. For this, we compute two matrices `up` and `down` where `up[i][j]` will denote consecutive number of rows above `i` (and including current) having corresponding value of `dp` for each row as atleast `dp[i][j]` and similarly `down[i][j]` denotes consecutive number of rows below `j` (and including current) each having corresponding value of `dp` for each rows as atleast equal to `dp[i][j]`.\n\nFor calculating `up` matrix- \n1. We iterate from 1st row till last row. \n2. Each time, we get a row having `dp[i][j] >= dp[s.top()][j]`, we push it into stack. \n3. If we get a row having `dp[i][j] < dp[s.top()][j]`, we pop from stack until we find row index in stack having atleast `dp[i][j]`. This helps maintain the monotonous stack. \n4. At each iteration, the value of `up[i][j]` is equal to `i-s.top()` (current row - row index on top of stack having atleast `dp[i][j]` for that row), i.e, number of consecutive rows above having atleast `dp[i][j]`.\n\nWe follow a similar approach for `down` as well.\n\n\n(*PS:* This approach\'s logic seems to be similar to other solutions based on largest rectangle in histogram, but with different implementation. Since my brute-force approaches were based on this, I have kept it same. The only difference is that for each cell, I have just used width and calculated `up` & `down` having same width instead of using height and calculating `left` & `right` having same height.)\n\n```cpp\nclass Solution {\npublic:\n int maximalRectangle(vector<vector<char>>& M) {\n if(!size(M)) return 0;\n int ans = 0, m = size(M), n = size(M[0]);\n vector<vector<short>> dp(m+1, vector<short>(n+1)), up(m, vector<short>(n,1)), down(up);\n for(int i = m-1; ~i; i--) \n for(int j = n-1; ~j; j--) \n dp[i][j] = M[i][j] == \'1\' ? dp[i][j+1] + 1 : 0;\n \n stack<int> s;\n for(int j = 0; j < n; j++) {\n s = stack<int>();\n for(int i = 0; i < m; i++) {\n while(size(s) && dp[s.top()][j] >= dp[i][j]) s.pop();\n up[i][j] = i - (size(s) ? s.top() : -1);\n s.push(i);\n }\n s = stack<int>();\n for(int i = m-1; ~i; i--) {\n while(size(s) && dp[s.top()][j] >= dp[i][j]) s.pop();\n down[i][j] = (size(s) ? s.top() : m) - i;\n s.push(i);\n } \n }\n\n for(int i = 0; i < m; i++) \n for(int j = 0; j < n; j++) \n ans = max(ans, dp[i][j] * (up[i][j]+down[i][j]-1));\n \n return ans;\n }\n};\n```\n\n***Time Complexity :*** <code>O(MN)</code>\n***Space Complexity :*** <code>O(MN)</code>\n\n---\n---\n\n\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, comment below \uD83D\uDC47 \n\n---\n---
| 267 | 1 |
[]
| 14 |
maximal-rectangle
|
My java solution based on Maximum Rectangle in Histogram with explanation
|
my-java-solution-based-on-maximum-rectan-45ms
|
We can apply the maximum in histogram in each row of the 2D matrix. What we need is to maintain an int array for each row, which represent for the height of the
|
atwenbobu
|
NORMAL
|
2015-08-18T15:42:12+00:00
|
2018-10-21T23:01:51.340090+00:00
| 46,662 | false |
We can apply the maximum in histogram in each row of the 2D matrix. What we need is to maintain an int array for each row, which represent for the height of the histogram.\n\nPlease refer to https://leetcode.com/problems/largest-rectangle-in-histogram/ first.\n\n\nSuppose there is a 2D matrix like\n\n1 1 0 1 0 1\n\n0 1 0 0 1 1\n\n1 1 1 1 0 1\n\n1 1 1 1 0 1\n\n\nFirst initiate the height array as 1 1 0 1 0 1, which is just a copy of the first row. Then we can easily calculate the max area is 2.\n\nThen update the array. We scan the second row, when the matrix[1][i] is 0, set the height[i] to 0; else height[i] += 1, which means the height has increased by 1. So the height array again becomes 0 2 0 0 1 2. The max area now is also 2.\n\nApply the same method until we scan the whole matrix. the last height arrays is 2 4 2 2 0 4, so the max area has been found as 2 * 4 = 8.\n\nThen reason we scan the whole matrix is that the maximum value may appear in any row of the height.\n\n\nCode as follows: \n\n public class Solution {\n public int maximalRectangle(char[][] matrix) {\n if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;\n \n int[] height = new int[matrix[0].length];\n for(int i = 0; i < matrix[0].length; i ++){\n if(matrix[0][i] == '1') height[i] = 1;\n }\n int result = largestInLine(height);\n for(int i = 1; i < matrix.length; i ++){\n resetHeight(matrix, height, i);\n result = Math.max(result, largestInLine(height));\n }\n \n return result;\n }\n \n private void resetHeight(char[][] matrix, int[] height, int idx){\n for(int i = 0; i < matrix[0].length; i ++){\n if(matrix[idx][i] == '1') height[i] += 1;\n else height[i] = 0;\n }\n } \n \n public int largestInLine(int[] height) {\n if(height == null || height.length == 0) return 0;\n int len = height.length;\n Stack<Integer> s = new Stack<Integer>();\n int maxArea = 0;\n for(int i = 0; i <= len; i++){\n int h = (i == len ? 0 : height[i]);\n if(s.isEmpty() || h >= height[s.peek()]){\n s.push(i);\n }else{\n int tp = s.pop();\n maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));\n i--;\n }\n }\n return maxArea;\n }\n \n\n}
| 218 | 0 |
['Dynamic Programming', 'Java']
| 22 |
maximal-rectangle
|
Easiest solution, build on top of leetcode84
|
easiest-solution-build-on-top-of-leetcod-a1ig
|
\npublic int maximalRectangle(char[][] matrix) {\n if(matrix.length==0) return 0;\n // for each cell with value=1, we look upward (north), the num
|
sikp
|
NORMAL
|
2018-04-06T01:03:47.358165+00:00
|
2018-08-20T22:32:43.226280+00:00
| 17,413 | false |
```\npublic int maximalRectangle(char[][] matrix) {\n if(matrix.length==0) return 0;\n // for each cell with value=1, we look upward (north), the number of continuous \'1\' is the height of cell\n int[] heights = new int[matrix[0].length];\n int maxArea=-1;\n for(int i=0; i<matrix.length; i++){\n for(int j=0; j<matrix[0].length; j++){\n if(matrix[i][j]==\'0\'){\n heights[j] = 0;\n } else {\n heights[j] ++;\n }\n } \n int area = yourLeetCode84Method(heights);\n maxArea = Math.max(maxArea, area);\n }\n return maxArea;\n }\n```
| 177 | 5 |
[]
| 29 |
maximal-rectangle
|
💯Faster✅💯Lesser✅Detailed Explaination🎯Stack🔥Height🧠Step-by-Step Explaination✅Python🐍Java🍵
|
fasterlesserdetailed-explainationstackhe-i84u
|
\uD83D\uDE80 Hi, I\'m Mohammed Raziullah Ansari, and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explain
|
Mohammed_Raziullah_Ansari
|
NORMAL
|
2024-04-13T05:21:27.175320+00:00
|
2024-04-13T06:33:15.349017+00:00
| 37,709 | false |
# \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explaination: \n- We have a 2D array `matrix` filled with `0\'s` and `1\'s`.\n- We need to find the largest rectangle containing only 1\'s and return its `area`.\n# \uD83E\uDDE0Thinking Behind the Solution:\n\nLet\'s break down the solution process into two distinct sub-processes: **Processing Height Array** and **Max Area Calculation**.\n\n### 1\uFE0F\u20E3Processing Height Array\u2705:\n1. **Initialization**:\n - Create an array `height` initialized with zeros, with length equal to the number of columns in the matrix. This array will represent the heights of bars in a histogram.\n\n2. **Processing Each Row**:\n - For each row `currRow` in the 2D matrix:\n - Traverse through each element of `currRow`.\n - If the element is `1`, increment the corresponding index in the `height` array.\n - If the element is `0`, reset the corresponding index in the `height` array to `0`.\n\n### 2\uFE0F\u20E3Max Area Calculation (Naive Approach)\uD83E\uDD13:\n- Now that we got `height` array assume that you are solving `Leetcode Problem 84. Largest Rectangle in Histogram` where we are given an array of integers `heights` representing the histogram\'s bar height where the width of each bar is 1.\n- We want to find and return the area of the largest rectangle in the histogram.\n\n**Approach**:\n - Iterate over all possible pairs of bars (i, j) where i < j.\n - For each pair (i, j), determine the minimum height `h` between the bars from index `i` to `j`.\n - Calculate the area of the rectangle formed by this pair of bars, which is `area = h * (j - i + 1)`.\n - Keep track of the maximum area found during these iterations.\n\n#### Code\uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB(TLE\u274C):\n\n\n```python []\nclass Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n if not matrix:\n return 0\n \n rows, cols = len(matrix), len(matrix[0])\n heights = [0] * (cols + 1) # Include an extra element for easier calculation\n max_area = 0\n \n for row in matrix:\n for i in range(cols):\n heights[i] = heights[i] + 1 if row[i] == \'1\' else 0\n \n # Calculate max area using histogram method\n n = len(heights) # Number of bars in the histogram\n\n for i in range(n):\n for j in range(i, n):\n # Determine the minimum height between bar i and bar j\n min_height = min(heights[k] for k in range(i, j + 1))\n # Calculate the area of the rectangle\n area = min_height * (j - i + 1)\n # Update maximum area if the current rectangle\'s area is larger\n if area > max_area:\n max_area = area\n\n return max_area\n \n```\n \n```Java []\nclass Solution {\n public int maximalRectangle(char[][] matrix) {\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n return 0;\n \n int rows = matrix.length;\n int cols = matrix[0].length;\n int[] heights = new int[cols + 1]; // Include an extra element for easier calculation\n int maxArea = 0;\n \n for (char[] row : matrix) {\n for (int i = 0; i < cols; i++) {\n heights[i] = (row[i] == \'1\') ? heights[i] + 1 : 0;\n }\n \n // Calculate max area using histogram method\n int n = heights.length; // Number of bars in the histogram\n \n for (int i = 0; i < n; i++) {\n for (int j = i, minHeight = Integer.MAX_VALUE; j < n; j++) {\n minHeight = Math.min(minHeight, heights[j]);\n int area = minHeight * (j - i + 1);\n maxArea = Math.max(maxArea, area);\n }\n }\n }\n \n return maxArea;\n }\n}\n\n```\n \n```C++ []\nclass Solution {\npublic:\n int maximalRectangle(vector<vector<char>>& matrix) {\n if (matrix.empty() || matrix[0].empty())\n return 0;\n \n int rows = matrix.size();\n int cols = matrix[0].size();\n vector<int> heights(cols + 1, 0); // Include an extra element for easier calculation\n int maxArea = 0;\n \n for (const auto& row : matrix) {\n for (int i = 0; i < cols; i++) {\n heights[i] = (row[i] == \'1\') ? heights[i] + 1 : 0;\n }\n \n // Calculate max area using histogram method\n int n = heights.size(); // Number of bars in the histogram\n \n for (int i = 0; i < n; i++) {\n for (int j = i, minHeight = INT_MAX; j < n; j++) {\n minHeight = min(minHeight, heights[j]);\n int area = minHeight * (j - i + 1);\n maxArea = max(maxArea, area);\n }\n }\n }\n \n return maxArea;\n }\n};\n```\n\n**Complexity**:\nThe naive approach examines all possible rectangles by iterating through each pair of bars in the histogram, resulting in a time complexity of O(n^3), where n is the number of bars. \n\n\n\n**Optimization**:\nTo optimize, identify and address inefficiencies in the brute-force method. This involves recognizing repetitive calculations, such as repeatedly finding the minimum height between pairs of bars. We can use techniques like dynamic programming (DP) or stack-based methods to streamline the process and reduce unnecessary recalculations, ultimately improving efficiency and scalability for larger datasets.\n\n### 2\uFE0F\u20E3Max Area Calculation (Using Stack-Based Approach)\uD83D\uDE0E:\n1. **Initialization**:\n - Initialize a stack `stack` to keep track of indices of bars in the histogram.\n - Initialize `max_area` to store the maximum rectangle area found.\n\n2. **Iterate Through Each Bar**:\n - Traverse each bar\'s height in the `height` array from left to right.\n\n3. **Stack Operations**:\n - For each bar at index `i`:\n - While the stack is not empty and the current bar\'s height (`height[i]`) is less than the height of the bar represented by the index on top of the stack (`height[stack[-1]]`):\n - Pop the top index `j` from the stack.\n - Calculate the area with the popped bar\'s height:\n - `h = height[j]`\n - `w = i - stack[-1] - 1` (if stack is not empty), otherwise `w = i`\n - `area = h * w`\n - Update `max_area` with the maximum of `max_area` and `area`.\n\n4. **Final Maximum Area**:\n - After processing all bars in the `height` array:\n - Check if the stack is not empty:\n - Pop each remaining index `j` from the stack and calculate the area similarly to step 3.\n\n5. **Return Result**:\n - `max_area` will hold the value of the largest rectangle that can be formed within the histogram.\n\n\n# Let\'s walkthrough\uD83D\uDEB6\uD83C\uDFFB\u200D\u2642\uFE0F the implementation process with an example for better understanding\uD83C\uDFAF:\nLet\'s walk through the code step by step with the input `matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]`.\n- Iteration 1:\n```\nCurrent Row Array: [\'1\', \'0\', \'1\', \'0\', \'0\']\nHeight Array: [1, 0, 1, 0, 0]\nCurrent Histogram:\n# # \nMax Area: 1\n```\n- Iteration 2:\n```\nCurrent Row Array: [\'1\', \'0\', \'1\', \'1\', \'1\']\nHeight Array: [2, 0, 2, 1, 1]\nCurrent Histogram:\n# # \n# ###\nMax Area: 3\n```\n- Iteration 3:\n```\nCurrent Row Array: [\'1\', \'1\', \'1\', \'1\', \'1\']\nHeight Array: [3, 1, 3, 2, 2]\nCurrent Histogram:\n# # \n# ###\n#####\nMax Area: 6\n```\n- Iteration 4:\n```\nCurrent Row Array: [\'1\', \'0\', \'0\', \'1\', \'0\']\nHeight Array: [4, 0, 0, 3, 0]\nCurrent Histogram:\n# \n# # \n# # \n# # \nMax Area: 6\n```\n\n# Code\uD83D\uDC68\uD83C\uDFFB\u200D\uD83D\uDCBB:\n```Python []\nclass Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n if not matrix:\n return 0\n \n rows, cols = len(matrix), len(matrix[0])\n heights = [0] * (cols + 1) # Include an extra element for easier calculation\n max_area = 0\n \n for row in matrix:\n for i in range(cols):\n heights[i] = heights[i] + 1 if row[i] == \'1\' else 0\n \n # Calculate max area using histogram method\n stack = []\n for i in range(len(heights)):\n while stack and heights[i] < heights[stack[-1]]:\n h = heights[stack.pop()]\n w = i if not stack else i - stack[-1] - 1\n max_area = max(max_area, h * w)\n stack.append(i)\n \n return max_area \n```\n```Java []\nclass Solution {\n public int maximalRectangle(char[][] matrix) {\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0)\n return 0;\n\n int rows = matrix.length;\n int cols = matrix[0].length;\n int[] heights = new int[cols + 1]; // Include an extra element for easier calculation\n int maxArea = 0;\n\n for (char[] row : matrix) {\n for (int i = 0; i < cols; i++) {\n heights[i] = (row[i] == \'1\') ? heights[i] + 1 : 0;\n }\n\n // Calculate max area using stack-based method\n Stack<Integer> stack = new Stack<>();\n for (int i = 0; i < heights.length; i++) {\n while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {\n int h = heights[stack.pop()];\n int w = stack.isEmpty() ? i : i - stack.peek() - 1;\n maxArea = Math.max(maxArea, h * w);\n }\n stack.push(i);\n }\n }\n\n return maxArea;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int maximalRectangle(vector<vector<char>>& matrix) {\n if (matrix.empty() || matrix[0].empty())\n return 0;\n\n int rows = matrix.size();\n int cols = matrix[0].size();\n vector<int> heights(cols + 1, 0); // Include an extra element for easier calculation\n int maxArea = 0;\n\n for (const auto& row : matrix) {\n for (int i = 0; i < cols; i++) {\n heights[i] = (row[i] == \'1\') ? heights[i] + 1 : 0;\n }\n\n // Calculate max area using stack-based method\n stack<int> stk;\n for (int i = 0; i < heights.size(); i++) {\n while (!stk.empty() && heights[i] < heights[stk.top()]) {\n int h = heights[stk.top()];\n stk.pop();\n int w = stk.empty() ? i : i - stk.top() - 1;\n maxArea = max(maxArea, h * w);\n }\n stk.push(i);\n }\n }\n\n return maxArea;\n }\n};\n\n```\n
| 164 | 2 |
['Array', 'Stack', 'Matrix', 'Monotonic Stack', 'C++', 'Java', 'Python3']
| 21 |
maximal-rectangle
|
Evolve from brute force to optimal
|
evolve-from-brute-force-to-optimal-by-yu-i8hi
|
This problem is similar to maximal square but much more difficult.\n1. brute force O(n^6), count each rectangle\n\n int maximalRectangle(vector<vector<char>>
|
yu6
|
NORMAL
|
2016-11-13T08:03:35.394000+00:00
|
2018-10-21T17:31:22.101476+00:00
| 8,018 | false |
This problem is similar to [maximal square](https://discuss.leetcode.com/topic/55063/evolve-from-brute-force-to-dp) but much more difficult.\n1. brute force O(n^6), count each rectangle\n```\n int maximalRectangle(vector<vector<char>>& matrix) {\n if(matrix.empty()) return 0;\n int r = matrix.size(), c = matrix[0].size(), area = 0;\n for(int i=0;i<r;i++)\n for(int j=0;j<c;j++) { //each start point (i,j)\n if(matrix[i][j]=='0') continue;\n for(int p=i;p<r;p++)\n for(int q=j;q<c;q++) { // each end point (p,q)\n if(matrix[p][q]=='0') continue;\n bool ones = 1;\n for(int x=i;x<=p;x++) { //check if the rectangle contains all 1s\n for(int y=j;y<=q;y++) \n if(matrix[x][y] == '0') {\n ones = 0;\n break;\n }\n if(!ones) break;\n }\n if(ones) area = max(area, (p-i+1)*(q-j+1));\n }\n }\n return area;\n }\n```\n2. O(n^4), whether a rectangle contains all 1s can be determined incrementally from the previous rectangle\n```\n int maximalRectangle(vector<vector<char>>& matrix) {\n if(matrix.empty()) return 0;\n int r = matrix.size(), c = matrix[0].size(), area = 0;\n for(int i=0;i<r;i++)\n for(int j=0;j<c;j++) {\n vector<vector<bool>> dp(r,vector<bool>(c));\n for(int p=i;p<r;p++)\n for(int q=j;q<c;q++) {\n dp[p][q] = matrix[p][q]=='1';\n if(p>i) dp[p][q] = dp[p][q] & dp[p-1][q];\n if(q>j) dp[p][q] = dp[p][q] & dp[p][q-1];\n if(dp[p][q]) area=max(area,(p-i+1)*(q-j+1));\n else break;\n }\n }\n return area;\n }\n```\n3. O(n^3), for a start/end point, we do not need to consider all end/start points, we only need to consider points that connect to the start/end point by all 1s. We use a 2d array to cache number of consecutive 1s to the left of each point. Then for a point, we can determine its maximal rectangles in linear time. [The idea is from @uniqueness ](https://discuss.leetcode.com/topic/1122/my-o-n-3-solution-for-your-reference).\n```\n int maximalRectangle(vector<vector<char>>& matrix) {\n int r = matrix.size();\n if (!r) return 0;\n int c = matrix[0].size(), area = 0;\n vector<vector<int>> ones(r,vector<int>(c));\n for(int i=0;i<r;i++) \n for(int j=0;j<c;j++) {\n if(matrix[i][j]=='0') continue;\n int w = ones[i][j] = (j?ones[i][j-1]:0) + 1;\n for(int k=i; k>=0; k--) {\n w = min(ones[k][j],w);\n area = max(area,w*(i-k+1));\n }\n }\n return area;\n }\n```\n4. O(n^2) dp. The optimal solution does not check a rectangle by start/end point. Given a point (i, j), it computes the left boundary, right boundary of the maximal rectangle with height(i,j) incrementally in constant time. [The idea is from @morrischen2008](https://discuss.leetcode.com/topic/6650/share-my-dp-solution).\n```\n int maximalRectangle(vector<vector<char>>& matrix) {\n int r = matrix.size();\n if (!r) return 0;\n int c = matrix[0].size(), area = 0;\n vector<int> left(c), right(c,c), height(c);\n for(int i=0;i<r;i++) { \n int cur = 0;\n for(int j=0;j<c;j++)\n if(matrix[i][j]=='0') {\n height[j] = left[j] = 0;\n cur = j+1; //left boundary of current row\n } else {\n left[j] = max(left[j],cur); //left boundary for height[j]\n height[j]++;\n }\n cur = c;\n for(int j=c-1;j>=0;j--) {\n if (matrix[i][j]=='0') cur = j;\n right[j] = matrix[i][j]=='0'? c:min(right[j],cur);\n area = max(height[j]*(right[j]-left[j]),area);\n }\n }\n return area;\n }\n```
| 101 | 0 |
[]
| 7 |
maximal-rectangle
|
Sharing my straightforward C++ solution with O(n^2) time with explanation
|
sharing-my-straightforward-c-solution-wi-2u0j
|
int maximalRectangle(vector<vector<char> > &matrix) {\n if(matrix.empty()){\n return 0;\n }\n int maxRec = 0;\n vector<in
|
zxyperfect
|
NORMAL
|
2014-12-07T22:19:40+00:00
|
2018-09-11T02:22:24.954097+00:00
| 25,055 | false |
int maximalRectangle(vector<vector<char> > &matrix) {\n if(matrix.empty()){\n return 0;\n }\n int maxRec = 0;\n vector<int> height(matrix[0].size(), 0);\n for(int i = 0; i < matrix.size(); i++){\n for(int j = 0; j < matrix[0].size(); j++){\n if(matrix[i][j] == '0'){\n height[j] = 0;\n }\n else{\n height[j]++;\n }\n }\n maxRec = max(maxRec, largestRectangleArea(height));\n }\n return maxRec;\n }\n \n int largestRectangleArea(vector<int> &height) {\n stack<int> s;\n height.push_back(0);\n int maxSize = 0;\n for(int i = 0; i < height.size(); i++){\n if(s.empty() || height[i] >= height[s.top()]){\n s.push(i);\n }\n else{\n int temp = height[s.top()];\n s.pop();\n maxSize = max(maxSize, temp * (s.empty() ? i : i - 1 - s.top()));\n i--;\n }\n }\n return maxSize;\n }\n\nIn order to solve this problem, I use the solution from "Largest Rectangle in Histogram". \n\nNow I assume you already know how to solve "Largest Rectangle in Histogram".\n\nWe can regard a matrix as many histograms. For example, given a matrix below:\n\n1 0 1 0\n\n0 1 0 1\n\n0 1 1 0\n\n1 0 1 0\n\n1 0 1 1\n\nFrom top to bottom, we can find these histograms:\n\nNumber 1: 1 0 1 0\n\nNumber 2: 0 1 0 1\n\nNumber 3: 0 2 1 0\n\nNumber 4: 1 0 2 0\n\nNumber 5: 2 0 3 1\n\nPass all of these histograms to the function which can solve "Largest Rectangle in Histogram". And then find the maximum one. \n\nFinally, we get the answer.
| 98 | 2 |
['C++']
| 11 |
maximal-rectangle
|
Easy C++ soln based on Largest Histogram
|
easy-c-soln-based-on-largest-histogram-b-wj1e
|
\nclass Solution {\npublic:\n \n int largestArea(vector<int>& histogram){\n int n=histogram.size(), area=0;\n stack<int> s;\n \n
|
ankurharitosh
|
NORMAL
|
2020-09-30T15:02:25.492042+00:00
|
2020-09-30T15:03:02.776952+00:00
| 10,717 | false |
```\nclass Solution {\npublic:\n \n int largestArea(vector<int>& histogram){\n int n=histogram.size(), area=0;\n stack<int> s;\n \n for(int i=0; i<n; i++){\n while(!s.empty() && histogram[s.top()]>=histogram[i]){\n int top = s.top();\n s.pop();\n \n int start;\n if(s.empty())\n start = -1;\n else\n start = s.top();\n \n \n int curr_area = histogram[top] * (i - start -1);\n area = max(area, curr_area);\n }\n s.push(i);\n }\n \n while(!s.empty()){\n int top = s.top();\n s.pop();\n\n int start;\n if(s.empty())\n start = -1;\n else\n start = s.top();\n \n int curr_area = histogram[top] * (n - start -1);\n area = max(area, curr_area);\n }\n \n return area;\n }\n \n int maximalRectangle(vector<vector<char>>& matrix) {\n int m=matrix.size();\n if(m==0) return 0;\n int n=matrix[0].size(), result=0;\n vector<int> histogram(n, 0);\n \n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(matrix[i][j]==\'1\')\n histogram[j]+=1;\n else\n histogram[j]=0;\n }\n \n result = max(result, largestArea(histogram));\n cout<<result<<" ";\n }\n return result;\n }\n};\n\n/*\n\n2 0 2 1 1 \n\n3 1 3 2 2 \n\n\nAlgorithm Outline:\nlargestArea()\n\n |\n | | |\n| | | | |\n\n1 2 3 1 2 -> 5\n0 1 2 3 4 -> index\n\n1. stack\n2. iterate, check when value is less that top\n3. While less than top, area = height of bar * distance from i (anchor)\n4. Add to stack\n5. Check while stack not empty\n6. Return max_area\n\nmain()\n1. Calculate histogra array for each row\n2. Check largest area in that row\n3. Return ans\n\n\nHorizontal - can check length\nVerticle - Keep height of each column top to bottum\n\ncalculate area for each histogram in each row \n\n1 0 1 0 0 -> 1\n1 0 1 1 1 -> 3\n1 1 1 1 1 -> 6\n1 0 1 1 1\n\n*/\n```\nI appreciate your upvote !!
| 81 | 2 |
['Stack', 'C', 'C++']
| 3 |
maximal-rectangle
|
DP Thinking Process
|
dp-thinking-process-by-gracemeng-2yje
|
\n> How can we identify a rectangle?\nThe point on the top-left corner and the point on te bottom-right corner.\n\nFor each possible top-left\n For each possib
|
gracemeng
|
NORMAL
|
2019-03-13T15:32:24.849163+00:00
|
2019-03-13T15:32:24.849193+00:00
| 7,543 | false |
\n> **How can we identify a rectangle?**\nThe point on the top-left corner and the point on te bottom-right corner.\n```\nFor each possible top-left\n For each possible bottom-right\n Check if matrix is made of 1s\n\t If valid, we calculate area and update maxArea\n```\n\n> **How can we check if matrix with top-left (i, j) and bottome-right(x, y) is made of 1s?**\n> In Brute Force, we check each cells in matrix, that takes O(n^2) time complexity\n> To optimize, we observe that, \n```\nwith (i, j) as top-left, rectangle with (x, y) as bottom-right is valid if \n matrix[x][y] is 1\n && rectangle with (x, y - 1) as bottom-right is valid\n && rectangle with (x - 1, y) as bottom-right is valid\n```\n> We build an array isValid to save states. That takes O(1) time complexity.\n****\n```\n public int maximalRectangle(char[][] matrix) {\n if (matrix.length == 0) return 0;\n \n int rows = matrix.length, cols = matrix[0].length, maxArea = 0;\n // For each point topleft\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n // Construt isValid\n boolean[][] isValid = new boolean[rows][cols];\n // For each point bottom right \n for (int x = i; x < rows; x++) {\n for (int y = j; y < cols; y++) {\n if (matrix[x][y] != \'1\') continue;\n // Check if valid matrix\n isValid[x][y] = true;\n if (x > i) isValid[x][y] = isValid[x][y] && isValid[x - 1][y];\n if (y > j) isValid[x][y] = isValid[x][y] && isValid[x][y - 1];\n // If valid, calculate area and update max\n if (isValid[x][y]) {\n int area = (x - i + 1) * (y - j + 1);\n maxArea = Math.max(maxArea, area);\n }\n }\n }\n }\n }\n return maxArea;\n }\n```\n**(\u4EBA \u2022\u0348\u1D17\u2022\u0348)** Thanks for voting!
| 53 | 6 |
['Dynamic Programming']
| 3 |
maximal-rectangle
|
[Python] O(mn) solution, explained
|
python-omn-solution-explained-by-dbabich-ojmy
|
There is dp O(n^2m^2) solution. We can do better, with O(nm*min(m,n)) complexity, if we use dynamic programming and keep two tables: h[i][j] is the largest L, s
|
dbabichev
|
NORMAL
|
2021-11-30T06:40:54.875536+00:00
|
2021-11-30T06:40:54.875563+00:00
| 5,002 | false |
There is dp `O(n^2m^2)` solution. We can do better, with `O(nm*min(m,n))` complexity, if we use dynamic programming and keep two tables: `h[i][j]` is the largest `L`, such that all elements in `A[i:i+L-1][j] = 1`, and similar `w[i][j]`. Then we go through our original table `A` and we can calculate for `A[i][j]` the largest subarray that has `A[i][j]` as its bottom-left corner, it can be done with `O(n)` iterations.\n\nFinally, there is very smart way with complexity `O(nm)`, using problem **0084**. Indeed, for each row we can evaluate our skyline heights, given previous row in `O(m)` and do it `n` times. Additional complexity is `O(m)`, because actually we need to keep only one row at at time.\n\n#### Complexity\nIt is `O(nm)` for time and `O(m)` for space.\n\n#### Code\n```python\nclass Solution:\n def maximalRectangle(self, matrix):\n def hist(heights):\n stack, ans = [], 0\n for i, h in enumerate(heights + [0]):\n while stack and heights[stack[-1]] >= h:\n H = heights[stack.pop()]\n W = i if not stack else i-stack[-1]-1\n ans = max(ans, H*W)\n stack.append(i)\n return ans\n \n if not matrix or not matrix[0]: return 0\n m, n, ans = len(matrix[0]), len(matrix), 0\n row = [0]*m\n for i in range(n):\n for j in range(m):\n row[j] = 0 if matrix[i][j] == "0" else row[j] + 1\n ans = max(ans, hist(row))\n \n return ans\n```\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!**\n
| 52 | 2 |
['Monotonic Stack']
| 2 |
maximal-rectangle
|
[Python] Based on Maximum Rectangle in Histogram - Clean & Concise
|
python-based-on-maximum-rectangle-in-his-m882
|
Idea\n- Sub problem of this problem is: 84. Largest Rectangle in Histogram\n- So, instead of solving sub-matrix problems, we can change to solve by sub-array pr
|
hiepit
|
NORMAL
|
2021-06-06T14:52:20.265547+00:00
|
2021-07-03T19:18:52.533694+00:00
| 2,671 | false |
**Idea**\n- Sub problem of this problem is: [84. Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)\n- So, instead of solving sub-matrix problems, we can change to solve by sub-array problems.\n\n```python\nclass Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n if len(matrix) == 0: return 0\n m, n = len(matrix), len(matrix[0])\n dp = [0] * n\n maxArea = 0\n for r in range(m):\n for c in range(n):\n if matrix[r][c] == "1":\n dp[c] += 1\n else:\n dp[c] = 0\n maxArea = max(maxArea, self.maxRectangleInHistogram(dp))\n return maxArea\n\n def maxRectangleInHistogram(self, heights): # O(N)\n n = len(heights)\n st = [-1]\n maxArea = 0\n for i in range(n):\n while st[-1] != -1 and heights[st[-1]] >= heights[i]:\n currentHeight = heights[st.pop()]\n currentWidth = i - st[-1] - 1\n maxArea = max(maxArea, currentWidth * currentHeight)\n st.append(i)\n while st[-1] != -1:\n currentHeight = heights[st.pop()]\n currentWidth = n - st[-1] - 1\n maxArea = max(maxArea, currentWidth * currentHeight)\n return maxArea\n```\n\nComplexity:\n- Time: `O(R * C)`\n- Space: `O(C)`
| 48 | 0 |
[]
| 2 |
maximal-rectangle
|
Java | Detailed Explanation | Easy Approach | O(row*col)
|
java-detailed-explanation-easy-approach-jilf8
|
\nIntuition :\n1) Pick one row\n2) Do summation of each index till that row\n\t\ti) if any index value is 0 then put 0 else previous summation + 1 \n3) Pass thi
|
javed_beingzero
|
NORMAL
|
2021-11-30T04:30:08.637473+00:00
|
2021-12-01T02:38:09.144969+00:00
| 10,410 | false |
```\nIntuition :\n1) Pick one row\n2) Do summation of each index till that row\n\t\ti) if any index value is 0 then put 0 else previous summation + 1 \n3) Pass this array to get max area (84. Largest Rectangle in Historgram)\n4) Update max area\n\n84. Largest Rectangle in Histogram\nIntuition :\n1) Max area will always have atleast one full bar height on any index\n2) Find largest rectangle including each bar one by one.\n\ta) For each bar, We have to find it\'s left limit & right limit (to know the maximum width)\n\tb) Find it\'s left limit (where we find any index\'s value is smaller than current index in left side array of curr index)\n\tc) Find it\'s right limit (where we find any index\'s value is smaller than current index in right side array of curr index\n3) Take the maximum of all the max area found by each bar.\n4) calculate area\n\t\twidth * height\nwhere width = right limit - left limit + 1\nheight = curr index\'s value\n5) Update max area & return it\n```\n```\nclass Solution {\n public int maximalRectangle(char[][] matrix) {\n if(matrix.length == 0) return 0;\n int maxArea = 0;\n int row = matrix.length;\n int col = matrix[0].length;\n int[] dp = new int[col];\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n dp[j] = matrix[i][j] == \'1\' ? dp[j]+1 : 0;\n }\n //treating dp[j] as histogram, solving max area problem there and updating the max area\n maxArea = Math.max(maxArea, findMaxAreaInHistogram(dp));\n }\n return maxArea;\n }\n\t//84. Largest Rectangle in Histogram code\n public int findMaxAreaInHistogram(int[] dp){\n int len = dp.length;\n int maxArea = 0;\n int[] left = new int[len];\n int[] right = new int[len];\n Stack<Integer> stack = new Stack<>();\n //traversing left to right, finding left limit\n for(int i=0;i<len;i++){\n if(stack.isEmpty()){\n stack.push(i);\n left[i] = 0;\n }else{\n while(!stack.isEmpty() && dp[stack.peek()] >= dp[i])\n stack.pop();\n left[i] = stack.isEmpty() ? 0 : stack.peek()+1;\n stack.push(i);\n }\n }\n //doing empty to stack\n while(!stack.isEmpty())\n stack.pop();\n \n //traversing right to left, find right limit\n for(int i=len-1;i>=0;i--){\n if(stack.isEmpty()){\n stack.push(len-1);\n right[i] = len - 1;\n }else{\n while(!stack.isEmpty() && dp[stack.peek()] >= dp[i])\n stack.pop();\n right[i] = stack.isEmpty() ? len-1 : stack.peek()-1;\n stack.push(i);\n }\n }\n //traversing the array , caculating area\n int[] area = new int[len];\n for(int i=0;i<len;i++){\n area[i] = (right[i] - left[i] + 1) * dp[i];\n maxArea = Math.max(maxArea, area[i]);\n }\n return maxArea;\n }\n}\n```
| 47 | 2 |
['Stack', 'Java']
| 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.