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
subtree-of-another-tree
Java| 5ms | 97.22% faster
java-5ms-9722-faster-by-aish9-1r5i
\nclass Solution {\n public boolean isSubtree(TreeNode s, TreeNode t) {\n if(t==null)\n return true;\n if(s==null)\n retu
aish9
NORMAL
2021-04-20T21:31:59.795813+00:00
2021-04-20T21:31:59.795843+00:00
1,307
false
```\nclass Solution {\n public boolean isSubtree(TreeNode s, TreeNode t) {\n if(t==null)\n return true;\n if(s==null)\n return false;\n if(isIdentical(s,t))\n return true;\n return isSubtree(s.left,t) ||isSubtree(s.right,t);\n }\n public boolean isIdentical(TreeNode s, TreeNode t) {\n if(s==null&&t==null)\n return true;\n if(s==null||t==null)\n return false;\n return s.val==t.val&&(isIdentical(s.left,t.left))&&(isIdentical(s.right,t.right));\n }\n}\n```
5
0
['Recursion', 'Java']
2
subtree-of-another-tree
O(N+M) | KMP | Explanation
onm-kmp-explanation-by-saurabhyadavz-wp89
Steps:\n Convert tree S and T into its serialize strings S1 and T1 respectively.\n Now the problem is reduced to finding the pattern(T1) in the given text(S1).\
saurabhyadavz
NORMAL
2021-03-04T19:56:26.424427+00:00
2021-03-04T19:56:26.424480+00:00
303
false
**Steps**:\n* Convert tree S and T into its **serialize** strings **S1** and **T1** respectively.\n* Now the problem is reduced to finding the pattern(T1) in the given text(S1).\n* Now we can use **KMP Algorithm** to check whether pattern(T1) is present in text(S1) or not.\n\n\n```\n\nclass Solution {\npublic:\n void preorder(TreeNode *root,string &pre)\n {\n if(root==NULL)\n {\n pre+=\'#\';\n return;\n }\n pre+=\',\'+to_string(root->val);\n preorder(root->left,pre);\n preorder(root->right,pre);\n }\n\t// Pre-processing the Longest Prefix Suffix array\n void preprecessLPS(string t1,int lps[])\n {\n \n lps[0]=0;\n int len=0;\n int i=1;\n while(i<t1.size())\n {\n if(t1[i]==t1[len])\n {\n \n lps[i++]=++len;\n \n }\n else{\n if(len!=0)\n {\n len=lps[len-1];\n \n }\n else{\n lps[i]=0;\n i++;\n }\n }\n }\n \n }\n bool isSubtree(TreeNode* s, TreeNode* t) {\n\t\n\t /* Converting S and T to its serialize form*/\n string s1;\n preorder(s,s1);\n string t1;\n preorder(t,t1);\n \n int lps[t1.size()];\n preprecessLPS(t1,lps);\n int i=0,j=0;\n \n\t\t// Pattern Matching\n while(i<s1.size())\n {\n if(s1[i]==t1[j])\n {\n i++;\n j++;\n }\n if(j==t1.size())\n {\n return true;\n \n }\n else if(i<s1.size()&&s1[i]!=t1[j])\n {\n if(j!=0)\n {\n j=lps[j-1];\n }\n else{\n i++;\n }\n }\n }\n return false;\n \n \n \n }\n};\n```\n
5
0
['C']
1
subtree-of-another-tree
Python, DFS traversal
python-dfs-traversal-by-blue_sky5-1is5
\nclass Solution:\n def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:\n def dfs(node):\n def same(n1, n2):\n if not n1
blue_sky5
NORMAL
2020-11-12T02:31:11.158846+00:00
2020-11-12T02:31:11.158887+00:00
1,683
false
```\nclass Solution:\n def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:\n def dfs(node):\n def same(n1, n2):\n if not n1 and not n2:\n return True\n if not n1 or not n2 or n1.val != n2.val:\n return False\n return same(n1.left, n2.left) and same(n1.right, n2.right)\n \n if not node:\n return False\n \n if node.val == t.val and same(node, t):\n return True\n \n return dfs(node.left) or dfs(node.right)\n \n return dfs(s)\n```
5
0
['Python', 'Python3']
0
subtree-of-another-tree
Java, Solve with BFS
java-solve-with-bfs-by-ikay-xws4
Time: O(N*M)\n\njava\nclass Solution {\n public boolean isSubtree(TreeNode s, TreeNode t) {\n Queue<TreeNode> que = new LinkedList<TreeNode>();\n
ikay
NORMAL
2020-07-24T13:13:56.365471+00:00
2020-07-24T13:17:14.722884+00:00
644
false
- Time: O(N*M)\n\n```java\nclass Solution {\n public boolean isSubtree(TreeNode s, TreeNode t) {\n Queue<TreeNode> que = new LinkedList<TreeNode>();\n que.add(s);\n while(!que.isEmpty()) { // bfs\n TreeNode node = que.poll();\n if (this.areSameTrees(node, t)) return true;\n if (node.left != null) que.add(node.left);\n if (node.right != null) que.add(node.right);\n }\n return false;\n }\n \n private boolean areSameTrees(TreeNode s, TreeNode t) {\n if (s == null && t == null) return true;\n if ((s == null && t != null) || (s != null && t == null)) return false;\n if (s.val != t.val) return false;\n \n return this.areSameTrees(s.left, t.left) && this.areSameTrees(s.right, t.right); \n } \n}\n```
5
0
['Breadth-First Search', 'Java']
0
subtree-of-another-tree
Swift Solution, tree traversal
swift-solution-tree-traversal-by-alpteki-xju3
\nclass Solution {\n func isSubtree(_ s: TreeNode?, _ t: TreeNode?) -> Bool {\n if s == nil { return false}\n return isSame(s, t) ||\xA0isSubtr
alptekin35
NORMAL
2020-01-31T01:40:58.784532+00:00
2020-01-31T01:40:58.784563+00:00
450
false
```\nclass Solution {\n func isSubtree(_ s: TreeNode?, _ t: TreeNode?) -> Bool {\n if s == nil { return false}\n return isSame(s, t) ||\xA0isSubtree(s?.left, t) || isSubtree(s?.right, t)\n }\n \n func isSame(_ s: TreeNode?, _ t: TreeNode?) -> Bool {\n if s == nil &&\xA0t == nil { return true}\n if s == nil ||\xA0t == nil { return false}\n return ((s?.val == t?.val) && isSame(s?.left, t?.left) && isSame(s?.right, t?.right))\n }\n}\n```
5
0
['Swift']
0
subtree-of-another-tree
99.74 % faster c++ solution dfs, optimized, 4 approaches
9974-faster-c-solution-dfs-optimized-4-a-kjds
--------\n(a). 24 ms, 21MB\n\n--------\nRuntime: 24 ms, faster than 99.74% of C++ online submissions for Subtree of Another Tree.\nMemory Usage: 21 MB, less tha
alokgupta
NORMAL
2019-12-23T11:14:09.725322+00:00
2019-12-23T11:14:09.725361+00:00
1,468
false
--------\n**(a).** 24 ms, 21MB\n\n--------\n**Runtime:** 24 ms, faster than **99.74%** of C++ online submissions for Subtree of Another Tree.\n**Memory Usage:** 21 MB, less than **75.00%** of C++ online submissions for Subtree of Another Tree.\n\nclass Solution { **// dfs**\npublic:\n void subtreeComparator(TreeNode* s, TreeNode* t,bool &areIdentical){\n if(!s && !t || !areIdentical) return;\n if(!s || !t || s->val!=t->val) {areIdentical=false; return;}\n \n if(s->val == t->val && areIdentical){\n subtreeComparator(s->left,t->left,areIdentical);\n subtreeComparator(s->right,t->right,areIdentical);\n }\n }\n bool isSubtree(TreeNode* s, TreeNode* t){ \n if(s->val == t->val){\n bool areIdentical(true);\n subtreeComparator(s,t,areIdentical);\n if(areIdentical) return true;\n }\n return (s->left && isSubtree(s->left,t)) || (s->right && isSubtree(s->right,t));\n }\n};\n\n--------\n**(b).** 32 ms, 21.4 MB\nTwo trees are identical when they are recursively identical. Brute force solution would be recursively compare each node in s with t to check for identical. Better solution is to only compare nodes in s with the same max depth as t. First get max depth of t, then recursively check each node in s, if depth equals, push to a vector. Then compare each node in the vector with t.\n\n------\nclass Solution { **// using depth of the second tree**\nprivate:\n vector<TreeNode*> nodes; \npublic:\n bool isSubtree(TreeNode* s, TreeNode* t) {\n if(!s && !t) return true;\n if(!s || !t) return false;\n \n int depthOfT(getDepth(t,-1));\n getDepth(s,depthOfT); // adds all nodes at depth depthOfT from s to nodes\n \n for(TreeNode* node : nodes)\n if(isIdentical(node,t))\n return true;\n \n return false;\n }\n \n int getDepth(TreeNode* r, int d){\n if(!r) return -1;\n int depth(max(getDepth(r->left,d), getDepth(r->right,d))+1);\n \n if(depth==d) nodes.push_back(r);\n \n return depth;\n }\n \n bool isIdentical(TreeNode* t1, TreeNode* t2){\n if(!t1 && !t2) return true;\n if(!t1 || !t2 || t1->val!=t2->val) return false;\n return isIdentical(t1->left,t2->left) && isIdentical(t1->right,t2->right);\n }\n};\n\n------\n\n**(c).** 28 ms, 20.9 MB\n\n--------\nclass Solution {\npublic:\n bool isSubtree(TreeNode* s, TreeNode* t) {\n if(!s && !t) return true;\n if(!s || !t) return false;\n \n return isSameTree(s,t) || isSubtree(s->left,t) || isSubtree(s->right,t);\n }\n \n bool isSameTree(TreeNode* t1, TreeNode* t2){\n if(!t1 && !t2) return true;\n if(!t1 || !t2 || t1->val!=t2->val) return false;\n \n return isSameTree(t1->left,t2->left) && isSameTree(t1->right,t2->right);\n }\n};\n\n------\n**(d).** 32 ms, 20.9 MB\n\n------\nclass Solution { **// tc: O(mn), sc: O(n)*\npublic:\n bool isSubtree(TreeNode* s, TreeNode* t) {\n return !t || s && (same(s,t) || isSubtree(s->left,t) || isSubtree(s->right,t));\n }\n bool same(TreeNode* t1, TreeNode* t2){\n return (!t1 || !t2)? (t1==t2):(t1->val==t2->val)&&same(t1->left,t2->left)&&same(t1->right,t2->right);\n }\n};\n\n------\n\n **// DFS**\n \n**(e).** 36 ms, 21 MB\n\nTime complexity : O(m*n). In worst case(skewed tree) traverse function takes O(m*n) time.\nSpace complexity : O(n). The depth of the recursion tree can go upto nn. nn refers to the number of nodes in ss.\n\n--------\nclass Solution { **// tc: O(m*n)- worst case(skewed tree), sc: O(n)- n refers to the number of nodes in s** **// dfs**\npublic:\n bool isSubtree(TreeNode* s, TreeNode* t) {\n return s && (equals(s,t) || isSubtree(s->left,t) || isSubtree(s->right,t));\n }\n bool equals(TreeNode* x, TreeNode* y){\n if(!x && !y) return true;\n if(!x || !y) return false;\n return x->val==y->val && equals(x->left,y->left) && equals(x->right,y->right);\n }\n};\n\n------\n
5
1
['Depth-First Search', 'Breadth-First Search', 'Recursion', 'C', 'C++']
0
subtree-of-another-tree
O(n + m) time complexity. 1ms runtime
on-m-time-complexity-1ms-runtime-by-zhou-udit
n = size(s), m = size(t). There could be at most n/m subtrees that have size equal to m. Compare each candidate with t which takes m comparisons. So complexit
zhouningman
NORMAL
2019-04-13T14:54:39.031830+00:00
2019-04-13T14:54:39.031862+00:00
427
false
n = size(s), m = size(t). There could be at most n/m subtrees that have size equal to m. Compare each candidate with t which takes m comparisons. So complexit is O(n/m * m) ~= O(n). \n```\n public boolean isSubtree(TreeNode s, TreeNode t) {\n if(s == null && t == null) return true;\n else if( s== null || t == null) return false;\n\n int m = collect(t, -1, null);//size of t\n List<TreeNode> candidates = new ArrayList<>();\n collect(s, m, candidates);\n for(TreeNode candidate : candidates) {\n if(compare(candidate, t)) return true;\n }\n return false;\n }\n\n private int collect(TreeNode node, int m, List<TreeNode> candidates) {\n if(node == null) return 0;\n int size = 1 + collect(node.left, m, candidates) + collect(node.right, m, candidates);\n if(size == m) {//collect subtree with size of t\n candidates.add(node);\n }\n return size;\n }\n\n private boolean compare(TreeNode s, TreeNode t) {\n if(s == null && t == null ) return true;\n else if(s == null || t == null) return false;\n return s.val == t.val && compare(s.left, t.left) && compare(s.right, t.right);\n }\n```
5
0
[]
3
subtree-of-another-tree
python clear solution
python-clear-solution-by-rockeroad-thnr
\ndef isSubtree(self, s, t):\n """\n :type s: TreeNode\n :type t: TreeNode\n :rtype: bool\n """\n def isEqual(s1,s2):\
rockeroad
NORMAL
2018-05-02T03:11:20.012114+00:00
2018-05-02T03:11:20.012114+00:00
874
false
```\ndef isSubtree(self, s, t):\n """\n :type s: TreeNode\n :type t: TreeNode\n :rtype: bool\n """\n def isEqual(s1,s2):\n if s1 == None or s2 == None:\n return s1==s2\n if s1.val != s2.val:\n return False\n return isEqual(s1.left,s2.left) and isEqual(s1.right,s2.right)\n \n queue = []\n queue.append(s)\n while queue:\n node = queue.pop(0)\n if isEqual(node, t):\n return True\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return False\n```
5
1
[]
0
subtree-of-another-tree
🚀 **Beats 100% | O(N) Tree Hashing 🌲🔢 | Efficient Subtree Check** 🎯
beats-100-on-tree-hashing-efficient-subt-ngac
IntuitionThe problem requires checking whether subRoot is a subtree of root. A brute-force approach would compare each subtree of root with subRoot, leading to
Michael_Magdy
NORMAL
2025-03-30T23:40:04.123910+00:00
2025-03-31T12:09:15.647463+00:00
499
false
# **Intuition** The problem requires checking whether `subRoot` is a subtree of `root`. A brute-force approach would compare each subtree of `root` with `subRoot`, leading to **O(N * M)** complexity. Instead, we use **tree hashing** to uniquely encode subtrees and check for matches in **O(N) time**. Tree hashing is similar to **rolling hash for strings**, where we assign a unique integer value to each subtree based on its structure and node values. This allows efficient comparison using just **one integer value per subtree** instead of performing deep tree comparisons. --- # **Approach** 1. **Compute a unique hash for `subRoot`** - Use a recursive function (`HashTree`) that computes a hash for each subtree using a polynomial hash formula. - The hash incorporates: - **Left subtree hash** (multiplied by 31) - **Current node value** (shifted by `+10001` to avoid negative and zero values, multiplied by 29) - Without this shift, a subtree with an extra 0 child could produce the same hash as another valid subtree, leading to false positives in subtree checks. - **Right subtree hash** (multiplied by 37) 2. **Traverse `root` and check if any subtree has the same hash** - Recursively compute hashes for `root` and compare them with `subRoot`’s hash. - If a match is found, set `flag = true`. 3. **Return the result** - If `flag` is `true`, `subRoot` exists as a subtree of `root`. ### **⚠️ Handling Hash Collisions** This approach **could fail** in certain edge cases due to hash collisions. For example, the following subtrees would produce the same hash: ```plaintext [1, 37, 0] and [1, 0, 31] ``` Collisions occur when different subtrees generate identical hash values. While rare, they can lead to incorrect results. To mitigate this: - **Use multiple hash functions** (double hashing) to verify matches more reliably. *(The test cases didn't not include a conflicting case with the primes i chose, which is why it passed without this.)* - **Use a larger prime modulus** (e.g., `10^9+7`) to better distribute hash values and reduce collisions. # **Complexity** - **Time complexity:** - **O(N)** → Each node in `root` is visited once, computing its hash in constant time. - **O(M)** → We compute the hash of `subRoot` once. - **Total:** **O(N + M)**, which is much faster than **O(N * M)** brute force. - **Space complexity:** - **O(H)** → Recursive stack space, where `H` is the height of the tree (worst-case O(N) for skewed trees, O(log N) for balanced ones). - **O(1)** → We store only one hash instead of a hash table. --- # **Code** ```cpp /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: long long mod = 1000000007; long long hash; bool flag = false; public: long long HashTree(TreeNode* node) { if (!node) return 0; long long leftHash = HashTree(node->left); long long rightHash = HashTree(node->right); long long x = (leftHash * 31 + (node->val+10001) * 29 + rightHash * 37) % mod; return x; } long long HashTreeAndCheck(TreeNode* node) { if (!node) return 0; long long leftHash = HashTreeAndCheck(node->left); long long rightHash = HashTreeAndCheck(node->right); long long x = (leftHash * 31 + (node->val+10001) * 29 + rightHash * 37) % mod; if (x == hash) flag = true; return x; } bool isSubtree(TreeNode* root, TreeNode* subRoot) { hash = HashTree(subRoot); HashTreeAndCheck(root); return flag; } }; ```
4
0
['C++']
2
subtree-of-another-tree
Simple Recursion ✅✅- Beats 100%
simple-recursion-beats-100-by-sajal0701-d3z2
Intuition\n\nWe simply have to explore all the subtrees whose root have the same value as the value of the root of the given subtree.\n\nWe can just traverse ov
Sajal0701
NORMAL
2024-11-22T19:38:01.000658+00:00
2024-11-22T19:38:01.000693+00:00
1,109
false
# Intuition\n\nWe simply have to explore all the subtrees whose root have the same value as the value of the root of the given subtree.\n\nWe can just traverse over each such subtree checking value of each child and if it differs we will return false , and if any of the subtree is same we will return true.\n\n# Approach\n\nNow declare a queue and push all the nodes whose value is same as the value of given subTree.\n\nTraverse for each value in the queue, take the first node and traverse over this node and given subTree checking if the value of each node and child is same or not, and if we found such subtree simply return true.\n\nAt the end , when we have explored each subtree and still found no match , return false.\n\n\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```cpp []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n\n void preorder(TreeNode*root , queue<TreeNode*>&q , int val){\n if(!root) return;\n if(root ->val == val) q.push(root);\n preorder(root->left,q,val);\n preorder(root->right,q,val);\n }\n\n bool solve(TreeNode* root1 , TreeNode* root2){\n if(!root1 && !root2) return true;\n if(!root1) return false;\n if(!root2) return false;\n\n if(root1->val != root2->val) return false;\n return solve(root1->left, root2->left) && solve(root1->right, root2->right);\n }\n bool isSubtree(TreeNode* root, TreeNode* subRoot) {\n if(!subRoot) return true;\n int val = subRoot->val;\n queue<TreeNode*>q;\n TreeNode* temp = root;\n preorder(temp, q, val);\n\n while(!q.empty()){\n TreeNode* first = q.front();\n q.pop();\n TreeNode* second = subRoot;\n if(solve(first, second)) return true;\n }\n return false;\n }\n};\n```
4
0
['C++']
0
subtree-of-another-tree
SIMPLE ITERATIVE C++ COMMENTED SOLUTION
simple-iterative-c-commented-solution-by-6h5o
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
Jeffrin2005
NORMAL
2024-09-14T03:31:54.681004+00:00
2024-09-14T03:31:54.681030+00:00
542
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 []\n#include <bits/stdc++.h>\n#define ll long long\n#define nl \'\\n\'\nclass Solution {\npublic:\n bool isSubtree(TreeNode* root, TreeNode* subRoot) {\n queue<TreeNode*> queue;\n queue.push(root);\n // BFS to find a node that matches the root of subRoot\n while (!queue.empty()){\n TreeNode* currentNode = queue.front();\n queue.pop();\n if(currentNode != NULL ){\n // Check if the current node\'s value matches subRoot\'s root value\n if(currentNode->val == subRoot->val){\n if(isSameTree(currentNode, subRoot)) {\n return true;\n }\n }\n queue.push(currentNode->left);\n queue.push(currentNode->right);\n }\n }\n return false;\n }\nprivate:\n bool isSameTree(TreeNode* s, TreeNode* t){\n stack<TreeNode*> stackS, stackT;\n stackS.push(s); // Push the root of the first tree onto stackS\n stackT.push(t); // Push the root of the second tree onto stackT\n while (!stackS.empty() && !stackT.empty()) {\n TreeNode* nodeS = stackS.top();\n TreeNode* nodeT = stackT.top();\n stackS.pop();\n stackT.pop();\n\n if (nodeS == NULL && nodeT == NULL) continue;\n // If one of the nodes is NULL, trees are not identical\n if (nodeS == NULL || nodeT == NULL ) return false;\n // If the values of the nodes do not match, trees are not identical\n if (nodeS->val != nodeT->val) return false;\n stackS.push(nodeS->left);\n stackS.push(nodeS->right);\n stackT.push(nodeT->left);\n stackT.push(nodeT->right);\n }\n // If both stacks are empty, trees are identical\n return stackS.empty() && stackT.empty();\n }\n};\n```
4
0
['C++']
0
subtree-of-another-tree
🌳47. Recursive [ DFS ] || Classic Solution !! || Short & Sweet Code ! || C++ Code Reference !
47-recursive-dfs-classic-solution-short-je2gu
Intuition\n- Traverse Main Tree , Whenever It\'s Node value Equals SubRoot\'s Value Check if They are Identical TreesisSame\n\n## Similar Problem \n- 100. Same
Amanzm00
NORMAL
2024-07-04T18:09:54.494162+00:00
2024-07-04T18:09:54.494186+00:00
433
false
# Intuition\n- Traverse Main Tree , Whenever It\'s Node value Equals SubRoot\'s Value Check if They are Identical Trees`isSame`\n\n## Similar Problem \n- [100. Same Tree](https://leetcode.com/problems/same-tree/description/)\n# Approach\n\n![WhatsApp Image 2024-07-04 at 23.33.49_3284fd11.jpg](https://assets.leetcode.com/users/images/81ee9005-1b45-4a58-82d6-5fb59627b7db_1720116351.1870458.jpeg)\n\n\n# Code\n```\n\nclass Solution {\n\n bool Ans=0;\n\n bool isSame(TreeNode* a, TreeNode* b)\n {\n if(!a && !b) return 1;\n if(!a || !b) return 0;\n return (a->val==b->val && isSame(a->left,b->left) && isSame(a->right,b->right));\n }\n \n void Traverse(TreeNode* a,TreeNode* subRoot)\n {\n if(!a) return ;\n\n if(a->val==subRoot->val && isSame(a,subRoot)) Ans= true;\n\n Traverse(a->left,subRoot);\n Traverse(a->right,subRoot);\n }\n\npublic:\n\n bool isSubtree(TreeNode* Root, TreeNode* subRoot ) {\n Traverse(Root,subRoot);\n return Ans;\n }\n};\n```\n\n---\n# *Guy\'s Upvote Pleasee !!* \n![up-arrow_68804.png](https://assets.leetcode.com/users/images/05f74320-5e1a-43a6-b5cd-6395092d56c8_1719302919.2666397.png)\n\n# ***(\u02E3\u203F\u02E3 \u035C)***\n
4
0
['Tree', 'Depth-First Search', 'Binary Tree', 'Hash Function', 'C++']
1
subtree-of-another-tree
C++ Simple Recursive Solution using Preorder
c-simple-recursive-solution-using-preord-od0g
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can compare all subtrees of given root with subRoot and check if we find a valid sub
aman2oo4
NORMAL
2023-08-19T12:10:35.964807+00:00
2023-08-19T12:17:33.598575+00:00
1,357
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can compare all subtrees of given root with subRoot and check if we find a valid subtree\n\nNote: We can prune our recursion slightly as explained in the comments below\n\n# Complexity\n- Time complexity: O(N^2) in worst case\n- We are making call to areSame() in each recursive call (N calls in worst case where N is number of nodes)\n- The areSame() function itself takes roughly N time to check the two trees\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n bool areSame(TreeNode* root, TreeNode* subRoot){\n if(!root && !subRoot) return true;\n if(!root || !subRoot) return false;\n\n return (root->val == subRoot->val && areSame(root->left, subRoot->left) && areSame(root->right, subRoot->right));\n }\n\n void traverse(TreeNode* root, TreeNode* subRoot, bool &ans){\n if(ans) return; //stop recursion if we have already found subtree\n if(root->val == subRoot->val && areSame(root, subRoot)){\n //instead of calling areSame() every time check if the root values are same\n ans = true;\n return;\n }\n\n if(root->left) traverse(root->left, subRoot, ans);\n if(root->right) traverse(root->right, subRoot, ans);\n }\n bool isSubtree(TreeNode* root, TreeNode* subRoot) {\n bool ans = false;\n traverse(root, subRoot, ans);\n return ans;\n }\n};\n```
4
0
['Tree', 'Recursion', 'Binary Tree', 'C++']
1
subtree-of-another-tree
Java easy solution, 0ms, Beats100%
java-easy-solution-0ms-beats100-by-007ha-cl1p
Intuition\n Describe your first thoughts on how to solve this problem. \nHere i have used concept of recursion and Binary tree\n\n# Approach\n Describe your app
007Harsh-
NORMAL
2023-03-27T19:15:36.606736+00:00
2023-03-27T19:15:36.606770+00:00
1,456
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere i have used concept of recursion and Binary tree\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- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isSubtree(TreeNode root, TreeNode subRoot) {\n if(root==null){\n return false;\n }\n if(root.val==subRoot.val){\n if(isIdentical(root,subRoot)){\n return true;\n }\n }\n return isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);\n }\n public boolean isIdentical(TreeNode node,TreeNode subRoot){\n if(node==null&&subRoot==null){\n return true;\n }\n else if(node==null||subRoot==null||node.val!=subRoot.val){\n return false;\n }\n if(!isIdentical(node.left,subRoot.left)){\n return false;\n }\n if(!isIdentical(node.right,subRoot.right)){\n return false;\n }\n return true;\n }\n}\n```
4
0
['Java']
1
subtree-of-another-tree
✅✅Easy C++ Solution || Simple to Understand
easy-c-solution-simple-to-understand-by-04wqy
\tclass Solution {\n\tpublic:\n\n\t\tbool isSame(TreeNode p, TreeNode q){\n\n\t\t\tif(p == NULL || q == NULL){\n\t\t\t\treturn (p == q);\n\t\t\t} \n\t\t\tret
debav2
NORMAL
2022-08-24T19:21:04.133648+00:00
2022-08-24T19:21:04.133689+00:00
1,001
false
\tclass Solution {\n\tpublic:\n\n\t\tbool isSame(TreeNode* p, TreeNode* q){\n\n\t\t\tif(p == NULL || q == NULL){\n\t\t\t\treturn (p == q);\n\t\t\t} \n\t\t\treturn (p->val == q->val) && isSame(p->left, q->left) && isSame(p->right, q->right);\n\t\t}\n\n\n\t\tbool isSubtree(TreeNode* root, TreeNode* subRoot) {\n\n\t\t\tif(root == NULL){\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif(subRoot == NULL){ \n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif(isSame(root, subRoot)){\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);\n\t\t}\n\t};\nI hope that you\'ve found the solution useful.\nIn that case, please do upvote. Happy Coding :)
4
0
['Tree', 'Depth-First Search', 'Recursion', 'C', 'Binary Tree', 'C++']
1
subtree-of-another-tree
Convert trees to strings and check if substring
convert-trees-to-strings-and-check-if-su-gcbo
1) Convert both trees into string representation\n2) Check if s2 is a substring of s1\n3) The square brackets [12] around the numbers is to ensure that it passe
kdaahri
NORMAL
2022-08-07T03:35:55.481401+00:00
2022-08-14T01:05:31.707529+00:00
325
false
1) Convert both trees into string representation\n2) Check if s2 is a substring of s1\n3) The square brackets [12] around the numbers is to ensure that it passes test cases like the below\n```\nThis would output true when checking if s2 is in s1 even though it should be false.\n[12] = "12,NULL,NULL"\n[2] = "2,NULL,NULL"\n\nSquare brackets fixes it so the full number is compared\n[12] = "[12],NULL,NULL"\n[2] = "[2],NULL,NULL"\n```\n\n```\nclass Solution {\npublic:\n bool isSubtree(TreeNode* root, TreeNode* subRoot) {\n string s1 = convertToString(root);\n string s2 = convertToString(subRoot);\n return s1.find(s2) != string::npos;\n }\n \n string convertToString(TreeNode* node) {\n if(node == NULL) return "NULL,";\n return "[" + to_string(node->val) + "]" + "," + convertToString(node->left) + convertToString(node->right);\n }\n};\n```\n\n\uD83D\uDE46 Upvote if this helped you \uD83D\uDE46
4
0
['Depth-First Search', 'Recursion', 'C', 'C++']
0
subtree-of-another-tree
Thinking Process Explained. Bonus Cheeky Solution included ;)
thinking-process-explained-bonus-cheeky-yf5oy
Subtree of Another Tree\n\n## Question\n\n---\n\nGiven the roots of two binary trees\xA0root\xA0and\xA0subRoot, return\xA0true\xA0if there is a subtree of\xA0ro
ebaad96
NORMAL
2022-07-07T03:28:57.128131+00:00
2022-07-07T03:28:57.128177+00:00
268
false
# **Subtree of Another Tree**\n\n## Question\n\n---\n\nGiven the roots of two binary trees\xA0`root`\xA0and\xA0`subRoot`, return\xA0`true`\xA0if there is a subtree of\xA0`root`\xA0with the same structure and node values of\xA0`subRoot`\xA0and\xA0`false`\xA0otherwise.\n\nA subtree of a binary tree\xA0`tree`\xA0is a tree that consists of a node in\xA0`tree`\xA0and all of this node\'s descendants. The tree\xA0`tree`\xA0could also be considered as a subtree of itself.\n\n**Example 1:**\n\n![https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg](https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg)\n\n```\nInput: root = [3,4,5,1,2], subRoot = [4,1,2]\nOutput: true\n\n```\n\n**Example 2:**\n\n![https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg](https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg)\n\n```\nInput: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]\nOutput: false\n```\n\n## Solutions\n\n---\n\n1. First lets deal with a few base cases\n 1. base cases\n \n ```python\n #if there is a node and the subtree is None\n # we can be sure that subtree is in the tree\n if root and subRoot == None:\n return True\n \n # in the other case if there is a subtree and \n # no root(meaning no tree) its imposible for us to have a\n # subtree in a non existent tree\n # this will also take care of the base case when\n # have hit the bottom of the tree\n elif root == None and subRoot:\n return False\n else:\n # if the root == subTree \n \t\treturn True\n \t\t# recusrisve cases as we reduce the size of the tree\n ```\n \n2. We can\u2019t just ask this question of root == subtree as the subtree might not be fully like the root. In the case of the subtree being in the middle of the [tree.](http://tree.SO) We iterate over the whole subtree and the elements of the root to see if they are similar.\n \n ```python\n p = root q = subTree\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n \n \n # both nodes are None\n if p == None and q == None:\n return True \n \t\t\t\t# this will only be hit if the above one is not hit\n # one is None\n elif p == None or q == None:\n return False\n \t\t\t\t# we have both p and q\n else:\n \t\t # to be equal or not \n if p.val != q.val:\n return False\n return (self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right))\n ```\n \n3. Now we check for the condition in the else\n \n ```python\n else:\n if self.isSameTree(root,subRoot):\n return True\n return (self.isSubtree(root.left,subRoot) or self.isSubtree(root.right,subRoot))\n ```\n \n\n### Final Code\n\n```python\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n \n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n \n \n # both nodes are None\n if p == None and q == None:\n return True \n\t\t\t\t# this will only be hit if the above one is not hit\n # one is None\n elif p == None or q == None:\n return False\n\t\t\t\t# we have both p and q\n else:\n\t\t# to be equal or not \n if p.val != q.val:\n return False\n return (self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right))\n \n \n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n \n \n \n if root and subRoot == None:\n return True\n elif root == None and subRoot:\n return False\n else:\n if self.isSameTree(root,subRoot):\n return True\n return (self.isSubtree(root.left,subRoot) or self.isSubtree(root.right,subRoot))\n```\n\n> Time \u23F0\xA0O(N*M) Space \uD83D\uDCBE\xA0O(N+M) N = nodes in the main tree and M nodes in the subtree\n> \n\n### CHEAKY SOLUTION\n\n1. Traverse the Tree in any order. \n \n ```python\n def traverseTree(self, s):\n if s == None:\n return None\n #inorder Traversal\n else:\n return f"# {self.traverse_tree(s.left)} {s.val} {self.traverse_tree(s.right)}"\n ```\n \n2. Convert the traversal into a string. \n \n ```python\n rootString = traverseTree(root)\n #string = # # # None 1 None 4 # None 2 None 3 # None 5 None\n \n ```\n \n 1. Do the same with the subtree\n \n ```python\n subTreeString = traverseTree(subTree)\n #string = # # None 1 None 4 # None 2 None\n ```\n \n3. See if the subtree string is in the main tree string\n\n```python\nif string_t in string_s:\n return True\n return False\n```\n\n### Code\n\n```python\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n \n \n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n\n rootString= self.traverseTree(root)\n subRootString = self.traverseTree(subRoot)\n\n if subRootString in rootString:\n return True\n return False\n\n def traverseTree(self, s):\n if s == None:\n return None\n #inorder Traversal\n else:\n return f"# {self.traverseTree(s.left)} {s.val} {self.traverseTree(s.right)}"\n```\n\n> Time \u23F0\xA0O(N+M) Space \uD83D\uDCBE\xA0O(N+M) N = nodes in the main tree and M nodes in the subtree\n>
4
0
['Python']
0
subtree-of-another-tree
✅ Easy C++ Solution || Recursion
easy-c-solution-recursion-by-soorajks200-h768
\nclass Solution {\n bool check(TreeNode* root, TreeNode* subroot){\n if(root==nullptr and subroot==nullptr) return true;\n if(root==nullptr or
soorajks2002
NORMAL
2022-03-14T08:26:49.414090+00:00
2022-03-14T08:26:49.414118+00:00
519
false
```\nclass Solution {\n bool check(TreeNode* root, TreeNode* subroot){\n if(root==nullptr and subroot==nullptr) return true;\n if(root==nullptr or subroot==nullptr) return false;\n if(root->val!=subroot->val) return false;\n if(check(root->left,subroot->left) and check(root->right,subroot->right)) return true;\n return false;\n }\npublic:\n bool isSubtree(TreeNode* root, TreeNode* subRoot) {\n if(root==nullptr) return false;\n if(root->val==subRoot->val and check(root,subRoot)) return true;\n else if(isSubtree(root->left,subRoot)) return true;\n else if(isSubtree(root->right,subRoot)) return true;\n return false;\n }\n};\n```
4
0
['Recursion', 'C', 'C++']
0
subtree-of-another-tree
Python3 || Neat - Clean and Fast Code || TC: O(n) SC:O(1)
python3-neat-clean-and-fast-code-tc-on-s-up39
If you like the code please upvote\n\n\nclass Solution:\n def isSubtree(self, root: Optional[TreeNode], subroot: Optional[TreeNode]) -> bool:\n \n
Dewang_Patil
NORMAL
2022-02-28T23:58:31.601933+00:00
2022-02-28T23:58:31.601971+00:00
981
false
**If you like the code please upvote**\n\n```\nclass Solution:\n def isSubtree(self, root: Optional[TreeNode], subroot: Optional[TreeNode]) -> bool:\n \n def subchk(root, subroot):\n if not root and not subroot: return True\n elif not root or not subroot: return False\n \n if root.val == subroot.val:\n if subchk(root.left, subroot.left) and subchk(root.right, subroot.right):\n return True\n\n \n def valchk(root, subroot):\n if not root: return\n \n if root.val == subroot.val and subchk(root, subroot): res[0] = True\n \n if root.left: valchk(root.left, subroot)\n if root.right: valchk(root.right, subroot)\n \n res = [False]\n valchk(root, subroot) \n return res[0]\n```
4
0
['Depth-First Search', 'Recursion', 'Python', 'Python3']
2
subtree-of-another-tree
Rust 4ms | 2.3
rust-4ms-23-by-astroex-q67o
Runtime: 4 ms, faster than 100.00% of Rust online submissions for Subtree of Another Tree.\nMemory Usage: 2.3 MB, less than 45.45% of Rust online submissions fo
astroex
NORMAL
2022-01-08T21:28:00.886917+00:00
2022-01-08T21:28:00.886960+00:00
200
false
Runtime: 4 ms, faster than 100.00% of Rust online submissions for Subtree of Another Tree.\nMemory Usage: 2.3 MB, less than 45.45% of Rust online submissions for Subtree of Another Tree.\n```\nuse std::rc::Rc;\nuse std::cell::RefCell;\nimpl Solution {\n pub fn is_subtree(root: Option<Rc<RefCell<TreeNode>>>, sub_root: Option<Rc<RefCell<TreeNode>>>) -> bool {\n \n if root == sub_root {return true} \n if let Some(node) = root { \n let node = node.borrow();\n Self::is_subtree(node.left.clone(), sub_root.clone()) || \n Self::is_subtree(node.right.clone(), sub_root.clone())\n } else { \n return false \n }\n }\n}\n```
4
0
['Rust']
1
subtree-of-another-tree
[C++] Easy Solution Easy Recursion
c-easy-solution-easy-recursion-by-rishab-rvjg
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0)
Rishabhsinghal12
NORMAL
2021-11-01T14:20:16.868605+00:00
2021-11-01T14:23:12.335113+00:00
669
false
```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\n bool isSameTree(TreeNode* root1, TreeNode* root2)\n {\n if(!root1 and !root2)return true;\n if(!root1 || !root2)return false;\n if(root1->val != root2->val)return false;\n return isSameTree(root1->left,root2->left) and isSameTree(root1->right,root2->right);\n }\npublic:\n bool isSubtree(TreeNode* root, TreeNode* subRoot) \n {\n if(!root and !subRoot)return true;\n if(!root || !subRoot)return false;\n return isSameTree(root,subRoot) || isSubtree(root->left,subRoot) || isSubtree(root->right,subRoot);\n }\n};\n```
4
0
['Recursion', 'C', 'C++']
3
subtree-of-another-tree
Easy Java Solution
easy-java-solution-by-himanshubhoir-hg6g
\nclass Solution {\n public boolean isSubtree(TreeNode root, TreeNode subRoot) {\n if(root == null) return false;\n if(same(root,subRoot))
HimanshuBhoir
NORMAL
2021-10-12T07:37:33.062229+00:00
2021-10-12T07:37:33.062265+00:00
495
false
```\nclass Solution {\n public boolean isSubtree(TreeNode root, TreeNode subRoot) {\n if(root == null) return false;\n if(same(root,subRoot)) return true;\n return isSubtree(root.left,subRoot) || isSubtree(root.right,subRoot);\n }\n private boolean same(TreeNode root, TreeNode subRoot){\n if(root == null && subRoot == null) return true;\n if(root == null || subRoot == null) return false;\n if(root.val != subRoot.val) return false;\n return same(root.left,subRoot.left) && same(root.right,subRoot.right);\n }\n}\n```
4
1
['Java']
0
count-the-number-of-incremovable-subarrays-ii
C++ | Two pointer | O(N) | Detailed Explanation
c-two-pointer-on-detailed-explanation-by-4zfy
This question is very intresting.\n\nI solved this question with opposite langauge in question see test case 3 : [8,7,6,6] \n\nwe remove -\n\n[8,7,6] to make re
chandanagrawal23
NORMAL
2023-12-23T16:07:45.213674+00:00
2023-12-23T17:09:01.406341+00:00
4,585
false
This question is very intresting.\n\nI solved this question with opposite langauge in question see test case 3 : [8,7,6,6] \n\nwe remove -\n\n[8,7,6] to make remaining [6] as our valid array ( in question we have given after removal the remaining array should be strictly increasing)\n[7,6,6] to make remaining [8] as our valid array ( in question we have given after removal the remaining array should be strictly increasing)\n[8,7,6,6] to make remaining [] as our valid array ( in question we have given after removal the remaining array should be strictly increasing)\n\n\nSo instead of saying how many subarrays we have to remove , I will say how many valid array I can Make - \n\n\nLet\'s take bigger example - \n\nArr : [1,2,5,3,4,6,7] , answer will be 18 let see how ?\n\n\nlet\'s try to parition this array into two strictly sorted part \n\n1 => [1,2,5] called as left\n\n2 => [3,4,6,7] called as right\n\nThere are 4 parts of solution -\n\n\n1) Take only from left array, so how many elements I can take ? obviously 3 how ? [1], [1,2] , [1,2,5] and see all are valid LOOK CAREFULLY PREFIX are valid\n\n2) Take only from right arrar, so how many elements I can take ? obviously 4 how ? [7], [6,7] , [4,6,7], [3,4,6,7] and see all are valid LOOK CAREFULLY SUFFIX are valid\n\n3) Take prefix from left + suffix from right such that the merge will be sorted ?\n\n so [1],[7]\n [1],[6,7]\n [1],[4,6,7]\n [1],[3,4,6,7]\n [1,2],[7]\n [1,2],[6,7]\n [1,2],[4,6,7]\n [1,2],[3,4,6,7]\n [1,2,5],[7]\n [1,2,5],[6,7]\n\n So that means given two sorted arrays how many sorted arrays I can make such that I will take prefix of first array and suffix of second array and the resultant array will be sorted.\n\n\n4) add extra 1 to delete whole array and empty array [] will be valid array.\n\n**TOTAL = 3 + 4 + 10 + 1 = 18**\n\n```\nclass Solution {\npublic:\n long long countSortedArrays(const vector<int>& arr1, const vector<int>& arr2) {\n int n1 = arr1.size();\n int n2 = arr2.size();\n\n long long result = 0;\n int i = 0, j = 0;\n\n while (i < n1 && j < n2) {\n if (arr1[i] < arr2[j]) {\n // If arr1[i] is less than arr2[j], you can form sorted arrays with arr1[0..i] and arr2[j..n2-1]\n result += (n2 - j);\n i++;\n } else {\n // If arr1[i] is greater than arr2[j], move to the next element in arr2\n j++;\n }\n }\n\n return result;\n}\n long long incremovableSubarrayCount(vector<int>& a) {\n long long n = a.size();\n\t\t\n if(n==1)\n return 1;\n \n\t\tint i=0;\n int j=n-1;\n\t\t\n vector<int>arr1,arr2;\n\n while((i+1)<n and a[i]<a[i+1])\n {\n arr1.push_back(a[i]);\n i++;\n }\n arr1.push_back(a[i]);\n \n while((j-1)>=0 and a[j]>a[j-1]){\n arr2.push_back(a[j--]);\n }\n arr2.push_back(a[j]);\n\t\t\n reverse(arr2.begin(),arr2.end());\n if(j<i)\n {\n long long ans = (1ll*n*(n+1)*1LL)/2;\n return ans;\n }\n\t\t\n long long ans = 0;\n\t\tans += arr1.size(); //1\n ans += arr2.size(); //2\n ans += countSortedArrays(arr1,arr2); //3\n\t\tans++; //4\n \n\t\treturn ans;\n \n }\n};\n```\n\nPS : if whole array is struclty sorted, we will just find total subarray.\n\nThanks for reading, please upvote :)\n\nConnect me on Linkedin : https://www.linkedin.com/in/chandanagrawal23/\n
106
2
['Two Pointers', 'C++']
17
count-the-number-of-incremovable-subarrays-ii
Explained with dry run - left & right increasing seq || simple & easy to understand
explained-with-dry-run-left-right-increa-rn7v
Intuition\n- If you consider as the pionts as the line chart then you will realise that only the starting increasing sequence and ending increasing sequence is
kreakEmp
NORMAL
2023-12-23T20:24:08.905132+00:00
2023-12-24T04:54:26.162954+00:00
1,301
false
# Intuition\n- If you consider as the pionts as the line chart then you will realise that only the starting increasing sequence and ending increasing sequence is contributing to the result.\n- Further the each number from starting incresing sequence to each number from the ending incresing sequence which are greater than the starting sequence number considered can be removed.\n- Also the for the end sequence, we can consider starting point as 0 and till that number we can remove and hence we can have : end incresing seq numbers count + 1 sub arrays that can be removed\n- This is the case because we can remove item from diff chunk and can only be removed from middle.\n\n\n# Approach\n- we need to find the increasing sequenc from the end.\n- If the complete array is in increasing then total no of way we can remove = total number of subarray possible = (n*(n+1))/2. So return is answer.\n- After this we will update answer to size of the last increasing sequence + 1. As we can remove that many subarrays where the starting index is 0 and ending index of subarray is one of the item in the increasing seq. +1 is for the completely empty where we remove all items.\n- Now start checking the incresing sequence from the begin. For each item from begin, we have search the upper bound (next greater item) in the last increasing sequence that we have created. Count the number left after that larger value include that one. that many number of sub array can be removed - where the start index of the sub array is the nums[i] + 1 and end index is any item which is larger than nums[i] in the last increasing sub sequence.\n - this can be achived by evaluating the upper bound index then calculate to number of items on its right.\n\nExample: \n\n```\nlets the nums = [1, 4, 6, 2, 5, 12, 4, 8, 10]\n\nSo here the incresing sub-array from the end is [4, 8, 10] \n\nNow we update our answer with 4 as we can remove 4 ways (size of increasing seq + 1 ) shown below :\n\n[ 1, 4, 6, 2, 5, 12, 4, 8, 10]\n ------------------\n ---------------------\n -----------------------\n ---------------------------\nans = 4 till now\n\n------------------------------------------------------------------\nNow we start iterating from begin, until the sequenc is in increasing order:\nFirst we see 1, so we search for next incresing item in the [4, 8, 10] that is 4. now there are 3 items towrds right of 3 including 4. So total number of way we can remove is 3 +1 = 4 as shown below:\n[ 1, 4, 6, 2, 5, 12, 4, 8, 10]\n ---------------\n -----------------\n ---------------------\n -----------------------\nans = 4 + 4 = 8 ways\nBasically we start from the next to 1 and go till end of the incresing sequnce we have.\n\n------------------------------------------------------------------\nNow lets update our iteration to next item that is 4. So for 4 next largest item in [4, 8, 10] is 8 and we have 2 items towrds right including 8. So total no of ways we can remove the sub array = 2 + 1 = 3\nas shown below:\n\n[ 1, 4, 6, 2, 5, 12, 4, 8, 10]\n ----------------\n -------------------\n ----------------------\nSo now ans is = 8 +3 = 11 ways\n\n------------------------------------------------------------------\nSimilarly for 6 next larget is 8 and only 3 ways we can remove sub array starting from next item of 6 as shown below:\n\n[ 1, 4, 6, 2, 5, 12, 4, 8, 10]\n -------------\n ----------------\n -------------------\nNow the ans = 11 + 3 = 14\n\nAs the next item of 6 is 2, which breaks our increasing sequence from begin we stop now and return the answer.\n\n```\n\n### Complexity\n- Time complexity : O(N.logN)\n- Space complexity : O(N)\n\n# Code\n```\nlong long incremovableSubarrayCount(vector<int>& nums) {\n vector<int> lastInc;\n lastInc.push_back(nums.back());\n for(int i = nums.size()-2; i >= 0; --i){ // find the increasing sequence from the right most side\n if(nums[i] >= nums[i+1]) break;\n lastInc.push_back(nums[i]);\n } \n reverse(lastInc.begin(), lastInc.end()); // reverse it to set it to ascending order\n if( nums.size() == lastInc.size()) return (nums.size() * (nums.size() + 1)/2); // If the complete array is in increasing then total no of way we can remove = total number of subarray possible = (n*(n+1))/2\n\n long long ans = 1+lastInc.size(), n = nums.size() - lastInc.size();\n for(int i = 0, last = -1; i < n; ++i){\n if(nums[i] <= last) break; \n last = nums[i];\n ans += lastInc.end() - upper_bound(lastInc.begin(), lastInc.end(), nums[i]) + 1;\n }\n return ans;\n}\n```\n\n---\n\n<b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted\n\n---
23
3
['C++']
2
count-the-number-of-incremovable-subarrays-ii
Two Pointers
two-pointers-by-votrubac-xl06
Frustrating edge cases. Otherwise a typical two-pointer solution.\n\nFor each i where [0, i - 1] is strictly increasing, we find the smallest j so that:\n- [j +
votrubac
NORMAL
2023-12-23T18:22:34.806399+00:00
2023-12-23T21:01:59.657292+00:00
905
false
Frustrating edge cases. Otherwise a typical two-pointer solution.\n\nFor each `i` where `[0, i - 1]` is strictly increasing, we find the smallest `j` so that:\n- `[j + 1, sz)` is strictly increasing.\n\t- This can be done by going right-to-left once in the beginning.\n- `nums[i - 1] < nums[j + 1]`.\n\t- `j` goes left-to-right until this condition is satisfied.\n\nThe subarray `[i, j]` is incremovable, and so do `sz - j` subarrays:\n- We add `1 + sz - j` to the result.\n\n**C++**\n```cpp\nlong long incremovableSubarrayCount(vector<int>& nums) {\n int sz = nums.size(), j = sz - 1;\n while (j > 1 && nums[j - 1] < nums[j])\n --j;\n if (j == 0)\n return sz * (sz + 1) / 2;\n long long res = 1 + sz - j;\n for (int i = 1; i < sz; ++i) {\n j = max(i + 1, j);\n while (j < sz && nums[i - 1] >= nums[j])\n ++j;\n res += 1 + sz - j;\n if (nums[i - 1] >= nums[i])\n break;\n }\n return res;\n} \n```
16
1
['C']
4
count-the-number-of-incremovable-subarrays-ii
Video Explanation (Journey from N^3 --> N*N --> N)
video-explanation-journey-from-n3-nn-n-b-h3bu
Explanation\n\nClick here for the video\n\n# Code\n\ntypedef long long int ll;\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>
codingmohan
NORMAL
2023-12-23T16:32:30.946238+00:00
2023-12-23T16:32:30.946268+00:00
408
false
# Explanation\n\n[Click here for the video](https://youtu.be/XONGTEupzPY)\n\n# Code\n```\ntypedef long long int ll;\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n int n = nums.size();\n \n int lft = 0;\n int rgt = n-1;\n while (lft+1 < n && nums[lft] < nums[lft+1]) lft ++;\n while (rgt > 0 && nums[rgt-1] < nums[rgt]) rgt --;\n \n ll ans = (lft == n-1)? 0 : 1 + (n - rgt);\n for (int i = 0; i <= lft; i ++) {\n int valid_start = upper_bound(nums.begin()+rgt, nums.end(), nums[i]) - nums.begin();\n ans += (n - valid_start + 1);\n }\n return ans;\n }\n};\n```
10
0
['C++']
1
count-the-number-of-incremovable-subarrays-ii
Python | Two Pointers | O(n)
python-two-pointers-on-by-aryonbe-msrq
Code\n\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n nums = [0]+nums+[float(\'inf\')]\n n = len(nums)\n
aryonbe
NORMAL
2023-12-23T16:04:51.801576+00:00
2023-12-23T16:04:51.801599+00:00
866
false
# Code\n```\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n nums = [0]+nums+[float(\'inf\')]\n n = len(nums)\n for i in range(n-1):\n if nums[i] >= nums[i+1]:\n break\n else:\n return (n-2)*(n-1)//2\n for j in range(n-1, 0, -1):\n if nums[j-1] >= nums[j]:\n break\n l = 0\n r = j\n res = 0\n while l <= i:\n while r < n and nums[l] >= nums[r]:\n r += 1\n res += n - r\n l += 1\n return res\n \n \n \n \n \n```
9
0
['Python3']
3
count-the-number-of-incremovable-subarrays-ii
[Java/C++/Python] Two Pointers, O(n)
javacpython-two-pointers-on-by-lee215-kcmv
Explanation\nFind the longest increasing prefix subarray.\nIf the A is strict increasing,\nreturn n * (n + 1) / 2.\n\nThe check the all increasing suffix array
lee215
NORMAL
2023-12-28T08:52:35.613275+00:00
2023-12-28T08:52:35.613295+00:00
271
false
# **Explanation**\nFind the longest increasing prefix subarray.\nIf the `A` is strict increasing,\nreturn `n * (n + 1) / 2`.\n\nThe check the all increasing suffix array one elment by one element,\nand find out the longest smaller increasing prefix by moving the pointer `i`.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public long incremovableSubarrayCount(int[] A) {\n int n = A.length, i = 0;\n while (i + 1 < n && A[i] < A[i + 1]) {\n i++;\n }\n if (i == n - 1) {\n return n * (n + 1) / 2;\n }\n long res = i + 2;\n for (int j = n - 1; j >= 0; j--) {\n if (j < n - 1 && A[j] >= A[j + 1]) {\n break;\n }\n while (i >= 0 && A[i] >= A[j]) {\n i--;\n }\n res += i + 2;\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n long long incremovableSubarrayCount(vector<int>& A) {\n int n = A.size(), i = 0;\n while (i + 1 < n && A[i] < A[i + 1])\n i++;\n if (i == n - 1)\n return n * (n + 1) / 2;\n long long res = i + 2;\n for (int j = n - 1; j >= 0; j--) {\n if (j < n - 1 && A[j] >= A[j + 1]) break;\n while (i >= 0 && A[i] >= A[j])\n i--;\n res += i + 2;\n }\n return res;\n }\n```\n\n**Python**\n```py\n def incremovableSubarrayCount(self, A: List[int]) -> int:\n n = len(A)\n i = 0\n while i + 1 < n and A[i] < A[i + 1]:\n i += 1\n if i == n - 1:\n return n * (n + 1) // 2\n res = i + 2\n for j in range(n - 1, -1, -1):\n if j < n - 1 and A[j] >= A[j + 1]:\n break\n while i >= 0 and A[i] >= A[j]:\n i -= 1\n res += i + 2\n return res\n\n```\n
7
0
['C', 'Python', 'Java']
2
count-the-number-of-incremovable-subarrays-ii
Beats 100%! Java - Two Pointers + Binary Search - O(NlogN)
beats-100-java-two-pointers-binary-searc-ze9k
Intuition\nThere are two steps involved in solving this problem:\n1. Since we are removing a subarray from the array, the smallest subarray we must always remov
harsh0p
NORMAL
2023-12-24T13:49:41.979061+00:00
2023-12-24T13:49:41.979097+00:00
227
false
# Intuition\nThere are two steps involved in solving this problem:\n1. Since we are removing a subarray from the array, the **smallest subarray we must always remove** will be the one which leaves an increasing left subarray and increasing right subarray. We can use two pointers and simple traversals to find our anwer here.\n\n - Example: ```[1, 2, 3, 4, 3, 9, 8, 1, 6, 7, 8]``` in this case the left increasing subarray is ```[1, 2, 3, 4]``` and right increasing subarray is ```[1, 6, 7, 8]```. Inclusion of ```3``` in a solution containing left subarray will invalidate the answer and similarily inclusion of ```8``` in right subarray will as well. Thus all of anwers must at minimum remove ```[3, 9, 8]```.\n\n2. Then for each element on the left subarray we must find the smallest subarray starting from that element which must be removed to form an increasing array. All subarrays greater than this one are our answers as well. We can use upper bound binary search to find our anwer here.\n\n - Example: ```[1, 2, 3, 4, 3, 9, 8, 1, 6, 7, 8]``` consider ```1``` in the left subarray. We will apply binary search on ```[1, 6, 7, 8]``` to find first element larger than ```1```. Thus we get ```6```. Meaning, If we start our subarray from ```2``` then it must atleast go on till ```1``` to leave an increasing sequence behind. There can be total four such arrays that start from ```2```.\n\n3. In above step we have considered all subarrays that start after ```1``` but not those which also contain ```1```. These subarrays will be equal to the number of elements in right increasing subarray plus 1 (for the whole array). \n\nSmall Optimization: If our whole array is increasing we can simply return ```n * (n + 1)/2``` as answer as it is the number of all unique possible subarrays.\n\n# Approach\nTraverse from left carrying and ```index``` and ```prev``` pointer. When ```index``` is smaller than or equal to ```prev``` we stop and ```prev``` is the last element of our left increasing subarray.\n\nIf we reach the end then return ```n * (n + 1)/2```.\n\nSimilarily traverse from right and perform the operation in reverse to find the first element of our right increasing subarray.\n\nNow for every element in the left increasing subarray we will find its upper bound in the right increasing subarray. For each element we will add to ```ans``` this ```nums.length - val + 1``` as it is the number of possible subarrays from that element.\n\nIn the end we add ```nums.length - r + 1``` to aur answer to account for all subarrays stating from ```0th``` index.\n\n# Complexity\n- Time complexity: O(NlogN) \nN to traverse through left increasing subarray and we perform binary search at each element for logN\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) Extra space taken \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\nAn upvote from you would make my day :)\n```\nclass Solution {\n public long incremovableSubarrayCount(int[] nums){\n int l = 0, r = nums.length-1;\n int idx = 1;\n while(idx < nums.length && nums[l] < nums[idx]){\n idx++;\n l++;\n }\n if(idx == nums.length){\n return nums.length*(nums.length+1)/2;\n }\n idx = nums.length-2;\n while(idx > 0 && nums[r] > nums[idx]){\n idx--;\n r--;\n }\n long ans = 0;\n for(int i = 0; i <= l; i++){\n int val = bs(nums, r, nums.length-1, nums[i]);\n val = nums.length - val + 1;\n ans = ans + val;\n }\n ans = ans + nums.length - r + 1;\n return ans;\n }\n\n public int bs(int[] nums, int l, int r, long x){\n int ans = -1;\n while(l <= r){\n int mid = (l+r)/2;\n if(nums[mid] <= x){\n l = mid+1;\n }else{\n ans = mid;\n r = mid-1;\n }\n }\n if(ans == -1) return nums.length;\n return ans;\n }\n\n\n}\n```
7
0
['Two Pointers', 'Binary Search', 'Java']
1
count-the-number-of-incremovable-subarrays-ii
✅☑[C++/Java/Python/JavaScript] || Easiest Approach || EXPLAINED🔥
cjavapythonjavascript-easiest-approach-e-1o0l
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n1. Finding the First Increasing Sequence:\n - Move the pointer \'r\' unt
MarkSPhilip31
NORMAL
2023-12-23T16:22:09.316676+00:00
2023-12-23T16:22:09.316702+00:00
936
false
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n1. **Finding the First Increasing Sequence:**\n - Move the pointer \'r\' until the elements are in increasing order.\n - If the entire array is in increasing order, return the count of all possible subarrays.\n1. **Iterating Backward:**\n - Traverse the array backward and find the count of "incremovable" subarrays.\n - Use binary search to find the position of the current element in the increasing sequence.\n - Increment the count based on the position found.\n1. **Return the Total Count:** Return the total count of "incremovable" subarrays.\n\n\n# Complexity\n- Time complexity:\n $$O(nlogr)$$\n \n\n- Space complexity:\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n long long ans = 1; // Initialize the count with 1 (single element is always "incremovable")\n int r = 1; // Initialize a pointer r to 1\n int n = nums.size(); // Get the size of the input vector\n\n // Move the pointer r until elements are in increasing order\n while (r < n && nums[r] > nums[r - 1]) {\n r++;\n }\n\n // If the entire array is in increasing order, return the count of all possible subarrays\n if (r == n) {\n return 1LL * n * (n + 1) / 2;\n }\n\n int lst = 1e9 + 1; // Set a large initial value for \'lst\' (to ensure comparison with first element)\n ans += r; // Increment the count by the current value of pointer r\n\n // Iterate through the array from the end to count "incremovable" subarrays\n for (int i = n - 1; i >= 0; i--) {\n if (nums[i] >= lst) { // If the current element is greater than or equal to \'lst\', break the loop\n break;\n }\n int low = 0, high = r - 1; // Initialize pointers for binary search\n int left = -1; // Initialize \'left\' to -1\n\n // Binary search to find the position of the current element in the increasing sequence\n while (low <= high) {\n int mid = (low + high) >> 1; // Calculate mid index\n if (nums[mid] < nums[i]) {\n left = mid; // Update \'left\' if the current element is greater\n low = mid + 1; // Adjust the search range\n } else {\n high = mid - 1; // Adjust the search range\n }\n }\n\n ans += (left + 2); // Increment the count by (left + 2)\n lst = nums[i]; // Update \'lst\' with the current element\n }\n return ans; // Return the total count of "incremovable" subarrays\n }\n};\n\n\n\n\n\n```\n```Java []\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n long ans = 1;\n int r = 1;\n int n = nums.length;\n\n while (r < n && nums[r] > nums[r - 1]) {\n r++;\n }\n\n if (r == n) {\n return (long) n * (n + 1) / 2;\n }\n\n int lst = Integer.MAX_VALUE;\n ans += r;\n\n for (int i = n - 1; i >= 0; i--) {\n if (nums[i] >= lst) {\n break;\n }\n int low = 0, high = r - 1;\n int left = -1;\n\n while (low <= high) {\n int mid = (low + high) >> 1;\n if (nums[mid] < nums[i]) {\n left = mid;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n ans += (left + 2);\n lst = nums[i];\n }\n\n return ans;\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n ans = 1\n r = 1\n n = len(nums)\n\n while r < n and nums[r] > nums[r - 1]:\n r += 1\n\n if r == n:\n return n * (n + 1) // 2\n\n lst = float(\'inf\')\n ans += r\n\n for i in range(n - 1, -1, -1):\n if nums[i] >= lst:\n break\n low, high = 0, r - 1\n left = -1\n\n while low <= high:\n mid = (low + high) // 2\n if nums[mid] < nums[i]:\n left = mid\n low = mid + 1\n else:\n high = mid - 1\n\n ans += (left + 2)\n lst = nums[i]\n\n return ans\n\n\n\n```\n```javascript []\nvar incremovableSubarrayCount = function(nums) {\n let ans = 1;\n let r = 1;\n const n = nums.length;\n\n while (r < n && nums[r] > nums[r - 1]) {\n r++;\n }\n\n if (r === n) {\n return (n * (n + 1)) / 2;\n }\n\n let lst = Number.MAX_SAFE_INTEGER;\n ans += r;\n\n for (let i = n - 1; i >= 0; i--) {\n if (nums[i] >= lst) {\n break;\n }\n let low = 0, high = r - 1;\n let left = -1;\n\n while (low <= high) {\n let mid = Math.floor((low + high) / 2);\n if (nums[mid] < nums[i]) {\n left = mid;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n ans += (left + 2);\n lst = nums[i];\n }\n\n return ans;\n};\n\n\n\n```\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
7
1
['String', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
2
count-the-number-of-incremovable-subarrays-ii
Easy C++ Solution || Two Pointer
easy-c-solution-two-pointer-by-gojo_28s-073r
Intuition\n Describe your first thoughts on how to solve this problem. \nAbsolutely! This alternate perspective changes the problem statement and the approach t
Gojo_28s
NORMAL
2023-12-23T16:44:17.295789+00:00
2023-12-23T16:44:17.295808+00:00
281
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAbsolutely! This alternate perspective changes the problem statement and the approach to solve it. Instead of counting the number of subarrays to remove to make the remaining array strictly increasing, you\'re now looking at the number of valid arrays that can be formed by selecting prefixes and suffixes from two strictly increasing partitions of the given array.\n\n!! IMPORTANT THING IN THIS QUESTION IS :-\nFinding the number of combination of two sorted array elements to form a strictly increasing array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s how you can approach solving this revised problem in C++:\n1. First count the prefix strictly increasing array.\n2. Second count the suffix strictly increasing array.\n3. Then their merge combination.\n4. Lastly add 1 for complete array deletion.\n\n\nCertainly! Let\'s adapt the approach to the array [1, 2, 4, 3, 5, 6].\n\nBreaking down the array into strictly increasing partitions:\n\nLeft Partition: [1, 2, 4]\nRight Partition: [3, 5, 6]\nEnumerating the valid arrays formed by selecting prefixes from the left and suffixes from the right:\n\nPrefixes from Left (Left Partition):\n\n[1]\n[1, 2]\n[1, 2, 4]\nSuffixes from Right (Right Partition):\n\n[6]\n[5, 6]\n[3, 5, 6]\nPrefixes from Left & Suffixes from Right:\n\n[1], [6]\n[1], [5, 6]\n[1, 2], [6]\n[1, 2], [5, 6]\n[1, 2, 4], [6]\n[1, 2, 4], [5, 6]\nTotal valid arrays: 12+1 (add 1 for the complete array removal)\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \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 long long countSortedArrays(const vector<int>& arr1, const vector<int>& arr2) {\n int n1 = arr1.size();\n int n2 = arr2.size();\n\n long long cnt = 0;\n int i = 0, j = 0;\n\n while (i < n1 && j < n2) {\n if (arr1[i] < arr2[j]) {\n cnt += (n2 - j);\n i++;\n } else {\n j++;\n }\n }\n\n return cnt;\n}\n long long incremovableSubarrayCount(vector<int>& a) {\n long long n = a.size();\n\t\t\n if(n==1)\n return 1;\n \n\t\tint i=0;\n int j=n-1;\n\t\t\n vector<int>arr1,arr2;\n\n while((i+1)<n and a[i]<a[i+1])\n {\n arr1.push_back(a[i]);\n i++;\n }\n arr1.push_back(a[i]);\n \n while((j-1)>=0 and a[j]>a[j-1]){\n arr2.push_back(a[j--]);\n }\n arr2.push_back(a[j]);\n\t\t\n reverse(arr2.begin(),arr2.end());\n\n \n if(j<i)\n {\n long long ans = (1ll*n*(n+1)*1LL)/2;\n return ans;\n }\n\n long long ans = arr1.size();\n ans += arr2.size();\n ans++;\n ans += countSortedArrays(arr1,arr2);\n return ans;\n \n }\n};\n```
6
1
['C++']
2
count-the-number-of-incremovable-subarrays-ii
C++ || O(n) || SLIDING WINDOW || COMMENTS 🔥
c-on-sliding-window-comments-by-silent_w-i1yg
\nKEY IDEA: We can only remove the SUBARRAY. So you see that we can remove the subarray from index left to right such that all elements from right+1 to n are st
Silent_Warrior_001
NORMAL
2023-12-23T16:01:54.316530+00:00
2023-12-23T16:32:53.477137+00:00
1,552
false
\nKEY IDEA: We can only remove the SUBARRAY. So you see that we can remove the subarray from index left to right such that all elements from right+1 to n are strictly increasing and all elements from 0 to left-1 are strictly increasing. AND all element from 0 to left-1 are strictly less than all elements from right+1 to n. \n\n\n\n# Code\n```\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n long long int i,j,k,n=nums.size(),indl=-1,inds=-1,cnt,l,r;\n cnt=0;\n for(i=0;i<n-1;i++){\n if(nums[i]<nums[i+1]){\n cnt++;\n }\n }\n if(cnt==n-1){\n return (n*(n+1))/2;\n }\n\n cnt=0; \n for(i=n-2;i>=0;i--){\n if(nums[i]>=nums[i+1]){\n indl=i;\n break;\n }\n }\n cnt=n-indl; //if we start removing from the first element \n i=0; j=indl+1; \n while(i<n || j<n ){\n if(i>0 && nums[i]<=nums[i-1]){ //if so then we can not remove subarray from starting\n break;\n }\n while(j<n && nums[i]>=nums[j]){ //we are doing this to remove the middle subarray\n j++;\n }\n if(j<n && nums[i]<nums[j]){\n cnt+=(n-j+1); //this subarray we will remove\n }\n else if(j>=n && i<n){\n cnt+=(n-j+1); //we are removing subarray from the end side\n }\n i++;\n }\n return cnt; \n }\n};\n```
6
1
['C++']
2
count-the-number-of-incremovable-subarrays-ii
C++| Easy solution|O(nlogn)
c-easy-solutiononlogn-by-nastywaterespre-vvos
Intuition\nSince the question demands O(n) or O(nlogn) solution,\nwe can think finding the number of incremoval subarrays with left end at index i for all 0<=i
NastyWaterEspresso
NORMAL
2023-12-24T03:42:06.353597+00:00
2024-02-10T14:03:47.049270+00:00
116
false
# Intuition\nSince the question demands $$O(n)$$ or $$O(nlogn$$) solution,\nwe can think finding the number of incremoval subarrays with left end at index $$i$$ for all $$0<=i<n$$ efficiently.\n\nLet\'s find the length ($$l$$) of the longest prefix (P) such that this prefix is an increasing subarray\nSimilarly, find the length ($$r$$) of the longest suffix (S) which is an increasing subarray\n\nEx: $$[6, 5, 10, 7, 8]$$\nP: $$[6]$$\nS: $$[7, 8]$$\n\n$$l=1, r=2$$\nThe valid incremoval subarrays are \n$$[6, 5, 10]$$\n$$[6, 5, 10, 7]$$\n$$[6, 5, 10, 7, 8]$$\n\n$$[5, 10]$$\n$$[5, 10, 7]$$\n$$[5, 10, 7, 8]$$\n\n$$total=6$$\n\nYou can observe that the elements in the range $$[l, n-r-1]$$ always exist in any valid incremoval subarray\n\n# Approach\n\nFor every element $$a[i]$$ in the prefix P, find the leftmost element $$a[j]$$ in the suffix S just greater than $$a[i]$$ \n\nThen the number of valid incremoval subarrays with left end as $$i+1$$ is \n$$[i+1, j-1], [i+1..j], [i+1..j+1], ..... [i+1..n-1]$$\n\nWhich is $$n-j+1$$\nWe also need to calculate the number of valid incremoval subarrays with left end as $$i=0$$\nwhich is $$r+1$$\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\ntypedef long long ll;\n\n\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& a) {\n long long ans=0;\n long long n=a.size();\n ll idx=n-1;\n ll r=1;\n for(int i=n-2;i>=0;i--)\n {\n if(a[i]<a[i+1]) {\n idx=i;\n r++;\n }\n else break;\n \n }\n long long l=1;\n for(int i=1;i<n;i++) {\n if(a[i]>a[i-1]) {\n l++;\n }\n else break;\n }\n if(l==n) {\n return (n*(n+1))/2;\n }\n \n vector<int> b;\n for(int i=idx;i<n;i++) {\n b.push_back(a[i]);\n }\n \n for(int i=0;i<l;i++)\n {\n \n ans+=b.end()-upper_bound(b.begin(), b.end(), a[i]);\n ans++;\n }\n ans+=r+1;\n return ans;\n }\n};\n```
5
0
['Binary Search', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
Optimal Solution | Beats 100% Users
optimal-solution-beats-100-users-by-cs_i-22vp
Approach\n Describe your approach to solving the problem. \nSince we have to delete subarrays. and the remaining should be in sorted order.\nI have 3 cases\n- R
cs_iitian
NORMAL
2023-12-23T16:58:26.765541+00:00
2023-12-23T17:25:12.826647+00:00
437
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nSince we have to delete subarrays. and the remaining should be in sorted order.\nI have 3 cases\n- Remove from starting\n- Remove from end\n- Remove from middle\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 {\n public long incremovableSubarrayCount(int[] nums) {\n int n = nums.length;\n if(n == 1) return 1;\n if(n == 2) {\n return 3;\n }\n \n long ans = 1; // removing all would be a solution\n\n // left increasing\n int left = 0;\n while(left < n-1 && nums[left] < nums[left+1]) {\n left++;\n }\n ans += left + 1l;\n \n // right increasing\n int right = n-1;\n while(right > 0 && nums[right-1] < nums[right]) {\n right--;\n }\n ans += n - right;\n \n // if all are increasing\n if(left >= right) {\n return ((n)*(n+1))/2l;\n }\n\n left = 0;\n // middle handling\n while(left < right && right < n) {\n if(nums[left] < nums[right]) {\n ans += right == n-1 ? 1l : (long)(n-right);\n if(left < n-1 && nums[left] < nums[left+1])\n left++;\n else \n break;\n } else {\n right++;\n }\n }\n \n return ans;\n }\n}\n```\n\n# Subscribe to Our Youtube Channel\nMy coding youtube channel, [cs_iitian](https://www.youtube.com/channel/UCuxmikkhqbmBOUVxf-61hxw), where I explore the fascinating world of programming and tech! \uD83D\uDDA5\uFE0F Join me on this journey of creativity, problem-solving, and continuous learning. Subscribe now and let\'s code together: https://www.youtube.com/channel/UCuxmikkhqbmBOUVxf-61hxw \uD83D\uDD17 Happy coding! \uD83D\uDE80\u2728 #CodingCommunity #TechEnthusiast #LearnToCode
5
0
['Java']
1
count-the-number-of-incremovable-subarrays-ii
Left and Right boundary Simple approach... C++
left-and-right-boundary-simple-approach-4cp2i
\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n long long n = nums.size();\n long long left = 0, right
asif_star_135
NORMAL
2023-12-23T16:41:45.424030+00:00
2023-12-23T16:41:45.424045+00:00
190
false
```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n long long n = nums.size();\n long long left = 0, right = n-1; // left and right boundary for sorted elements... \n \n\t\t// finding left side sorted elements\n while(left < n-1 && nums[left] < nums[left+1]) left++;\n \n\t\t// finding right side sorted elements\n while(right > 0 && nums[right] > nums[right-1]) right--;\n \n if(left >= right) return (n+1)*n/2; // condition for sorted elements\n \n long long ans = left + 1 + (n-right); // default elements that will be only from a single part(left or right)\n \n int i = 0, j = right;\n // calculate combinations of both left & right part elements...\n while(i <= left && j < n){\n if(nums[i] < nums[j]){\n ans += (n - j);\n i++;\n }\n else j++;\n }\n // +1 for empty resultant array as sorted...\n return ans+1;\n }\n};\n```
5
1
['Two Pointers', 'C']
0
count-the-number-of-incremovable-subarrays-ii
Best Solution O(n) 🔥 with 0ms in Java / C++ / C / C# / Python(3) / JavaScript / TypeScript
best-solution-on-with-0ms-in-java-c-c-c-yyp30
Intuition\n Describe your first thoughts on how to solve this problem. \n### "Simplified Strategy: Finding Strictly increasing / Strictly Ascending Subarrays at
sidharthjain321
NORMAL
2023-12-25T02:13:32.655208+00:00
2023-12-25T05:18:56.647928+00:00
213
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n### "Simplified Strategy: Finding Strictly increasing / Strictly Ascending Subarrays at Both Ends"\n\nInstead of counting the number of subarrays to remove to make the remaining array strictly increasing, you\'re now looking at the number of valid arrays that can be formed by selecting prefixes and suffixes from two strictly increasing partitions of the given array.\nThe valid subArrays will be made from only the strictly increasing parts.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- `n = nums.size()`\n- Firstly, find the `leftIdx` from start till the idx it is strictly increasing.\n```\nint leftIdx = 0;\nfor(int i = 1; i < n; i++) {\n if(nums[i-1] < nums[i]) leftIdx++;\n else break;\n}\n```\n- if `leftIdx = n`, then it means the overall array is strictly increasing then we are returning the total number of subarrays, as if we remove anything from the strictly increasing array, it will always be strictly increasing.\n```\nif (leftIdx == n - 1) {\n long long int ans = n * (n + 1) / 2;\n return ans;\n }\n```\n- Secondly, find the `rightIdx` from end till the idx it is strictly increasing.\n```\nll rightIdx = n-1;\nfor(int i = n-1; i > 0; i--) {\n if(nums[i-1] < nums[i]) rightIdx--;\n else break;\n}\n```\n- Initialise a variable `totalIncremovableSubarrays` for storing the total count og incremovable subarrays.\n```\nlong long int totalIncremovableSubarrays = 0;\n```\n- For example , Consider an array : [1,2,5,2,9,2,4,7,8,9] , here `leftIdx = 2` & `rightIdx = 5` , now if we don\'t take the left part of the array i.e, from idx `0` to `leftIdx` in our valid subarrays , then we have only strictly increasing elements as `[2,4,7,8,9]` and we want to make valid subarrays by taking nothing from left side and only taking elements from the right part then we can make :- `[2,4,7,8,9]`,`[4,7,8,9]`,`[7,8,9]`,`[8,9]`,`[9]`,`[]` as the removed incremovable subarrays was `[1,2,5,2,9]`,`[1,2,5,2,9,2]`,`[1,2,5,2,9,2,4]`,`[1,2,5,2,9,2,4,7]`,`[1,2,5,2,9,2,4,7,8]`,`[1,2,5,2,9,2,4,7,8,9]` respectively.\n\n- Here you can see incremovable subarrays made from only right strictly increasing part was number of elements in the right part and plus one for removing the whole array as empty array is also considered as strictly increasing.\n\n- So, the totalIncremovableSubarrays count will be increased by number of elements in the right part + 1. How many elements in the right part?? It is `n - rightIdx` and `1` for the empty array.\n```\ntotalIncremovableSubarrays += (n - rightIdx) + 1;\n```\n- Now , we will take the left part elements one by one and check with right part elements and then count the number of subarrays formed.\n- Now, How to check the left part element with right part element, as we know both the parts are strictly increasing , let\'s say left part is `[1,2,5]` and right part is `[2,4,7,8,9]`.\n\n- Now , we will check if the left part element is smaller than the right part element, if yes , then we count the subarrays formed with the help of pointer pointing to the right part element , If No, then we increase the pointer in the right subArray by one and again repeat this process for all the left part elements.\n```\nint l = 0 , r = rightIdx;\nwhile(l <= leftIdx) {\n while(r < n && nums[l] >= nums[r]) r++;\n totalIncremovableSubarrays += (n-r+1);\n l++;\n }\n```\n- Then , we return the `totalIncremovableSubarrays`.\n```\nreturn totalIncremovableSubarrays;\n\n```\n# Complexity\n- **Time complexity**: $$O(n)$$\n- As here we are using the two pointer approach for traversing the array elements only once\n\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space complexity:** $$O(1)$$\n- Here, we are using only integer variables of limited number which is obviously.. O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n``` C []\n#define ll long long int\nlong long incremovableSubarrayCount(int* nums, int n) {\n int leftIdx = 0;\n for (int i = 1; i < n; i++) {\n if (nums[i - 1] < nums[i]) {\n leftIdx++;\n } else {\n break;\n }\n }\n if (leftIdx == n - 1) {\n ll ans = (ll)n * (n + 1) / 2;\n return ans;\n }\n ll rightIdx = n - 1;\n for (int i = n - 1; i > 0; i--) {\n if (nums[i - 1] < nums[i]) {\n rightIdx--;\n } else {\n break;\n }\n }\n ll totalIncremovableSubarrays = 0;\n totalIncremovableSubarrays += (n - rightIdx) + 1;\n int l = 0, r = (int)rightIdx;\n while (l <= leftIdx) {\n while (r < n && nums[l] >= nums[r]) {\n r++;\n }\n totalIncremovableSubarrays += (n - r + 1);\n l++;\n }\n return totalIncremovableSubarrays;\n}\n```\n```C++ []\n#define ll long long int\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n int n = nums.size();\n int leftIdx = 0;\n for(int i = 1; i < n; i++) {\n if(nums[i-1] < nums[i]) leftIdx++;\n else break;\n }\n if(leftIdx == n-1) {\n ll ans = (n * (n+1)) / 2;\n return ans;\n }\n ll rightIdx = n-1;\n for(int i = n-1; i > 0; i--) {\n if(nums[i-1] < nums[i]) rightIdx--;\n else break;\n }\n ll totalIncremovableSubarrays = 0;\n totalIncremovableSubarrays += (n - rightIdx ) + 1;\n int l = 0 , r = rightIdx;\n while(l <= leftIdx) {\n while(r < n && nums[l] >= nums[r]) r++;\n totalIncremovableSubarrays += (n-r+1);\n l++;\n }\n return totalIncremovableSubarrays;\n }\n};\n```\n```C# []\npublic class Solution {\n public long IncremovableSubarrayCount(int[] nums) {\n int n = nums.Length;\n int leftIdx = 0;\n\n for (int i = 1; i < n; i++) {\n if (nums[i - 1] < nums[i]) {\n leftIdx++;\n } else {\n break;\n }\n }\n\n if (leftIdx == n - 1) {\n long ans = (long)n * (n + 1) / 2;\n return ans;\n }\n\n long rightIdx = n - 1;\n\n for (int i = n - 1; i > 0; i--) {\n if (nums[i - 1] < nums[i]) {\n rightIdx--;\n } else {\n break;\n }\n }\n\n long totalIncremovableSubarrays = 0;\n totalIncremovableSubarrays += (n - (int)rightIdx) + 1;\n\n int l = 0, r = (int)rightIdx;\n\n while (l <= leftIdx) {\n while (r < n && nums[l] >= nums[r]) {\n r++;\n }\n totalIncremovableSubarrays += (n - r + 1);\n l++;\n }\n\n return totalIncremovableSubarrays;\n }\n}\n```\n``` Java []\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n int n = nums.length;\n int leftIdx = 0;\n\n for (int i = 1; i < n; i++) {\n if (nums[i - 1] < nums[i]) {\n leftIdx++;\n } else {\n break;\n }\n }\n\n if (leftIdx == n - 1) {\n long ans = (long) n * (n + 1) / 2;\n return ans;\n }\n\n int rightIdx = n - 1;\n\n for (int i = n - 1; i > 0; i--) {\n if (nums[i - 1] < nums[i]) {\n rightIdx--;\n } else {\n break;\n }\n }\n\n long totalIncremovableSubarrays = 0;\n totalIncremovableSubarrays += (n - rightIdx) + 1;\n\n int l = 0, r = rightIdx;\n\n while (l <= leftIdx) {\n while (r < n && nums[l] >= nums[r]) {\n r++;\n }\n totalIncremovableSubarrays += (n - r + 1);\n l++;\n }\n\n return totalIncremovableSubarrays;\n }\n}\n\n\n```\n```python []\nclass Solution(object):\n def incremovableSubarrayCount(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n n = len(nums)\n leftIdx = 0\n\n for i in range(1, n):\n if nums[i - 1] < nums[i]:\n leftIdx += 1\n else:\n break\n\n if leftIdx == n - 1:\n ans = (n * (n + 1)) // 2\n return ans\n\n rightIdx = n - 1\n\n for i in range(n - 1, 0, -1):\n if nums[i - 1] < nums[i]:\n rightIdx -= 1\n else:\n break\n\n totalIncremovableSubarrays = 0\n totalIncremovableSubarrays += (n - rightIdx) + 1\n\n l, r = 0, rightIdx\n\n while l <= leftIdx:\n while r < n and nums[l] >= nums[r]:\n r += 1\n totalIncremovableSubarrays += (n - r + 1)\n l += 1\n\n return totalIncremovableSubarrays\n \n```\n``` Python3 []\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n n = len(nums)\n leftIdx = 0\n\n for i in range(1, n):\n if nums[i - 1] < nums[i]:\n leftIdx += 1\n else:\n break\n\n if leftIdx == n - 1:\n ans = (n * (n + 1)) // 2\n return ans\n\n rightIdx = n - 1\n\n for i in range(n - 1, 0, -1):\n if nums[i - 1] < nums[i]:\n rightIdx -= 1\n else:\n break\n\n totalIncremovableSubarrays = 0\n totalIncremovableSubarrays += (n - rightIdx) + 1\n\n l, r = 0, rightIdx\n\n while l <= leftIdx:\n while r < n and nums[l] >= nums[r]:\n r += 1\n totalIncremovableSubarrays += (n - r + 1)\n l += 1\n\n return totalIncremovableSubarrays\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar incremovableSubarrayCount = function(nums) {\n let n = nums.length;\n let leftIdx = 0;\n\n for (let i = 1; i < n; i++) {\n if (nums[i - 1] < nums[i]) leftIdx++;\n else break;\n }\n\n if (leftIdx === n - 1) {\n let ans = (n * (n + 1)) / 2;\n return ans;\n }\n\n let rightIdx = n - 1;\n\n for (let i = n - 1; i > 0; i--) {\n if (nums[i - 1] < nums[i]) rightIdx--;\n else break;\n }\n\n let totalIncremovableSubarrays = 0;\n totalIncremovableSubarrays += n - rightIdx + 1;\n\n let l = 0,\n r = rightIdx;\n\n while (l <= leftIdx) {\n while (r < n && nums[l] >= nums[r]) r++;\n totalIncremovableSubarrays += n - r + 1;\n l++;\n }\n\n return totalIncremovableSubarrays;\n }\n```\n``` TypeScript []\nfunction incremovableSubarrayCount(nums: number[]): number {\n const n = nums.length;\n let leftIdx = 0;\n\n for (let i = 1; i < n; i++) {\n if (nums[i - 1] < nums[i]) {\n leftIdx++;\n } else {\n break;\n }\n }\n\n if (leftIdx == n - 1) {\n const ans = (n * (n + 1)) / 2;\n return ans;\n }\n\n let rightIdx = n - 1;\n\n for (let i = n - 1; i > 0; i--) {\n if (nums[i - 1] < nums[i]) {\n rightIdx--;\n } else {\n break;\n }\n }\n\n let totalIncremovableSubarrays = 0;\n totalIncremovableSubarrays += (n - rightIdx) + 1;\n\n let l = 0, r = rightIdx;\n\n while (l <= leftIdx) {\n while (r < n && nums[l] >= nums[r]) {\n r++;\n }\n totalIncremovableSubarrays += (n - r + 1);\n l++;\n }\n\n return totalIncremovableSubarrays;\n};\n```\n\n```ruby []\n# @param {Integer[]} nums\n# @return {Integer}\ndef incremovable_subarray_count(nums)\n n = nums.length\n left_idx = 0\n\n (1...n).each do |i|\n if nums[i - 1] < nums[i]\n left_idx += 1\n else\n break\n end\n end\n\n return (n * (n + 1)) / 2 if left_idx == n - 1\n\n right_idx = n - 1\n\n (n - 1).downto(1) do |i|\n if nums[i - 1] < nums[i]\n right_idx -= 1\n else\n break\n end\n end\n\n total_incremovable_subarrays = 0\n total_incremovable_subarrays += (n - right_idx) + 1\n\n l, r = 0, right_idx\n\n while l <= left_idx\n while r < n && nums[l] >= nums[r]\n r += 1\n end\n total_incremovable_subarrays += (n - r + 1)\n l += 1\n end\n\n total_incremovable_subarrays\n end\n```\n``` Go []\nfunc incremovableSubarrayCount(nums []int) int64 {\n n := len(nums)\n\tleftIdx := 0\n\n\tfor i := 1; i < n; i++ {\n\t\tif nums[i-1] < nums[i] {\n\t\t\tleftIdx++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif leftIdx == n-1 {\n\t\tans := int64(n * (n + 1) / 2)\n\t\treturn ans\n\t}\n\n\trightIdx := int64(n - 1)\n\n\tfor i := n - 1; i > 0; i-- {\n\t\tif nums[i-1] < nums[i] {\n\t\t\trightIdx--\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\ttotalIncremovableSubarrays := int64(0)\n\ttotalIncremovableSubarrays += int64(n - int(rightIdx) + 1)\n\n\tl, r := 0, int(rightIdx)\n\n\tfor l <= leftIdx {\n\t\tfor r < n && nums[l] >= nums[r] {\n\t\t\tr++\n\t\t}\n\t\ttotalIncremovableSubarrays += int64(n - r + 1)\n\t\tl++\n\t}\n\n\treturn totalIncremovableSubarrays\n}\n// package main\n\n// import (\n// \t"fmt"\n// )\n\n// func incremovableSubarrayCount(nums []int) int64 {\n\t\n// }\n\n// func main() {\n// \tnums := []int{1, 2, 3, 4, 5}\n// \tresult := incremovableSubarrayCount(nums)\n// \tfmt.Println(result)\n// }\n```\n``` rust []\nimpl Solution {\n pub fn incremovable_subarray_count(nums: Vec<i32>) -> i64 {\n let n = nums.len();\n let mut left_idx = 0;\n\n for i in 1..n {\n if nums[i - 1] < nums[i] {\n left_idx += 1;\n } else {\n break;\n }\n }\n\n if left_idx == n - 1 {\n let ans = (n as i64 * (n as i64 + 1)) / 2;\n return ans;\n }\n\n let mut right_idx = n as i64 - 1;\n\n for i in (1..n).rev() {\n if nums[i - 1] < nums[i] {\n right_idx -= 1;\n } else {\n break;\n }\n }\n\n let mut total_incremovable_subarrays = 0;\n total_incremovable_subarrays += n as i64 - right_idx + 1;\n\n let mut l = 0;\n let mut r = right_idx as usize;\n\n while l <= left_idx {\n while r < n && nums[l] >= nums[r] {\n r += 1;\n }\n total_incremovable_subarrays += (n as i64 - r as i64 + 1);\n l += 1;\n }\n\n total_incremovable_subarrays\n }\n\n```\n[Instagram](https://www.instagram.com/iamsidharthaa__/)\n[LinkedIn](https://www.linkedin.com/in/sidharth-jain-36b542133)\n**If you find this solution helpful, consider giving it an upvote! Your support is appreciated. Keep coding, stay healthy, and may your programming endeavors be both rewarding and enjoyable!**
4
0
['C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'Ruby', 'JavaScript', 'C#']
4
count-the-number-of-incremovable-subarrays-ii
Well Explained || Two Pointers C++ SOLUTION || AC ✅🔥
well-explained-two-pointers-c-solution-a-bnxs
Intuition\n start (______) end\n ans = start.size() + end.size(); \n Count all subarrays we can make by combining last element of start array and starting elem
satyam_9911
NORMAL
2023-12-23T16:14:01.646106+00:00
2023-12-29T08:22:52.673458+00:00
255
false
# Intuition\n* start (______) end\n* ans = start.size() + end.size(); \n* Count all subarrays we can make by combining last element of start array and starting element of end array.\n* condition : lastElement of start < first Element of end \n* return ans + 1(for empty array)\n \n\n# Code\n```\nclass Solution {\npublic: \n \n #define ll long long \n \n long long incremovableSubarrayCount(vector<int>& nums) {\n \n int n = nums.size(); \n vector<int> start , end ; \n start.push_back(nums[0]); \n \n // store sorted Prefix\n for(int i = 1 ; i < n ; i++){\n if(start.back()<nums[i])start.push_back(nums[i]); \n else break; \n } \n \n end.push_back(nums[n-1]); \n\n // store sorted suffix\n for(int i = n-2 ; i>=0 ; i--){\n if(end.back()>nums[i])end.push_back(nums[i]); \n else break; \n } \n \n // if both coincide means whole array is sorted \n if(start.size()+end.size()>n) return 1ll*(n)*(n+1)/2; \n \n ll ans = start.size() + end.size(); \n int i = 0 , j = 0; \n \n reverse(end.begin() , end.end()); \n \n // count subarrays whose last element of prefix is smaller than \n // starting element of suffix array\n while( i < start.size() and j < end.size()){ \n if(start[i]<end[j])ans+=(end.size()-j) , i++; \n else j++;\n }\n \n // +1 for empty array\n return ans + 1;\n \n }\n};\n```
4
0
['Two Pointers', 'Greedy', 'Sorting', 'C++', 'Java']
3
count-the-number-of-incremovable-subarrays-ii
Edge Ascend ➡⬅ || T.C : O(n) || S.C : O(1)
edge-ascend-tc-on-sc-o1-by-algorhythmic_-9cq0
Intuition\n Describe your first thoughts on how to solve this problem. \n"Simplified Strategy: Finding Ascending Subarrays at Both Ends"\n\n- Rather than counti
AlgoRhythmic_Minds
NORMAL
2023-12-24T16:51:51.929656+00:00
2023-12-24T16:51:51.929676+00:00
120
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**"Simplified Strategy: Finding Ascending Subarrays at Both Ends"**\n\n- Rather than counting subarrays to reorder the remaining array, let\'s take a different route. We\'ll directly figure out the number of possible increasing subarrays at the leftmost and rightmost corners.\n\n- All we need to do is found the leftmost and rightmost increasing subarrays. Once we\'ve got them, it\'s straightforward to count the ascending subarrays from these segments.\n\n- Let\'s break down this idea using the example in the "Approach" section.**Approach** part.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- let say, given array {**7,8,6,9,10**}**Bold**\n- our leftmost increasing subarray is : {**7,8**}\n- our rightmost increasing subarray is : {**6,9,10**}\n- the possible subarrays for left part are :\n - {7}\n - {7,8}\n- the possible subarrays for right part are :\n - {6,9,10}\n - {9,10}\n - {10} \n- the possible subarrays from combining them are :\n - {7,9,10}\n - {7,8,9,10}\n - {7,10}\n - {7,8,10}\n- the possible subarray which does not include any element i.e. :\n - {}\n- ans=10.\n- total possible ascending arrays after removing any subarray part = (size of first ascending part) + (size of second ascending part) + (their combined ascending ascending arrays.) + 1.\n- **NOTE** : if ending of left part of ascending subarray lies after the starting of right part of ascending subarray means the given array is already in ascending order (e.g. : {1,2,3,4}),so simply return number of possible subarray from it i.e. **(n*(n+1))/2**\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 long long incremovableSubarrayCount(vector<int>& nums) {\n long long ans=1,n=nums.size();\n long long i=0,j=n-1;\n while(i<nums.size()-1 && nums[i]<nums[i+1]) i++;\n int e=i;\n while(j>0 && nums[j]>nums[j-1]) j--;\n int s=j;\n ans+=e+1;\n ans+=n-s;\n if(e>=s) return (1LL*n*(n+1))/2;\n j=n-1;\n while(e>=0 && j>=s){\n if(nums[e]<nums[j]) ans+=e+1,j--;\n else(e--);\n }\n return ans;\n }\n};\n```\n\n---\n\n**If you find this solution helpful, consider giving it an upvote! Your support is appreciated. Keep coding, stay healthy, and may your programming endeavors be both rewarding and enjoyable!**\n\nJoin our WhatsApp Channel\nCheck out the link in comments\n\n\uD83D\uDE80 Elevate your coding skills to new heights! \uD83C\uDF1F Join our exclusive WhatsApp community channel dedicated to daily LeetCode challenges, interview problem-solving, and cutting-edge contest solutions.\n\n\uD83D\uDD0D Explore the world of Algorithms and unravel the secrets of Data Structures with us. \uD83E\uDDE0\uD83D\uDCBB\n\n\uD83C\uDFAF What\'s in for you?\n\nDaily LeetCode problems to sharpen your coding prowess.\nInterview problem discussions to ace your tech interviews.\nContest solutions and optimized approaches for a deeper understanding.\nShare new approaches, optimized solutions, and DSA tricks.\nBuild a strong logic foundation at no cost!\n\uD83E\uDD1D Be part of our coding journey, where we learn and grow together. \uD83D\uDCA1\uD83D\uDCBB
3
0
['Two Pointers', 'C++']
1
count-the-number-of-incremovable-subarrays-ii
[Python3] 2-pass
python3-2-pass-by-ye15-i4y6
\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n ans = 0\n n = len(nums)\n suffix = [0]*n\n for
ye15
NORMAL
2023-12-23T16:02:21.491754+00:00
2023-12-23T16:02:21.491787+00:00
206
false
```\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n ans = 0\n n = len(nums)\n suffix = [0]*n\n for i in range(n-1, 0, -1): \n if i == n-1 or nums[i] < nums[i+1]: \n ans += 1\n suffix[i] = nums[i]\n else: break \n for i, x in enumerate(nums): \n if i == 0 or nums[i-1] < nums[i]: \n if i < n-1: ans += 1\n k = bisect_right(suffix, nums[i], i+2)\n ans += max(0, n - k)\n else: break \n return ans+1\n```
3
2
['Python3']
0
count-the-number-of-incremovable-subarrays-ii
Binary search ✅ | C++| Beginner friendly💯
binary-search-c-beginner-friendly-by-pro-pn76
CodeComplexity Time complexity: O(NlogN) Space complexity: O(1)
procrastinator_op
NORMAL
2025-02-03T14:45:38.354765+00:00
2025-02-03T14:45:38.354765+00:00
62
false
# Code ```cpp [] #define ll long long class Solution { public: long long incremovableSubarrayCount(vector<int>& nums) { int n = nums.size(); int i = n-1; // from 0 till i arr is sorted for(int k=0; k<n-1; k++){ if(nums[k] >= nums[k+1]){ i = k; break; } } int j = 0; // from j+1 till end arr is sorted for(int k=n-1; k>0; k--){ if(nums[k] <= nums[k-1]){ j = k-1; break; } } ll cnt = 0; for(int k=j; k<n; k++){ ll nxt = k+1<n ? nums[k+1] : 1e10; int r = min(k-1, i); int l = 0; int ans = -1; while(l <= r){ // binary search on answer int m = (l + r)/2; if(nums[m] >= nxt) r = m - 1; else{ ans = max(ans, m); l = m + 1; } } cnt += (ans + 2); } return cnt; } }; ``` # Complexity - Time complexity: O(NlogN) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ -->
2
0
['Array', 'Binary Search', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
C++ - easy to understand 2 pointer
c-easy-to-understand-2-pointer-by-roadto-8av6
Intuition and Approach\n Describe your first thoughts on how to solve this problem. \nhow many arrays can we remove from nums so that the reulsting array is str
roadToQuant
NORMAL
2024-11-30T02:10:17.699095+00:00
2024-11-30T02:10:17.699124+00:00
113
false
# Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nhow many arrays can we remove from nums so that the reulsting array is strictly increasing.\n\nsince we are talking about subarrays the removed array must be contigous, thus we can think of our nums array as [NR1 | R | NR2 ], where NR = not removed, and R = removed. What we really want to do is just find the total number of R s.t NRi is a valid strictly increasing array, and further that the concatination [NR1 NR2] is a strictly increasing array. We can tackle this by ensuring NR1 is the maximal strictly increasing prefix and NR2 is the maximal strictly increasing suffix.\n\nHow does this help us?\n\nWhat we jsut did was figure out the SMALLEST subarray that isnt strictly increasing(R), and the BIGGEST strictly increasing prefix(NR1) and suffix(NR2), this means giving a value of the \'R\' subarray to either NR1 or NR2 will not be a valid incremovable subarray. Now we have the basis for our algorithm, just add the rightmost values in the prefix and the left most values to the suffix in a valid way s.t [NR1 NR2] is still valid and increment the count as you do this.\n\nWe can utilize the fact that NR1 and NR2 are both sorted, thus I can take a value in our prefix and find the first valid index in NR2 s.t [NR1 NR2] is still strictly increasing, by using binary search..\n\nTheres more to be done here though, if I know prefix[i] < prefix[i + 1] and suffix[i] <suffix[i + 1], then I can utlize the fact that if prefix[i] >= suffix[i] (see NOTE 1*), then prefix[i + 1] >= suffix[i], thus theres no reason for me to ever consider suffix[i] in future checks.. this is where two pointers comes in and we improve on the logarithmic binary search approach\n\n\n\nNOTE 1: suffix and prefix are independantly sorted, this is why we even have to do this part, nothing is forcing pref[i] to be less than any value in our suffix\n# Visual + an additional case to include\n\nwith numbers:\n3) nums = [1, 3, 1, 4, 3, 2, 4]\n4) nums = [1, 3] (NR1) | [1, 4, 3](R) | [2, 4](NR2)\n\nprefix[:0] included in NR1\n-> [1] [2, 1, 4, 3] [2, 4] and [1] [2, 3, 1, 4, 3, 2] [4] and \n[1] [1, 2, 1, 4, 3, 2, 4] [] are valid. count = 3\n\nprefix[:1] included in NR1\n-> [1, 2] [1, 4, 3, 2] [4] and [1, 2] [1, 4, 3, 2, 4] [] are valid, count = 3 + 2 (note 2 in the suffix is not valid since NR1NR2 need to be strictly increasing)\n\nALSO note that something we havent calculated is having our prefix = [], as a result add len(nums) - suffix len + 1 to count.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(p) for prefix (p == len(prefix))\nO(s) for suffix (s == len(suffix))\nO(s + p) for enumeration of valid \'R\' arrays\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n long long n = nums.size(), pi = 0;\n while (pi < n - 1 && nums[pi] < nums[pi + 1]) {\n pi++;\n }\n // pi = last index of prefix (inclusive)\n if (pi == n - 1) return n * (n + 1) / 2;\n\n int si = n - 1;\n while (si > 0 && nums[si] > nums[si - 1]) {\n si--;\n }\n // si = first index of suffix (inclusive)\n\n long long count = n - si + 1; //subarrays that use NO Prefix := suffixes(nums[i in (si, n)]) = n - si (+ 1 for []) \n\n for (int l = 0; l <= pi; l++) {\n // for index l of prefix, see how many suffixes are greater\n // pref[l + 1] > pref[l] (since its a valid pref), so if si is not valid for prefix it wont be valid for l + 1\n while (si < n && nums[si] <= nums[l]) {\n si++;\n }\n //cout << "pref index = " << l << " value to add = " << (n - si) << endl;\n count += (n - si + 1);\n }\n return count;\n }\n};\n```
2
0
['Two Pointers', 'C++']
2
count-the-number-of-incremovable-subarrays-ii
Simple c++ Solution using Binary Search and Greedy approach
simple-c-solution-using-binary-search-an-m53a
Intuition\n Describe your first thoughts on how to solve this problem. \nWe will be using Binary Search and Greedy approach\n# Approach\n Describe your approach
hashwhile1
NORMAL
2023-12-28T11:34:01.294509+00:00
2023-12-28T11:34:01.294534+00:00
57
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will be using Binary Search and Greedy approach\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet suppose that the array is having following elements : a , b, c ,d ,e ,f ,g. Now we know that we can pick out only "one" subarray from this array so that resulting array is strictly increasing. So we can pick out either from first i.e [a,b,c] if d<e<f<g . Lets suppose that we pick out [c,d] from middle and we know that a<b and e<f<g and now we need to check upper bound of a and that of b in the subarray [e,f,g] so that we can ensure that resulting array is strictly increasing, lets say that in these remaining elements a<f but a>e so [a],[a,f,g], [a,g] can form answer and similarly if we check for b such that b>f and b<g so [a,b] and [a,b,g] can form answers.\n# Complexity\n- Time complexity: O(N log 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 long long incremovableSubarrayCount(vector<int>& nums) {\n int n=nums.size();\n long long ans=0;\n vector<int>temp1,temp2;\n int i=0,j=n-1;\n while(i<n-1 ){\n temp1.push_back(nums[i]);\n if(nums[i]>=nums[i+1])break;\n i++;\n }\n if(i==n-1)return ans=(long long)(n*(n+1)/2);\n while(j>0 ){\n temp2.push_back(nums[j]);\n if(nums[j]<=nums[j-1])break;\n j--;\n }\n \n reverse(temp2.begin(),temp2.end());\n int n1=temp1.size(),n2=temp2.size();\n cout<<n1<<" "<<n2<<endl;\n for(int i=0;i<n1;i++){\n int index=upper_bound(temp2.begin(),temp2.end(),temp1[i])-temp2.begin();\n ans+=(n2-index+1);\n }\n ans+=(n2+1);\n return ans;\n }\n};\n```
2
0
['Binary Search', 'Greedy', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
C++ Easy Explanation || Greedy || Binary Search || O(N LogN)
c-easy-explanation-greedy-binary-search-z5zwo
Intuition\n Describe your first thoughts on how to solve this problem. \n\nGreedy Approach\n\nJust find the last index (ind) after which the array is strictly i
ayushchandra73
NORMAL
2023-12-23T20:19:49.452227+00:00
2023-12-23T20:19:49.452244+00:00
243
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n**Greedy Approach**\n\nJust find the last index (ind) after which the array is strictly increasing.\nNow find the first index(indf) where the array becomes equal or decreasing for the first time.\n\nNow you have to remove subarray with start index varying between(0 to indf) and last index varying from (ind-1 to n-1). \n# Approach\n<!-- Describe your approach to solving the problem. -->\nKeep in note that if we are removing the subarray from index=i to index=j then nums[i-1]<nums[j+1].\nTo find this index of (j+1) we are using binary search (upper bound) since the elements are strictly increasing after ind.\n\n**Consider a testcase nums[]={2,4,2,2,3,4,2,3}**\nHere ind=6 and indf=1\nNow we can delete subarray from starting from (0 to 1) and ending at (5 to 7) so that the remaining arraay is strictly increasing.\n\nif(ind==0) implies array is strictly increasing so just use the number of subarrays as answer.\n# Complexity\n- Time complexity: O(N log 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 long long incremovableSubarrayCount(vector<int>& nums)\n {\n int n=nums.size();\n int ind=n-1;// find last index after which the array is increasing strictly\n for(int i=n-1;i>=1;i--)\n {\n if(nums[i]>nums[i-1])\n {\n ind--;\n }\n else break;\n }\n if(ind==0)\n {\n return n*1ll*(n+1)/2;\n }\n int indf=0;// find first index where the array becomes decreasing\n for(int i=0;i<n-1;i++)\n {\n if(nums[i]>=nums[i+1]) break;\n indf++;\n }\n int prev=-1;\n long long ans=0;\n for(int i=0;i<=(indf+1<n?(indf+1):n);i++)\n {\n int index=upper_bound(nums.begin()+ind,nums.end(),prev)-nums.begin()-1;\n ans=ans+(n-index)*1ll;\n prev=nums[i];\n }\n return ans;\n }\n};\n // Hope U like it! Do Upvote!!\n\n```
2
0
['Array', 'Binary Search', 'Greedy', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
Easy Solution || O(n) time || O(1) space
easy-solution-on-time-o1-space-by-nitlee-o7d0
Intuition\n Describe your first thoughts on how to solve this problem. \n\nTry to find the valid subarrays, or the combination of two valid subarrays which is v
nitleet12
NORMAL
2023-12-23T18:14:43.383843+00:00
2023-12-23T18:14:43.383861+00:00
31
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. \n-->\nTry to find the valid subarrays, or the combination of two valid subarrays which is valid.\nFind two sorted subarrays: \n1. starting from index 0\n2. starting from index i, but ending at last index\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOn getting the sorted arrays, \nLet [0,left] and [right,n-1] are sorted subarrays.\n\nOnly case where **right<left**, is left = n-1.\nIn this case all subarrays formed will be in increasing order.\nSo `return (n*(n-1))/2`\n\nleft<right\n1 -> empty subarray\n1+left -> valid subarrays starting from 0\nn-right -> valid subarrays ending at n-1\ncount = 1 + (1+left) + (n-right);\nUse two pointer approach,\nfor each i in [0,left], adjust right so that nums[i] < nums[right], add n-right to count\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 {\n public long incremovableSubarrayCount(int[] nums) {\n int n=nums.length,left=0,right=n-1;\n for(int i=1;i<n;i++){\n if(nums[i]>nums[i-1]) left=i;\n else break;\n }\n if(left==n-1) return (1l*n*(n+1))/2;\n for(int i=n-2;i>=0;i--){\n if(nums[i]<nums[i+1]) right=i;\n else break;\n }\n long count = 1+(left+1)+(n-right);\n for(int i=0;i<=left;i++){\n while(right<n && nums[right]<=nums[i]) right++;\n count += n-right;\n }\n return count;\n }\n}\n```
2
0
['Two Pointers', 'Suffix Array', 'Java']
0
count-the-number-of-incremovable-subarrays-ii
🔥Beats 100%, 89ms 🥰 Full explained 🧐🎉
beats-100-89ms-full-explained-by-lc-rekr-5k91
\n\n# Approach\nWe care about how much increasing numbers we have from the beginning and from the end (decreasing, if going from the end). We don\'t care about
lc-rekrul-lc
NORMAL
2023-12-23T17:40:12.569585+00:00
2023-12-23T17:42:09.596177+00:00
85
false
![image.png](https://assets.leetcode.com/users/images/e7315409-93f3-494f-a898-4159dd5c0df7_1703351850.4394066.png)\n\n# Approach\nWe care about how much increasing numbers we have from the beginning and from the end (decreasing, if going from the end). We don\'t care about increasing sequences in the middle, because we can separate it from other numbers only by removing from the left and from the right, which we can\'t do\n\nIf after you count the number of increasing numbers after going from the beginning of `nums` (variable `count1`), it\'s equal to `n`, then the answer is $$n * (n + 1) / 2$$ \n(look at example 1)\n\n\nIf not - going further. Count the number of decreasing numbers going from the end of `nums` (variable `count2`). \n\n\nOut current answer is `1(empty array) + count1 + count2`\n\nThen we have to count how much combinations of incremovable arrays we can get with numbers in the beginning and in the end. We use two pointers here. And also here we use variables `last1` and `last2`, that represents the end of the increasing sequence in the beginning and the beginning of the increasing sequence in the end (we went from right to left, so the last element is the beginning)\n\nSo how do we count that combinations?.. Let\'s say we make variables `indL = la1` (the greatest element in the increasing sequence from the beginning) and `IndR = n - 1` (the greatest element in the increasing sequence from the end). We go `while (indL >= 0 && indR >= la2)` \nIf current element in the end (`nums[indR]`) is greater that current element in the beginning (`nums[indL]`), it means that we can add `(indL + 1)` combinations to the answer\nAnd after that we make number in the end lower by decreasing `indR` by 1. \nIf current element in the end is lower or equal - we make element in the beginning lower by decreasing `indL` by 1\n\nAfter end of while we return our variable `ans`\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n\n // \uD83C\uDF38 Upvote, please \uD83C\uDF38\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n // \uD83C\uDF38 Upvote, please \uD83C\uDF38\n\n long long n = nums.size();\n if (n == 1)\n return 1;\n\n int count1 = 1, la1 = -1;\n for (int i = 1; i < n; ++i) {\n if (nums[i] <= nums[i - 1]) {\n la1 = i - 1;\n break;\n }\n count1++;\n }\n if (count1 == n)\n return (n * (n + 1)) / 2;\n\n int count2 = 1, la2 = -1;\n for (int i = n - 2; i >= 0; --i) {\n if (nums[i] >= nums[i + 1]) {\n la2 = i + 1;\n break;\n }\n count2++;\n }\n\n long long ans = count1 + count2 + 1;\n int indL = la1, indR = n - 1;\n while (indL >= 0 && indR >= la2) {\n if (nums[indL] < nums[indR]) {\n ans += indL + 1;\n indR--;\n }\n else {\n indL--;\n }\n }\n\n // \uD83C\uDF38 Upvote, please \uD83C\uDF38\n return ans;\n // \uD83C\uDF38 Upvote, please \uD83C\uDF38\n }\n};\n```
2
0
['Array', 'Two Pointers', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
C++ Commented Explanation
c-commented-explanation-by-roundspecs-ix43
Intuition\nA[l:r] is incremovable iff\n- A[0:l] is strictly increasing (Call it left part)\n- A[r:n] is strictly increasing (Call it right part)\n- A[l-1]<A[r]\
roundspecs
NORMAL
2023-12-23T16:32:21.996915+00:00
2023-12-23T16:32:21.996943+00:00
44
false
# Intuition\n`A[l:r]` is incremovable iff\n- `A[0:l]` is strictly increasing (Call it left part)\n- `A[r:n]` is strictly increasing (Call it right part)\n- `A[l-1]`<`A[r]`\n\n# Approach\n- Find the longest possible left part\n- Find the longest possible right part\n- For each element of one part, do binary search on the other\n\n# Complexity\n- Time complexity:\n$$O(n\\log{n})$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n\n long long n=nums.size();\n \n // The array is strictly increasing till(not including) l\n int l=1;\n while(l<n && nums[l-1]<nums[l]) l++;\n\n // l==n only if the entire array is strictly increasing\n // in that case, all sub-arrays are incremovable\n // Number of sub-arrays = n*(n+1)/2\n if(l==n) return n*(n+1)/2;\n\n // the array is strictly increasing from(including) r\n int r=n-1;\n while(r>0 && nums[r-1]<nums[r]) r--;\n \n // The only case where l>r, is when the entire array\n // is strictly increasing.\n // Since that case has already been handle,\n // for the rest of the code l<=r\n\n // Counting how many sub-arrays are incremovable\n long long count=0;\n \n // If left part is empty\n cnt += n-r+1;\n\n // If left part is not empty\n for(int i=0; i<l; i++) {\n int k = nums.end() - upper_bound(nums.begin()+r,nums.end(),nums[i]);\n cnt += k+1;\n }\n \n return cnt;\n }\n};\n```
2
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
💥💥 Beats 100% on runtime and memory [EXPLAINED]
beats-100-on-runtime-and-memory-explaine-6hdr
IntuitionWe need to identify parts of the array where elements are strictly increasing. The challenge is to find subarrays that can be removed to make the remai
r9n
NORMAL
2025-01-21T02:47:56.423264+00:00
2025-01-21T02:47:56.423264+00:00
8
false
# Intuition We need to identify parts of the array where elements are strictly increasing. The challenge is to find subarrays that can be removed to make the remaining array strictly increasing. # Approach First, I find the point where the array stops being strictly increasing from the left (prefix) and the point where it stops being strictly increasing from the right (suffix). Then, I check all elements before the prefix and calculate how many subarrays can be removed without breaking the strictly increasing property, while also checking the remaining part from the suffix. # Complexity - Time complexity: O(n), where n is the number of elements in the array. We iterate over the array a few times (just twice in this case), which makes it very efficient. - Space complexity: O(1), since we only use a few extra variables to track indices and pointers, and we don’t use any extra data structures like arrays or lists. The only space used is for the input array. # Code ```rust [] impl Solution { pub fn incremovable_subarray_count(nums: Vec<i32>) -> i64 { let n = nums.len(); if n == 1 { return 1; } let mut i = 0; while i < n - 1 && nums[i + 1] > nums[i] { i += 1; } let prefix_idx = i; if prefix_idx == n - 1 { return (n as i64) * (n as i64 + 1) / 2; } i = n - 1; while i > 0 && nums[i - 1] < nums[i] { i -= 1; } let suffix_idx = i; let mut ptr2 = suffix_idx; let mut res = 0; for ptr1 in 0..=prefix_idx { while ptr2 < n && nums[ptr2] <= nums[ptr1] { ptr2 += 1; } res += (n - ptr2) as i64 + 1; } res + (n - suffix_idx) as i64 + 1 } } ```
1
0
['Two Pointers', 'Binary Search', 'Dynamic Programming', 'Stack', 'Brainteaser', 'Suffix Array', 'Monotonic Stack', 'Binary Tree', 'Rust']
0
count-the-number-of-incremovable-subarrays-ii
O(N) Time|O(1) Space|EASY|CPP|WELL_EXPLAINED
on-timeo1-spaceeasycppwell_explained-by-oikbs
Intuition\nLooking at he constraints and taking help from LC 1574\n\n# Approach\nif the complete array is strictly increasing, then we can remove all the subarr
resilient_nik9
NORMAL
2023-12-26T13:25:56.794056+00:00
2023-12-26T13:34:23.673013+00:00
82
false
# Intuition\nLooking at he constraints and taking help from LC 1574\n\n# Approach\nif the complete array is strictly increasing, then we can remove all the subarrays that can be formed using the elements of the array.\n\ntill this i we have elements in strictly increasing order. now all the elements after this ith element is a single subarray that can be removed and our remaining elements till i will form a strictly increasing subarray. all these elements after i can take all the elements till 1 one by one and form a subarray that can be removed.\n\neg. 1 2 3 4 5 3 4 1 6 2 --> we have strictly increasing till index 4, and no of elements is 5. now subarray 3 4 1 6 2 can take elements from index 4 to 1. so total subarrays will be 4 + (subarray itself) = 5 i.e. i + 1\nthese subarrays that are being removed are kind of right subarrays since they start from right\n\nnow we check from the right side and calc subarrays based on similar above logic\nthese subarrays that are being removed are kind of left subarrays since they start from left\n\nnow we calc subarrays in the middle\n\nwe start form 0th index and move our \'i\' till the index where we had our last element of the strictly increasing subarray\nfor the right part, our j will move from the first element of the strictly increasing subarray and move till the end\n\nnow for every \'i\' we find a \'j\' which is >, now all the elements between this \'i\' and \'j\' is a single subarray that can be removed. also this subarray can take elements from \'j\' till \'n - 1\', these subarrays will be kind of middle subarrays starting in between and ending in between\n\nwe do this for every \'i\' and \'j\' pair we find where \'j\' > \'i\'\n\nat last we add 1 which is for the case when we remove all the elements and have an empty subarray\n\n# Complexity\n- Time complexity:\nO(N) -- we first visit the array twice through two while loops to find \'i\' and \'j\' which is O(N).\nthen we iterate again from i = 0 to leftcap (\'i\' previously found) and simultaneously move \'j\' till n. overall it is traversing the complete array in worst case. hence O(N).\n\n- Space complexity:\nO(1) -- we just use variables which takes constant space\n\n# Code\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n int n = nums.size(), i = 0, j = n - 1, leftcap = 0;\n long long res = 0;\n while(i < n - 1 && nums[i] < nums[i + 1]){\n i++;\n }\n // if the complete array is strictly increasing, then we can remove all the subarrays that can be formed using the elements of the array\n if(i == n - 1){\n return (long long)(n * (n + 1)) / 2;\n }\n // till this i we have elements in strictly increasing order. now all the elements after this ith element is a single subarray that can be removed and our remaining elements till i will form a strictly increasing subarray. all these elements after i can take all the elements till 1 one by one and form a subarray that can be removed.\n // eg. 1 2 3 4 5 3 4 1 6 2 --> we have strictly increasing till index 4, and no of elements is 5. now subarray 3 4 1 6 2 can take elements from index 4 to 1. so total subarrays will be 4 + (subarray itself) = 5 i.e. i + 1\n // these subarrays that are being removed are kind of right subarrays since they start from right\n res = i + 1;\n leftcap = i;\n // now we check from the right side and calc subarrays based on similar above logic\n // these subarrays that are being removed are kind of left subarrays since they start from left\n while(j > 0 && nums[j] > nums[j - 1]){\n j--;\n }\n res += (n - j);\n i = 0;\n // now we calc subarrays in the middle\n // we start form 0th index and move our \'i\' till the index where we had our last element of the strictly increasing subarray\n // for the right part, our j will move from the first element of the strictly increasing subarray and move till the end\n // now for every \'i\' we find a \'j\' which is >, now all the elements between this \'i\' and \'j\' is a single subarray that can be removed. also this subarray can take elements from \'j\' till \'n - 1\', these subarrays will be kind of middle subarrays starting in between and ending in between\n // we do this for every \'i\' and \'j\' pair we find where \'j\' > \'i\'\n while(i <= leftcap && i < j && j < n){\n if(nums[i] < nums[j]){\n res += ((n - j - 1) + 1);\n i++;\n }\n else{\n j++;\n }\n }\n // at last we add 1 which is for the case when we remove all the elements and have an empty subarray\n return res + 1;\n }\n};\n```
1
1
['C++']
1
count-the-number-of-incremovable-subarrays-ii
Easy Binary search
easy-binary-search-by-piyuxh_01-0yx5
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
Piyuxh_01
NORMAL
2023-12-25T17:16:49.491451+00:00
2023-12-25T17:16:49.491474+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 {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n int n = nums.size();\n int i;\n for (i = 0; i < n - 1; ++i) {\n if (nums[i] >= nums[i + 1]) {\n break;\n }\n }\n\n if (i == n - 1) {\n return ((n ) * (n + 1)) / 2;\n }\n\n int j;\n for (j = n - 1; j > 0; --j) {\n if (nums[j - 1] >= nums[j]) {\n break;\n }\n }\n\n int l = 0;\n int r = j;\n long long res = 1 + n - j;\n\n while (l <= i) {\n while (r < n && nums[l] >= nums[r]) {\n ++r;\n }\n res += 1 + n - r;\n ++l;\n }\n\n return res;\n }\n};\n```
1
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
🔥2 Approaches || 💯BinarySearch || ⚡O(1) SC || 💯PrefixSuffix || ✅🌟Clean & Best Code
2-approaches-binarysearch-o1-sc-prefixsu-i8a2
Connect with me on LinkedIN : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n\n# Complexity\n\n- Time complexity:\nO(n log n) for Approach 1\nO(n)
aDish_21
NORMAL
2023-12-23T20:11:05.985480+00:00
2023-12-24T17:10:45.500456+00:00
242
false
## Connect with me on LinkedIN : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n\n# Complexity\n```\n- Time complexity:\nO(n log n) for Approach 1\nO(n) for Approach 2\n\n- Space complexity:\nO(1)\n```\n\n# Code\n## PLease Upvote if it helps\uD83E\uDD17\n# **1st Approach (Using BinarySearch):-**\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n int n = nums.size(), pre = 0, suff = n - 1;\n long ans = 0;\n for(int i = 1 ; i < n ; i++){\n if(nums[i] > nums[i - 1])\n pre = i;\n else\n break;\n }\n for(int i = n - 2 ; i >= 0 ; i--){\n if(nums[i] < nums[i + 1])\n suff = i;\n else\n break;\n }\n ans += ((n - pre - 1) > 0 ? 1 : 0) + pre + 1;\n ans += ((suff > 0) ? 1 : 0) + n - suff - 1;\n for(int i = 0 ; i <= pre ; i++){\n int ind = upper_bound(nums.begin() + max(i, suff), nums.end(), nums[i]) - nums.begin();\n if(ind != n && ind != i)\n ans += ((ind - i - 1) > 0 ? 1 : 0) + (n - ind - 1);\n }\n return ans;\n }\n}; \n```\n# 2nd Approach (Using Two Pointers):-\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n int n = nums.size(), pre = 0, suff = n - 1;\n long ans = 0;\n for(int i = 1 ; i < n ; i++){\n if(nums[i] > nums[i - 1])\n pre = i;\n else\n break;\n }\n for(int i = n - 2 ; i >= 0 ; i--){\n if(nums[i] < nums[i + 1])\n suff = i;\n else\n break;\n }\n ans += (n - suff) + ((suff > 0) ? 1 : 0);\n for(int i = 1 ; i <= pre + 1 ; i++){\n while(suff < n && nums[suff] <= nums[i - 1])\n suff++;\n ans += (n - suff) + ((suff - i > 0) ? 1 : 0);\n }\n return ans;\n } \n}; \n```
1
0
['Two Pointers', 'Binary Search', 'Prefix Sum', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
Python simple counting solution, beats 100%, O(n*log(n))
python-simple-counting-solution-beats-10-els8
\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n res = 0\n n = len(nums)\n i = 0\n j = n-1\n
25points
NORMAL
2023-12-23T18:56:33.916629+00:00
2023-12-23T18:56:33.916657+00:00
151
false
```\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n res = 0\n n = len(nums)\n i = 0\n j = n-1\n # left strictly increasing array starts from 0\n while i<n-1 and nums[i] < nums[i+1]:\n i += 1\n # right strictly increasing array that ends in n-1\n while 0<j and nums[j-1] < nums[j]:\n j -= 1\n # if nums is strictly increasing, return all subarrays\n if j<=i:\n return (n+1)*n//2\n # for diminishing left array (from index 0), find insert idx in right array\n # every number starts from the insert idx represents a solution: [0...i, k...n-1]\n # including the right empty array, [0...i, ]\n while i >= 0:\n curr = nums[i]\n k = bisect.bisect(nums, curr, lo=j)\n res += (n-k+1)\n i -= 1\n # when left array becomes empty, each number in right array also represents a solution\n # [, j...n-1] including [,], the empty left and empty right\n res += (n-j+1) \n return res\n\n \n \n \n \n \n \n```
1
0
['Python3']
0
count-the-number-of-incremovable-subarrays-ii
C++ || Комментарии на русском || RUS_comments
c-kommentarii-na-russkom-rus_comments-by-xb65
Intuition\n Describe your first thoughts on how to solve this problem. \n\u0417\u0430\u0434\u0430\u0447\u0430 \u0437\u0430\u043A\u043B\u044E\u0447\u0430\u0435\u
bakhtiyarzbj
NORMAL
2023-12-23T16:59:05.919727+00:00
2023-12-23T16:59:24.971115+00:00
13
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\u0417\u0430\u0434\u0430\u0447\u0430 \u0437\u0430\u043A\u043B\u044E\u0447\u0430\u0435\u0442\u0441\u044F \u0432 \u043D\u0430\u0445\u043E\u0436\u0434\u0435\u043D\u0438\u0438 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u0432 \u0432 \u043C\u0430\u0441\u0441\u0438\u0432\u0435 nums, \u043F\u0440\u0438 \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0438 \u043A\u043E\u0442\u043E\u0440\u044B\u0445 \u043C\u0430\u0441\u0441\u0438\u0432 \u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0441\u044F \u0441\u0442\u0440\u043E\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0438\u043C. \u041F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432 \u043C\u043E\u0436\u043D\u043E \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0438\u0442\u044C \u043A\u0430\u043A \u043D\u0435\u043F\u0440\u0435\u0440\u044B\u0432\u043D\u0443\u044E \u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u0432 \u043C\u0430\u0441\u0441\u0438\u0432\u0435. \u041A\u043B\u044E\u0447\u0435\u0432\u0430\u044F \u0438\u0434\u0435\u044F \u0440\u0435\u0448\u0435\u043D\u0438\u044F \u0437\u0430\u043A\u043B\u044E\u0447\u0430\u0435\u0442\u0441\u044F \u0432 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0438 \u0434\u0432\u0443\u0445 \u0443\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u0435\u0439 \u0438 \u0431\u0438\u043D\u0430\u0440\u043D\u043E\u0433\u043E \u043F\u043E\u0438\u0441\u043A\u0430.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C \u0434\u0432\u0430 \u0443\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044F r \u0438 i. \u0423\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044C r \u0431\u0443\u0434\u0435\u0442 \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u0442\u044C \u043F\u0440\u0430\u0432\u0443\u044E \u0433\u0440\u0430\u043D\u0438\u0446\u0443 \u0442\u0435\u043A\u0443\u0449\u0435\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0435\u0433\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u0430. \u041D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 r \u0443\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u043C \u0432 1.\n2. \u0418\u0442\u0435\u0440\u0438\u0440\u0443\u0435\u043C\u0441\u044F \u043E\u0442 \u043D\u0430\u0447\u0430\u043B\u0430 \u043C\u0430\u0441\u0441\u0438\u0432\u0430 \u0434\u043E \u0442\u0435\u0445 \u043F\u043E\u0440, \u043F\u043E\u043A\u0430 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B \u0441\u0442\u0440\u043E\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0442 (\u043F\u043E\u043A\u0430 nums[r] > nums[r - 1]). \u042D\u0442\u043E \u043F\u043E\u0437\u0432\u043E\u043B\u044F\u0435\u0442 \u043D\u0430\u043C \u043D\u0430\u0439\u0442\u0438 \u043F\u0440\u0430\u0432\u0443\u044E \u0433\u0440\u0430\u043D\u0438\u0446\u0443 \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0435\u0433\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u0430.\n3. \u0415\u0441\u043B\u0438 r \u0434\u043E\u0441\u0442\u0438\u0433\u043B\u043E \u043A\u043E\u043D\u0446\u0430 \u043C\u0430\u0441\u0441\u0438\u0432\u0430, \u0442\u043E \u0432\u0435\u0441\u044C \u043C\u0430\u0441\u0441\u0438\u0432 \u044F\u0432\u043B\u044F\u0435\u0442\u0441\u044F \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0438\u043C, \u0438 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0432\u043E\u0437\u043C\u043E\u0436\u043D\u044B\u0445 \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u0432 \u0440\u0430\u0432\u043D\u043E (n * (n + 1)) / 2, \u0433\u0434\u0435 n - \u0434\u043B\u0438\u043D\u0430 \u043C\u0430\u0441\u0441\u0438\u0432\u0430.\n4. \u0418\u043D\u0430\u0447\u0435, \u043C\u044B \u043D\u0430\u0447\u0438\u043D\u0430\u0435\u043C \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u044E \u043E\u0442 \u043A\u043E\u043D\u0446\u0430 \u043C\u0430\u0441\u0441\u0438\u0432\u0430 (\u043E\u0442 i = n-1), \u0438\u0449\u0435\u043C \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u044B, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u043C\u043E\u0433\u0443\u0442 \u0431\u044B\u0442\u044C \u0443\u0434\u0430\u043B\u0435\u043D\u044B, \u0447\u0442\u043E\u0431\u044B \u0441\u0434\u0435\u043B\u0430\u0442\u044C \u043C\u0430\u0441\u0441\u0438\u0432 \u0441\u0442\u0440\u043E\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0438\u043C.\n5. \u0414\u043B\u044F \u043A\u0430\u0436\u0434\u043E\u0433\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 nums[i] \u043F\u0440\u043E\u0432\u0435\u0440\u044F\u0435\u043C, \u043C\u043E\u0436\u043D\u043E \u043B\u0438 \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432, \u043D\u0430\u0447\u0438\u043D\u0430\u044F \u0441 \u043D\u0435\u0433\u043E, \u0447\u0442\u043E\u0431\u044B \u0441\u0434\u0435\u043B\u0430\u0442\u044C \u043C\u0430\u0441\u0441\u0438\u0432 \u0441\u0442\u0440\u043E\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0438\u043C. \u0414\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C \u0431\u0438\u043D\u0430\u0440\u043D\u044B\u0439 \u043F\u043E\u0438\u0441\u043A, \u0447\u0442\u043E\u0431\u044B \u043D\u0430\u0439\u0442\u0438 \u0441\u0430\u043C\u044B\u0439 \u043F\u0440\u0430\u0432\u044B\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 (\u043F\u0440\u0435\u0434\u0448\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0439 nums[i]), \u043A\u043E\u0442\u043E\u0440\u044B\u0439 \u043C\u0435\u043D\u044C\u0448\u0435 nums[i].\n6. \u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0432\u0430\u0435\u043C \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u043D\u0430 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u0432, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u043C\u043E\u0436\u043D\u043E \u043E\u0431\u0440\u0430\u0437\u043E\u0432\u0430\u0442\u044C, \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u044F \u0432 nums[i]. \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u0432 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u044F\u0435\u0442\u0441\u044F \u0438\u043D\u0434\u0435\u043A\u0441\u043E\u043C \u043D\u0430\u0439\u0434\u0435\u043D\u043D\u043E\u0433\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0438 \u0440\u0430\u0432\u043D\u043E (left + 2), \u0433\u0434\u0435 left - \u0438\u043D\u0434\u0435\u043A\u0441 \u0441\u0430\u043C\u043E\u0433\u043E \u043F\u0440\u0430\u0432\u043E\u0433\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430, \u043C\u0435\u043D\u044C\u0448\u0435\u0433\u043E nums[i].\n7. \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C lst - \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0443\u044E, \u0445\u0440\u0430\u043D\u044F\u0449\u0443\u044E \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0433\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0434\u043B\u044F \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0439 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438.\n8. \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043C \u0438\u0442\u043E\u0433\u043E\u0432\u044B\u0439 \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442.\n# Complexity\n- Time complexity: $$O(n)$$, \u0433\u0434\u0435 $$n$$ - \u0434\u043B\u0438\u043D\u0430 \u043C\u0430\u0441\u0441\u0438\u0432\u0430. \u041C\u044B \u043F\u0440\u043E\u0445\u043E\u0434\u0438\u043C \u043F\u043E \u043C\u0430\u0441\u0441\u0438\u0432\u0443 \u0434\u0432\u0430\u0436\u0434\u044B: \u043E\u0434\u0438\u043D \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u043D\u0430\u0439\u0442\u0438 \u043F\u0440\u0430\u0432\u0443\u044E \u0433\u0440\u0430\u043D\u0438\u0446\u0443 \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0435\u0433\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u0430, \u0438 \u0432\u0442\u043E\u0440\u043E\u0439 \u0440\u0430\u0437, \u0447\u0442\u043E\u0431\u044B \u0432\u044B\u0447\u0438\u0441\u043B\u0438\u0442\u044C \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u0432.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$. \u041C\u044B \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u043A\u043E\u043D\u0441\u0442\u0430\u043D\u0442\u043D\u043E\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439 \u043F\u0430\u043C\u044F\u0442\u0438 \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445 \u0438 \u0438\u043D\u0434\u0435\u043A\u0441\u043E\u0432.\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# C++\n```\n#include <vector>\n#include <iostream>\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(std::vector<int>& nums) {\n long long ans = 1; // \u0418\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u0443\u0435\u043C \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u0435\u0434\u0438\u043D\u0438\u0446\u0435\u0439, \u0442\u0430\u043A \u043A\u0430\u043A \u043A\u0430\u0436\u0434\u044B\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043C\u0430\u0441\u0441\u0438\u0432\u0430 \u044F\u0432\u043B\u044F\u0435\u0442\u0441\u044F \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u043C\n int r = 1; // \u0418\u043D\u0434\u0435\u043A\u0441 \u043F\u0440\u0430\u0432\u043E\u0439 \u0433\u0440\u0430\u043D\u0438\u0446\u044B \u0442\u0435\u043A\u0443\u0449\u0435\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0435\u0433\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u0430\n const int n = nums.size(); // \u0420\u0430\u0437\u043C\u0435\u0440 \u043C\u0430\u0441\u0441\u0438\u0432\u0430\n // \u041D\u0430\u0445\u043E\u0434\u0438\u043C \u043F\u0440\u0430\u0432\u0443\u044E \u0433\u0440\u0430\u043D\u0438\u0446\u0443 \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0435\u0433\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u0430\n while (r < n && nums[r] > nums[r - 1]) {\n r++;\n }\n // \u0415\u0441\u043B\u0438 \u043C\u0430\u0441\u0441\u0438\u0432 \u043F\u043E\u043B\u043D\u043E\u0441\u0442\u044C\u044E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0438\u0439, \u0442\u043E \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0438\u0445 \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u0432 \u0440\u0430\u0432\u043D\u043E n * (n + 1) / 2\n if (r == n) {\n return (static_cast<long long>(n) * (n + 1)) / 2;\n }\n int lst = INT_MAX; // \u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F \u0434\u043B\u044F \u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0433\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\n ans += r; // \u041D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u0432 \u0440\u0430\u0432\u043D\u043E \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0443 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u0432 \u043F\u0435\u0440\u0432\u043E\u043C \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u044E\u0449\u0435\u043C \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u0435\n // \u0418\u0442\u0435\u0440\u0438\u0440\u0443\u0435\u043C\u0441\u044F \u043F\u043E \u043C\u0430\u0441\u0441\u0438\u0432\u0443 \u0432 \u043E\u0431\u0440\u0430\u0442\u043D\u043E\u043C \u043F\u043E\u0440\u044F\u0434\u043A\u0435\n for (int i = n - 1; i >= 0; i--) {\n if (nums[i] >= lst) {\n break; // \u0415\u0441\u043B\u0438 \u0442\u0435\u043A\u0443\u0449\u0438\u0439 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 \u043D\u0435 \u043C\u0435\u043D\u044C\u0448\u0435 \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0433\u043E, \u0432\u044B\u0445\u043E\u0434\u0438\u043C \u0438\u0437 \u0446\u0438\u043A\u043B\u0430\n }\n int low = 0, high = r - 1;\n int left = -1;\n // \u0411\u0438\u043D\u0430\u0440\u043D\u044B\u0439 \u043F\u043E\u0438\u0441\u043A \u0434\u043B\u044F \u043D\u0430\u0445\u043E\u0436\u0434\u0435\u043D\u0438\u044F \u0438\u043D\u0434\u0435\u043A\u0441\u0430 \u0441\u0430\u043C\u043E\u0433\u043E \u043F\u0440\u0430\u0432\u043E\u0433\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430, \u043C\u0435\u043D\u044C\u0448\u0435\u0433\u043E \u0442\u0435\u043A\u0443\u0449\u0435\u0433\u043E\n while (low <= high) {\n int mid = (low + high) / 2;\n if (nums[mid] < nums[i]) {\n left = mid;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n ans += (left + 2); // \u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0432\u0430\u0435\u043C \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u043D\u0430 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043F\u043E\u0434\u043C\u0430\u0441\u0441\u0438\u0432\u043E\u0432, \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u044E\u0449\u0438\u0445\u0441\u044F \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u043C \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0435\n lst = nums[i]; // \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0433\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\n }\n return ans; // \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043C \u0438\u0442\u043E\u0433\u043E\u0432\u044B\u0439 \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\n }\n};\n```
1
1
['Two Pointers', 'Binary Search', 'Greedy', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
Python3 Binary Search
python3-binary-search-by-sandeep_p-3qn6
Intuition\nconnect increasing left and right subarrays.\n\n j = bisect.bisect_left(nums, nums[i]+1, lo=max(i + 2, n - rc))\n #i+2 to delete atleast 1 elem
sandeep_p
NORMAL
2023-12-23T16:39:03.560166+00:00
2023-12-23T17:16:47.499616+00:00
71
false
# Intuition\nconnect increasing left and right subarrays.\n\n j = bisect.bisect_left(nums, nums[i]+1, lo=max(i + 2, n - rc))\n #i+2 to delete atleast 1 element, n-rc to make sure its in right increasing subarray.\n\n# Code\n```\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n nums=[float("-inf")]+nums+[float("inf")]\n n = len(nums)\n lc = 1\n rc = 1\n\n for i in range(1, n):\n if nums[i] <= nums[i - 1]:\n break\n lc += 1\n\n for i in range(n - 2, -1, -1):\n if nums[i] >= nums[i + 1]:\n break\n rc += 1\n\n ans=0\n for i in range(lc):\n j = bisect.bisect_left(nums, nums[i]+1, lo=max(i + 2, n - rc))\n if j < n and nums[j] > nums[i]:\n ans += n - j\n\n return ans\n```
1
0
['Binary Search', 'Python3']
0
count-the-number-of-incremovable-subarrays-ii
Count the Number of Incremovable Subarrays II || JAVASCRIPT || Solution by Bharadwaj
count-the-number-of-incremovable-subarra-4ni2
Approach\nTwo Pointers + Binary Search\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nvar incremovableSubarrayCount =
Manu-Bharadwaj-BN
NORMAL
2023-12-23T16:27:19.127834+00:00
2023-12-23T16:27:19.127851+00:00
31
false
# Approach\nTwo Pointers + Binary Search\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nvar incremovableSubarrayCount = function(nums) {\n let ans = 1;\n let r = 1;\n const n = nums.length;\n\n while (r < n && nums[r] > nums[r - 1]) {\n r++;\n }\n\n if (r === n) {\n return (n * (n + 1)) / 2;\n }\n\n let lst = Number.MAX_SAFE_INTEGER;\n ans += r;\n\n for (let i = n - 1; i >= 0; i--) {\n if (nums[i] >= lst) {\n break;\n }\n let low = 0, high = r - 1;\n let left = -1;\n\n while (low <= high) {\n let mid = Math.floor((low + high) / 2);\n if (nums[mid] < nums[i]) {\n left = mid;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n ans += (left + 2);\n lst = nums[i];\n }\n\n return ans;\n};\n```
1
0
['JavaScript']
0
count-the-number-of-incremovable-subarrays-ii
Easy to understand Java O(N) solution with explanation
easy-to-understand-java-on-solution-with-egcp
Intuition\nThe problem is the same as: find the strictly increasing subarrays that can be done by removing a subarray. \nThen it can be further changed to \n(1)
ebifurai_tsn
NORMAL
2023-12-23T16:15:09.986419+00:00
2023-12-23T16:15:09.986446+00:00
171
false
# Intuition\nThe problem is the same as: find the strictly increasing subarrays that can be done by removing a subarray. \nThen it can be further changed to \n(1) it starts from i = 0 or it ends at i = n - 1\n(2) removing all\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n int n = nums.length;\n \n int leftIncreasing = 1;\n for (int i = 1; i < n; i++) {\n if (nums[i] > nums[i - 1]) {\n leftIncreasing++;\n } else {\n break;\n }\n }\n\n // simplier to just return the answer when the whole nums is a strictly increasing sequence\n if (leftIncreasing == n) {\n return (1L + (long)n) * (long)n / 2L;\n }\n\n int rightIncreasing = 1;\n for (int i = n - 2; i >= 0; i--) {\n if (nums[i + 1] > nums[i]) {\n rightIncreasing++;\n } else {\n break;\n }\n }\n \n // find the patten of removing a subarray starts from i != 0 to i != n - 1\n long twinIncreasing = 0;\n int r = n - rightIncreasing;\n for (int l = 0; l < leftIncreasing; l++) {\n while (r < n && nums[l] >= nums[r]) {\n r++;\n }\n if (r == n) {\n break;\n }\n twinIncreasing += (long)(n - r);\n }\n\n // remember to add the case removing all numbers\n return (1L + (long)leftIncreasing + (long)rightIncreasing + (long)twinIncreasing);\n \n }\n}\n```
1
0
['Array', 'Two Pointers', 'Java']
0
count-the-number-of-incremovable-subarrays-ii
sliding window
sliding-window-by-directioner1d-twzc
\n# Code\n\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n nums=[-1]+nums\n j=len(nums)-1\n while(j>0
directioner1d
NORMAL
2023-12-23T16:12:05.774477+00:00
2023-12-23T16:12:05.774505+00:00
300
false
\n# Code\n```\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n nums=[-1]+nums\n j=len(nums)-1\n while(j>0 and nums[j-1]<nums[j]):\n j-=1\n ma=-2\n ans=0\n for i in range(len(nums)):\n if(nums[i]>ma):\n ma=nums[i]\n while(j<len(nums) and nums[j]<=ma):\n j+=1\n if(i+1!=j ):\n ans+=1\n ans+=len(nums)-j\n else:\n break\n return ans\n```
1
0
['Sliding Window', 'Python3']
1
count-the-number-of-incremovable-subarrays-ii
Binary search, O(n log(n)) TC
binary-search-on-logn-tc-by-filinovsky-ay2z
IntuitionApproachComplexity Time complexity: Space complexity: Code
Filinovsky
NORMAL
2024-12-30T22:16:17.378667+00:00
2024-12-30T22:16:17.378667+00:00
10
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 ```python3 [] class Solution: def incremovableSubarrayCount(self, nums: List[int]) -> int: import bisect n = len(nums) j = 1 while j < n and nums[j - 1] < nums[j]: j += 1 left = j - 1 j = n - 2 while j >= 0 and nums[j] < nums[j + 1]: j -= 1 right = j + 1 if left == n - 1: return n * (n + 1) // 2 ans = 0 for i in range(left, -1, -1): idx = bisect.bisect_right(nums, nums[i], lo=right, hi=n) ans += n - idx + 1 ans += n - right + 1 return ans ```
0
0
['Python3']
0
count-the-number-of-incremovable-subarrays-ii
All Solutions from Brute Force to O(n) || C++ || Easy to understand
all-solutions-from-brute-force-to-on-c-e-nqon
Code 1 - Brute Force O(n^3)\n\ncpp []\nclass Solution {\npublic:\n int incremovableSubarrayCount(vector<int>& nums) {\n int ans = 0;\n\n // Ite
manraj_singh_16447
NORMAL
2024-11-24T09:44:57.166421+00:00
2024-11-24T09:44:57.166458+00:00
3
false
# Code 1 - Brute Force $$O(n^3)$$\n\n```cpp []\nclass Solution {\npublic:\n int incremovableSubarrayCount(vector<int>& nums) {\n int ans = 0;\n\n // Iterate over all possible starting indices\n for (int i = 0; i < nums.size(); i++) {\n // Iterate over all possible ending indices\n for (int j = i; j < nums.size(); j++) {\n bool tillLeft = true, tillRight = true;\n\n // Check if prefix [0, i-1] is strictly increasing\n for (int k = 0; k < i - 1; k++) {\n if (nums[k] >= nums[k + 1]) {\n tillLeft = false;\n break;\n }\n }\n\n // Check if suffix [j+1, nums.size()-1] is strictly increasing\n for (int k = j + 1; k < nums.size() - 1; k++) {\n if (nums[k] >= nums[k + 1]) {\n tillRight = false;\n break;\n }\n }\n\n // Check the boundary condition for nums[i-1] and nums[j+1]\n if (tillLeft && tillRight &&\n (i - 1 >= 0 ? nums[i - 1] : INT_MIN) < (j + 1 < nums.size() ? nums[j + 1] : INT_MAX)) {\n ans++;\n }\n }\n }\n\n return ans;\n }\n};\n\n```\n# Code 2 - N Cube Optimization $$O(n^2)$$\n```cpp []\nclass Solution {\npublic:\n int incremovableSubarrayCount(vector<int>& nums) {\n int ans = 0;\n\n // Calculate longest increasing prefix\n int leftIncreasing = 0, rightDecreasing = nums.size() - 1;\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i - 1] >= nums[i]) break;\n leftIncreasing++;\n }\n\n // Calculate longest increasing suffix\n for (int i = nums.size() - 1; i > 0; i--) {\n if (nums[i] <= nums[i - 1]) break;\n rightDecreasing--;\n }\n\n // Iterate over all subarrays\n for (int i = 0; i < nums.size(); i++) {\n for (int j = i; j < nums.size(); j++) {\n // Skip invalid subarrays based on precomputed data\n bool tillLeft = i - 1 <= leftIncreasing;\n bool tillRight = j + 1 >= rightDecreasing;\n\n // Check the boundary condition for nums[i-1] and nums[j+1]\n if (tillLeft && tillRight &&\n (i - 1 >= 0 ? nums[i - 1] : INT_MIN) < (j + 1 < nums.size() ? nums[j + 1] : INT_MAX)) {\n ans++;\n }\n }\n }\n\n return ans;\n }\n};\n\n```\n\n\n# Code 3 - Binary Search $$O(nlog(n))$$\n\n```cpp []\nclass Solution {\npublic:\n // Helper function for binary search\n int bupper(vector<int>& nums, int left, int right, int target) {\n while (left < right) {\n int mid = (right - left) / 2 + left;\n\n // Move the search range based on the target\n if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n\n // Return the appropriate index\n return nums[right] <= target ? right + 1 : right;\n }\n\n int incremovableSubarrayCount(vector<int>& nums) {\n int leftIncreasing = 0, rightDecreasing = nums.size() - 1;\n\n // Calculate longest increasing prefix\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i - 1] >= nums[i]) break;\n leftIncreasing++;\n }\n\n // Calculate longest increasing suffix\n for (int i = nums.size() - 1; i > 0; i--) {\n if (nums[i - 1] >= nums[i]) break;\n rightDecreasing--;\n }\n\n // Special case: entire array is strictly increasing\n if (rightDecreasing == 0) {\n return nums.size() * (nums.size() + 1) / 2;\n }\n\n int ans = nums.size() - rightDecreasing + 1;\n\n // Use binary search for each prefix\n for (int i = 0; i <= leftIncreasing; i++) {\n int index = bupper(nums, rightDecreasing, nums.size() - 1, nums[i]);\n ans += (nums.size() - index + 1);\n }\n\n return ans;\n }\n};\n\n\n```\n\n# Code 4 - Two Pointer $$O(n)$$\n\n```cpp []\nclass Solution {\npublic:\n int incremovableSubarrayCount(vector<int>& nums) {\n int leftIncreasing = 0, rightDecreasing = nums.size() - 1;\n\n // Calculate longest increasing prefix\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i - 1] >= nums[i]) break;\n leftIncreasing++;\n }\n\n // Calculate longest increasing suffix\n for (int i = nums.size() - 1; i > 0; i--) {\n if (nums[i - 1] >= nums[i]) break;\n rightDecreasing--;\n }\n\n // Special case: entire array is strictly increasing\n if (rightDecreasing == 0) {\n return nums.size() * (nums.size() + 1) / 2;\n }\n\n int ans = nums.size() - rightDecreasing + 1;\n\n // Use two pointers to adjust the suffix dynamically\n for (int i = 0; i <= leftIncreasing; i++) {\n while (rightDecreasing < nums.size() && nums[rightDecreasing] <= nums[i]) {\n rightDecreasing++;\n }\n ans += (nums.size() - rightDecreasing + 1);\n }\n\n return ans;\n }\n};\n\n```\n\n
0
0
['Array', 'Two Pointers', 'Binary Search', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
binary search easy solution cpp
binary-search-easy-solution-cpp-by-vatsa-5gxe
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
vatsalarora
NORMAL
2024-11-20T13:07:50.936366+00:00
2024-11-20T13:07:50.936403+00:00
6
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\n\n void reverseVector(vector<pair<int,int>>& vec) {\n int left = 0, right = vec.size() - 1;\n\n while (left < right) {\n \n swap(vec[left], vec[right]);\n left++;\n right--;\n }\n}\n\n\n\n int binary( vector<pair<int,int>>& arr, int target) {\n int left = 0, right = arr.size() - 1;\n int result = -1; \n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n\n if (arr[mid].first > target) {\n result = arr[mid].second; \n right = mid - 1; \n } else {\n left = mid + 1; \n }\n }\n\n return result; \n}\n long long incremovableSubarrayCount(vector<int>& arr) {\n int n = arr.size();\n vector<pair<int,int>> vec;\n int last = 0;\n vec.push_back({arr[n-1],n-1});\n for(int i = n-2;i>=0;i--){\n if(arr[i] < arr[i+1]){\n vec.push_back({arr[i],i});\n \n }\n else{\n break;\n }\n }\n reverseVector(vec);\n // for(int i = 0;i<vec.size();i++){\n // cout<<vec[i].first<<" "<<vec[i].second<<endl;\n // }\n long long ans = 0;\n for(int i = 0;i<n;i++){\n if(i>0 && arr[i] <= arr[i-1]) break;\n int x = binary(vec,arr[i]) ;\n //cout<<x<<endl;\n if(x == i) {\n \n continue;\n }\n else if(x == -1){\n ans++;\n }\n else{\n ans += (n-x) + ((x-i > 1) ? 1 : 0);\n }\n \n }\n if(vec.size() == arr.size()) ans+=vec.size() -1;\n else ans+=vec.size() + 1;\n return ans;\n }\n};\n```
0
0
['Binary Search', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
scala O(n) solution
scala-on-solution-by-vititov-rokd
scala []\nobject Solution {\n def incremovableSubarrayCount(nums: Array[Int]): Long = {\n lazy val pxfEnd = Iterator.range(1,nums.length)\n .map(i => n
vititov
NORMAL
2024-11-16T14:31:03.793228+00:00
2024-11-16T14:31:03.793268+00:00
1
false
```scala []\nobject Solution {\n def incremovableSubarrayCount(nums: Array[Int]): Long = {\n lazy val pxfEnd = Iterator.range(1,nums.length)\n .map(i => nums(i)-nums(i-1) -> i).takeWhile(_._1>0)\n .to(List).lastOption.map(_._2).getOrElse(0)\n lazy val sfxStart = Iterator.range(nums.length-2,-1,-1)\n .map(i => nums(i+1)-nums(i) -> i).takeWhile(_._1>0)\n .to(LazyList).lastOption.map(_._2).getOrElse(nums.length-1)\n lazy val x3 = Iterator.range(0,pxfEnd+1).scanLeft(-1,sfxStart){\n case ((_,j),i) =>\n lazy val j1 = Iterator.range(j max (i+1), nums.length)\n .dropWhile(nums(i) >= nums(_)).take(1).to(List)\n .headOption.getOrElse(nums.length)\n (i,j1)\n }.map{case (a,b) => nums.length-b+1}.foldLeft(0L)(_ + _)\n if(sfxStart == 0) (nums.length+1L)*nums.length/2 else x3\n }\n}\n```
0
0
['Array', 'Two Pointers', 'Scala']
0
count-the-number-of-incremovable-subarrays-ii
c++ 0ms soln
c-0ms-soln-by-harshit_chauhan_07-ua7i
Intuition Beats 100% easy c++ soln\n Describe your first thoughts on how to solve this problem. \n\n# Approach easy \n Describe your approach to solving the pro
HARSHIT_CHAUHAN_07
NORMAL
2024-11-15T15:38:42.862823+00:00
2024-11-15T15:38:42.862844+00:00
1
false
# Intuition Beats 100% easy c++ soln\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach easy \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 long long incremovableSubarrayCount(vector<int>& nums) {\n int n=nums.size();\n int l=0,r=n-1;\n long long ans=0;\n while(l<n-1 && nums[l]<nums[l+1])l++;\n if(l==n-1)return (long long)n*(n+1)/2;\n while(r>0 && nums[r]>nums[r-1])r--;\n ans+=l+1+n-r;\n int j=l;\n while(r<n){\n l=j;\n while(l>0&&nums[l]>=nums[r])l--;\n if(l>=0 && nums[l]<nums[r])ans+=l+1;\n r++;\n }\n return ans+1;\n }\n};\n```
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
Prefix Suffix and Count Smaller
prefix-suffix-and-count-smaller-by-theab-1h4h
\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def incremovableSubarrayCount(self, arr: List[int]) -> int:\n n = len(arr)\n res
theabbie
NORMAL
2024-11-15T03:03:26.213767+00:00
2024-11-15T03:03:26.213808+00:00
2
false
```\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def incremovableSubarrayCount(self, arr: List[int]) -> int:\n n = len(arr)\n res = 0\n suff = [False] * n\n pref = [False] * n\n pref[0] = suff[n - 1] = True\n for i in range(n - 2, -1, -1):\n if arr[i] < arr[i + 1] and suff[i + 1]:\n suff[i] = True\n for i in range(1, n):\n if arr[i] > arr[i - 1] and pref[i - 1]:\n pref[i] = True\n bst = SortedList()\n for j in range(n):\n if j == 0 or pref[j - 1]:\n bst.add(arr[j - 1] if j > 0 else float(\'-inf\'))\n if j == n - 1 or suff[j + 1]:\n res += bst.bisect_right(arr[j + 1] - 1 if j + 1 < n else float(\'inf\'))\n \xA0 \xA0 \xA0 \xA0return res \n```
0
0
[]
0
count-the-number-of-incremovable-subarrays-ii
Very easy solution, I don't know why people are making it complicated
very-easy-solution-i-dont-know-why-peopl-2epx
Intuition\nDivide the Problem in three parts, finding left subarray, right subarray and mid subarray which satisfies the desire constraints\n\n# Approach\nTwo-p
hverma21
NORMAL
2024-10-19T06:43:50.171565+00:00
2024-10-19T06:43:50.171597+00:00
5
false
# Intuition\nDivide the Problem in three parts, finding left subarray, right subarray and mid subarray which satisfies the desire constraints\n\n# Approach\nTwo-pointers and Binary Search\n\n# Complexity\n- Time complexity:\nFor Approach 1 : O(NlogN)\nFor Approach 2 : O(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n int n = nums.size();\n int left = 0;\n int right = n-1;\n\n for(int i=1;i<n;i++){\n if(nums[i]>nums[i-1]){\n left = i;\n }\n else break;\n }\n\n for(int i=n-2;i>=0;i--){\n if(nums[i]<nums[i+1]){\n right = i;\n }\n else break;\n }\n\n if(left == n-1) return 1ll*n*(n+1)/2*1ll;\n\n long long mid = 0;\n\n int l=0,r=right;\n \n //Approach-1 O(NlogN)\n // for(int i=0;i<=left;i++){\n // int r = upper_bound(nums.begin()+right,nums.end(),nums[i])-nums.begin();\n // mid+=n-r;\n // }\n\n //Approach-2 O(N)\n while(l<=left && r<n){\n if(nums[l]<nums[r]){\n mid+=n-r;\n l++;\n }\n else r++;\n }\n\n return mid + (left+1) + (n-right) + 1;\n\n }\n};\n```
0
0
['Two Pointers', 'Binary Search', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
Python solution O(n^2)
python-solution-on2-by-pachavamanasa-jl81
Code\npython3 []\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n n=len(nums)\n left=0\n right=n-1\n
pachavamanasa
NORMAL
2024-09-22T23:51:50.129287+00:00
2024-09-22T23:51:50.129314+00:00
7
false
# Code\n```python3 []\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n n=len(nums)\n left=0\n right=n-1\n res=0\n for i in range(1,n):\n if nums[i]>nums[i-1]:\n left=i\n else:\n break\n if left==n-1:\n return (n*(n+1))//2\n for j in range(n-2,0,-1):\n if nums[j]<nums[j+1]:\n right=j\n else:\n break\n l=0\n r=right\n mid=0\n while l<=left:\n while r<n and nums[l]>=nums[r]:\n r+=1\n mid+=n-r\n l+=1\n return (left+1) + (n-right) + mid + 1\n \n \n```
0
0
['Two Pointers', 'Python3']
0
count-the-number-of-incremovable-subarrays-ii
Two Pointer Binary search Approach O(nlogn) Time Complexity
two-pointer-binary-search-approach-onlog-sybp
Intuition\n- Main Intuition is to remove a subarray such that the remaining part of the array is strictly increasing.\n- Firstly if we come with brute force sol
yash559
NORMAL
2024-09-01T02:13:18.836086+00:00
2024-09-01T02:13:18.836103+00:00
7
false
# Intuition\n- Main Intuition is to remove a subarray such that the remaining part of the array is strictly increasing.\n- Firstly if we come with brute force solution, we have to check for all possible ranges of **L and R** between L and R is the removed part then we need to check whether the remaining parts of array after removing i.e: **less than L and greater than R parts** are forming **strictly increasing array**, so the time complexity would be $$O(n^3)$$\n- If we observe one thing we are checking the two parts are strictly increasing again and again.\n- instead of that if we before hand know till what index the array is strictly increasing we can just consider that part of subarray and remove remaining right.\n- So we, find **maximum element index in prefix** and **minimum element index in suffix**.\n- why min? becoz for the minimum element should be greater than maximum element from suffix, if not we check for remaining array part.\n- Now, the complexity has reduced to $$O(n^2)$$\n- Now we need to find for each index **below left_max_index** we need to find an index **above right_min_index** such that it should be greater.\n- **One thing if we notice we know that after right_min_index the array is sorted, so we apply binary search**\n- Upper bound is best suited to find the element which is greater but not equal to current\n- after getting that index we add **n - ind + 1**, becoz that many subarrays are strictly inceasing if we keep on removing a single element every time.\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\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 long long incremovableSubarrayCount(vector<int>& nums) {\n //take long long for not getting integer overflow\n long long n = nums.size();\n if(n == 1) return 1;\n\n //calculate the index for left most max value possible such that before that index elements should be strictly increasing.\n int left_max_ind = 0,right_min_ind = n-1;\n for(int i=1;i<n;i++) {\n if(nums[i] > nums[i-1]) left_max_ind++;\n else break;\n }\n //similarly find smallest element possible from right such that elements after that index should be strictly increasing\n for(int i=n-2;i>=0;i--) {\n if(nums[i] < nums[i+1]) right_min_ind--;\n else break;\n }\n //this is edge case where whole array is strictly increasing\n //below if to handle that edge case ex: [1,2,3,4]\n if(left_max_ind == n-1) return (n*(n+1))/2;\n\n //here comes our main logic\n //initial ans value is if don\'t consider any elements below left_max_ind\n long long ans = n - right_min_ind + 1;\n for(int i=0;i<=left_max_ind;i++) {\n //if that particular index index i find a element which should be greater than current element\n //and it should lie above right_min_index becoz after that index the array is strictly increasing so we don\'t need to check again.\n int ind = upper_bound(nums.begin()+right_min_ind,nums.end(),nums[i]) - nums.begin();\n //after getting index add all possible arrays \n ans += n - ind + 1;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
100%|| Efficient Solution||
100-efficient-solution-by-satyjit654-2ctu
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
satyjit654
NORMAL
2024-08-27T09:04:54.614096+00:00
2024-08-27T09:04:54.614132+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```java []\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n int n = nums.length;\n long ans = 0;\n int i = 0, j = n - 1;\n while (j > 0 && nums[j] > nums[j - 1]) {\n j--;\n }\n while (i < n) {\n j = Math.max(j, i + 1);\n ans += n - j + 1;\n while (j < n && nums[j] <= nums[i]) {\n j++;\n }\n if (i > 0 && nums[i] <= nums[i - 1]) {\n break;\n }\n i++;\n }\n return ans;\n }\n}\n\n```
0
0
['Array', 'Two Pointers', 'Binary Search', 'C++', 'Java']
0
count-the-number-of-incremovable-subarrays-ii
Easy Prefix sum and Binary Search Solution
easy-prefix-sum-and-binary-search-soluti-6bsr
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
kvivekcodes
NORMAL
2024-08-23T08:38:32.241938+00:00
2024-08-23T08:38:32.241968+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```cpp []\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n int n = nums.size();\n if(n == 1) return 1;\n vector<bool> pref(n);\n\n pref[0] = true;\n for(int i = 1; i < n; i++){\n if(nums[i] <= nums[i-1]) break;\n pref[i] = true;\n }\n\n vector<int> cnt(n);\n cnt[n-1] = nums[n-1];\n for(int i = n-2; i >= 0; i--){\n if(nums[i] >= nums[i+1]) break;\n cnt[i] = nums[i];\n }\n\n long long ans = 0;\n for(int i = 0; i < n; i++){\n if(i > 0 && !pref[i-1]) break;\n if(i == 0){\n auto it = lower_bound(cnt.begin(), cnt.end(), 1) - cnt.begin();\n it = max((int)it, i+1);\n ans += n-it+1;\n }\n else{\n auto it = lower_bound(cnt.begin(), cnt.end(), nums[i-1]+1) - cnt.begin();\n it = max((int)it, i+1);\n ans += n-it+1;\n }\n }\n\n return ans;\n }\n};\n```
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
BEATS 100% of submissions in runtime and memory!! O(n) runtime, O(1) space
beats-100-of-submissions-in-runtime-and-vtb38
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
berkeley_upe
NORMAL
2024-08-17T22:52:43.446336+00:00
2024-08-17T22:52:43.446353+00:00
3
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```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar incremovableSubarrayCount = function(nums) {\n if (nums.length == 1) {\n return 1\n }\n let i = 0\n while (i < nums.length-1 && nums[i+1] > nums[i]) {\n i += 1\n }\n let prefixIdx = i\n if (prefixIdx == nums.length-1) {\n return (nums.length) * (nums.length+1)/2\n }\n i = nums.length-1\n while (i > 0 && nums[i-1] < nums[i]) {\n i -= 1\n }\n let suffixIdx = i\n let ptr2 = suffixIdx\n let res = 0\n for (let ptr1 = 0; ptr1 <= prefixIdx; ptr1+=1) {\n while (ptr2 < nums.length && nums[ptr2] <= nums[ptr1]) {\n ptr2 += 1\n }\n res += nums.length-ptr2+1\n }\n\n return res + nums.length-suffixIdx+1\n\n};\n```
0
0
['JavaScript']
0
count-the-number-of-incremovable-subarrays-ii
Solution with Intuition and comments on code
solution-with-intuition-and-comments-on-iu584
Approach\n Describe your approach to solving the problem. \n- Identifying Initial Strictly Increasing Subarray\n- Identifying Final Strictly Increasing Subarray
mkshv
NORMAL
2024-08-14T02:26:17.239392+00:00
2024-08-14T02:26:17.239423+00:00
4
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n- Identifying Initial Strictly Increasing Subarray\n- Identifying Final Strictly Increasing Subarray\n- Handling the Entire Array Being Strictly Increasing\n- Counting Incremovable Subarrays:\n\n### Counting Incremovable Arrays\n\n- res is initialized to 1 to account for the entire array.\n- The number of incremovable subarrays that start from the beginning and end before j (non-overlapping with the final strictly increasing part) is i + 1.\n- Similarly, the number of incremovable subarrays that start from j and end at the last element (non-overlapping with the initial strictly increasing part) is n - j.\n- To account for subarrays that span both the initial and final strictly increasing parts, the helper function get_count_of_arr is used. This function counts pairs of elements from these two sections that can form incremovable subarrays when combined. It leverages the two-pointer technique to efficiently compute this count.\n\n\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:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n i = 0 \n n = len(nums)\n\n while i < n - 1 and nums[i + 1] > nums[i]:\n i += 1 \n\n if i == n - 1:\n return n*(n+1)//2\n\n j = n - 1 \n while j > 0 and nums[j - 1] < nums[j]:\n j -= 1\n\n res = 1 # empty arr\n res += (i + 1) # consider only start elements \n res += (n - j) # consider only end elements\n\n # consider both start and end elements \n def get_count_of_arr(arr1,arr2):\n i = 0 \n j = 0 \n count = 0\n while i < len(arr1) and j < len(arr2):\n if arr1[i] < arr2[j]:\n count += (len(arr2) - j)\n i += 1 \n else:\n j += 1 \n return count\n \n res += get_count_of_arr(nums[0:i + 1], nums[j:])\n return res \n\n```
0
0
['Python3']
0
count-the-number-of-incremovable-subarrays-ii
O(NLogN) Python3 Bisect Module
onlogn-python3-bisect-module-by-dhruvp16-n29t
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
dhruvp16011
NORMAL
2024-08-08T07:51:38.124033+00:00
2024-08-08T07:51:38.124065+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```\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n def solve(nums):\n l , r = 0 , len(nums)-1\n n = len(nums)\n ans = 0\n while l+1 < len(nums) and nums[l] < nums[l+1]:\n l+=1\n\n if l == len(nums)-1:\n return((n*(n+1))//2)\n \n while r - 1 >= 0 and nums[r]>nums[r-1]:\n r-=1\n \n #approach\n for i in range(0, l+1):\n idx = bisect.bisect_right(nums[r:] , nums[i])\n ans = ans + (n - (idx + r) +1)\n\n #also the array starting from r\n ans= ans + (n- r+1)\n \n return(ans)\n\n return(solve(nums))\n \n```
0
0
['Python3']
0
count-the-number-of-incremovable-subarrays-ii
O(N) , Two pointers solution with detailed explanation
on-two-pointers-solution-with-detailed-e-rtpk
Intuition\n\n\n# Approach\n\nImagine the array is divided into three parts: A, B, and C:\n- A is strictly increasing.\n- C is also strictly increasing.\n\nAfter
sidneylin
NORMAL
2024-07-08T05:26:08.341144+00:00
2024-07-08T09:16:52.888306+00:00
8
false
# Intuition\n\n\n# Approach\n\nImagine the array is divided into three parts: `A`, `B`, and `C`:\n- `A` is strictly increasing.\n- `C` is also strictly increasing.\n\nAfter removing subarray `B`, the remaining elements fall into one of four categories:\n\n1. Empty array (B equals the whole array)\n2. Only the prefix of the array remains (`A` can\'t be empty).\n2. Both the prefix and suffix of the array remain (`A + C`).\n3. Only the suffix of the array remains (`C` can\' be empty).\n\nAssume we find the index of the last element of `A`, denoted as `last_element_index`, with the array length `n`, `j` is the first element of C;\n\n- **Special Case: All elements are strictly increasing**:\n there will be all combinations `n*(n+1)/2`.\n\n- **First case**:\nonly 1 combination which is empty array.\n\n- **Second case**:\nthere are i + 1 combinations, as i can range from 0 to i, inclusive.\n\n- **Third case**:\n `A` cannot be empty, otherwise, it would fall into the third case. `C` also cannot be empty, otherwise, it would fall into the first case. Therefore, the range of `i` is `[0, last_element_index]`, and the range of `j` is `[last_element_index + 1, n - 1]`.\n\n We need to find an element in `A` that is smaller than the first element of `C`, because after removing `B`, `[A, C]` must still be strictly increasing to connect:\n\n ```cpp\n while (i >= 0 && nums[i] >= nums[j]) {\n i--;\n }\n ```\n B can be empty so the range of j is `[last_element_index + 1, n - 1]`. For each j in this case, there are i + 1 combinations, as i can range from 0 to i, inclusive.\n\n\n For example, in [2, 10, 8, 9], where last_element_index is 1:\n\n j == 3 -> [2,10,9], [2,9]\n j == 2 -> [2,10,8,9], [2,8,9]\n\n\n\n- **Fourth case**:\n The range of C is also [last_element_index + 1, n - 1]. In this case, because only C remains, each j will generate only 1 combination.\n\n For example, in [2, 10, 8, 9], where last_element_index is 1:\n\n j == 3 -> [9]\n j == 2 -> [8, 9]\n \nAll these assumptions are based on A and C being strictly increasing.\n\nTo ensure that A and C are strictly increasing:\n\n1. **A** is straightforward: when finding `last_element_index`, it\'s already confirmed that A is strictly increasing.\n\n2. **C**, start looking for increasing subarrays from the back (`n-1`) until nums[j-1] and nums[j] violate strictly increasing.\n ```\n if (nums[j - 1] >= nums[j]) { break; }\n ```\n\n If there are more than two numbers `x` and `y` that violate the strictly increasing order: \n\n Example: \n [1, 2, 3, x, 5, 6, 7, y, 9, 10, 11]\n\n Because only one subarray can be removed and it must be contiguous,there is only one option: [x, 5, 6, 7, y], the smallest possible length of B.\n \n Only one subarray can be removed and must include x and y, so the largest possible range of B is removed. No longer concerned about whether there are numbers between x and y, because they must be included.\n So stop here, don\'t need to look back, because there won\'t be any smaller B than that. So the boundaries of ABC were found.\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 long long incremovableSubarrayCount(vector<int>& nums) {\n int last_element_index = 0;\n int len = nums.size();\n\n //case 1 empty array\n long long count = 1;\n\n while(last_element_index < len - 1 && nums[last_element_index] < nums[last_element_index+1]) {\n last_element_index++;\n }\n\n //special case \n if(last_element_index == len - 1) {\n return (len*(len+1))/2;\n }\n\n //case 2\n count += last_element_index + 1;\n\n //case 3\n int i = last_element_index;\n for(int j = len - 1; j >= i+1; j--) {\n while(i >= 0 && nums[i] >= nums[j]) {\n i--;\n }\n if(i>=0) {\n count += i+1;\n }\n if(nums[j-1] >= nums[j]) {\n break;\n }\n }\n //case 4\n int k = len - 1;\n while(k >= last_element_index + 1 ) {\n count++;\n if(nums[k-1] >= nums[k]) {\n break;\n }\n k--;\n }\n return count; \n }\n};;\n```
0
0
['Two Pointers', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
C++ | 2 Pointer
c-2-pointer-by-ghost_tsushima-tkwx
\n\n\n\nclass Solution {\npublic:\n \n \n // Intuition: How many subarrays can I Remove that starts with i? For a subarray that I can remove, that\n
ghost_tsushima
NORMAL
2024-07-02T12:15:35.290533+00:00
2024-07-02T12:15:35.290563+00:00
2
false
\n\n\n```\nclass Solution {\npublic:\n \n \n // Intuition: How many subarrays can I Remove that starts with i? For a subarray that I can remove, that\n // starts with i, nums[0]---nums[i-1] has to be increasing. Now, find the range of j that if you remove\n // will keep the array as increasing for the given i.\n \n long long incremovableSubarrayCount(vector<int>& nums) {\n int j = nums.size()-2;\n while(j>=0){\n if (nums[j] < nums[j+1]) {\n j--;\n } else {\n break;\n }\n }\n if (j == -1) {\n return (nums.size() * (nums.size()+1))/2;\n }\n j++;\n long long int ans = 0;\n \n int prev = INT_MIN;\n for (int i = 0; i < nums.size(); i++) {\n while(j < nums.size() && prev >= nums[j]) {\n j++;\n }\n int removeEndIndexMin = j-1;\n int removeEndIndexMax = nums.size()-1;\n ans = ans + removeEndIndexMax - removeEndIndexMin + 1;\n \n if(nums[i] <= prev) {\n break;\n }\n prev = nums[i]; \n }\n return ans;\n \n \n }\n};\n```
0
0
[]
0
count-the-number-of-incremovable-subarrays-ii
O(nlogn) Python Solution | Extremely Simple
onlogn-python-solution-extremely-simple-8lxn8
Summary\nWe can use strictly increasing prefixes and suffixes of the array to calculate the number of incremovable subarrays. This is because removing any incre
Pras28
NORMAL
2024-06-19T03:08:25.711083+00:00
2024-06-19T03:08:25.711122+00:00
17
false
# Summary\nWe can use strictly increasing prefixes and suffixes of the array to calculate the number of **incremovable** subarrays. This is because removing any **incremovable** subarray `nums[l...r]` will result in an increasing prefix `nums[0...l]` and suffix `nums[r...n]`.\n\n# Detailed Approach\nFirst, we need to make note of a few things. When we remove subarray `nums[l...r]` , we are left with the prefix `nums[0...l)` and the suffix `nums(r...n]`. In order for the subarray to be **incremovable**, the resulting array `nums[0...l-1,r+1...n]` must be strictly increasing.\n\nThis implies that `nums[0...l)` and `nums(r...n]` must also be strictly increasing. Thus, we can begin by finding possible prefixes and suffixes. This can be done with two pointers. If we have an increasing prefix `nums[0...l)` and `nums[l] > nums[l-1]`, then the subarray `nums[0...l + 1)` must also be an increasing prefix, and so on. The same thing can be done on the right side with another pointer to find suffixes.\n\nIf the prefix and the suffix both take up the entire array, then the result is simply $\\frac{n * (n+1)}{2}$, since any subarray will be strictly increasing. If not, then we can calculate the number of possible resulting combinations of prefixes and suffixes by iterating on our prefixes, and for each of these valid resulting arrays there must exist an **incremovable** subarray.\n\nFor each element in the prefix array `nums[0...l]`, we can binary search for the smallest element `nums[r]` in the suffix array which is larger than `nums[l]`. Now, notice that suffix arrays which start after `nums[r]` will be greater than `nums[l]`, making all of them valid resulting increasing arrays. This means that For every `l`, we have `n - r + 1` **incremovable** subarrays.\n\nThe final step is to add the number of suffix arrays (this is the case where we don\'t use any of the prefix arrays) and 1 (since the empty array is strictly increasing) to the result. This will give us our answer.\n\n# Complexity\n- Time complexity:\n$O(n\\log n)$\n\n- Space complexity:\n$O(n)$\n\n# Code\n```\nfrom bisect import bisect_left, bisect_right\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n n = len(nums)\n l = 0\n r = n - 1\n prev_r = float(\'inf\')\n right_side = 0\n while r >= 0 and nums[r] < prev_r:\n prev_r = nums[r]\n r -= 1\n right_side += 1\n right_list = nums[r + 1:]\n \n prev_l = 0\n left_side = 0\n while l < n and nums[l] > prev_l:\n prev_l = nums[l]\n l += 1\n left_side += 1\n if left_side == right_side == n:\n return (n * (n+1)) >> 1\n \n res = right_side + 1 # take out entire left + entire array \n # none of the left is used, so now we will iterate on numbers to keep on the left side\n\n\n for i in range(left_side):\n curr = nums[i] # number to include, must find smallest number greater than it on the right side\n idx = bisect_right(right_list, curr)\n res += len(right_list) - idx + 1\n \n return res\n \n```
0
0
['Python3']
0
count-the-number-of-incremovable-subarrays-ii
Easy Solution
easy-solution-by-harshkumar_23-1cf5
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
harshkumar_23
NORMAL
2024-06-18T05:46:33.577049+00:00
2024-06-18T05:46:33.577070+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 long incremovableSubarrayCount(int[] nums) {\n int n = nums.length;\n if(n == 1) return 1;\n if(n == 2) {\n return 3;\n }\n \n long ans = 1; // removing all would be a solution\n\n // left increasing\n int left = 0;\n while(left < n-1 && nums[left] < nums[left+1]) {\n left++;\n }\n ans += left + 1l;\n \n // right increasing\n int right = n-1;\n while(right > 0 && nums[right-1] < nums[right]) {\n right--;\n }\n ans += n - right;\n \n // if all are increasing\n if(left >= right) {\n return ((n)*(n+1))/2l;\n }\n\n left = 0;\n // middle handling\n while(left < right && right < n) {\n if(nums[left] < nums[right]) {\n ans += right == n-1 ? 1l : (long)(n-right);\n if(left < n-1 && nums[left] < nums[left+1])\n left++;\n else \n break;\n } else {\n right++;\n }\n }\n \n return ans;\n }\n}\n```
0
0
['Java']
0
count-the-number-of-incremovable-subarrays-ii
python3 two pointers + bisect
python3-two-pointers-bisect-by-maxorgus-s4wy
find the LIS starting from 0 ending at x and ending at n-1 starting at y\n\nif they are the same, that is the whole array is increasing, return n*(n+1) // 2 (pi
MaxOrgus
NORMAL
2024-06-12T02:17:17.350980+00:00
2024-06-12T02:17:17.350997+00:00
8
false
find the LIS starting from 0 ending at x and ending at n-1 starting at y\n\nif they are the same, that is the whole array is increasing, return n*(n+1) // 2 (pick any two or one indices)\n\notherwise, consider\n\n1) pick a non empty subarray from [0:x], we have x+1\n2) pick a non empty subarray from [y:n-1], we have n-y\n3) pick some from left some from right. for i in [0:x], find the smallest j such that nums[j] > nums[i], we can have n-j new arrays by deleting what is in between. For i == 0 we need bisect, for any i later just increase j until it reaches j where we quit.\n\nDon\'t forget the empty one we can get by deleting everything. \n\n\n# Code\n```\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n x = 0\n n = len(nums)\n for i in range(1,n):\n if nums[i] > nums[i-1]:\n x = i\n else:\n break\n if x == n-1:\n return n*(n+1) // 2\n y = n-1\n for j in range(n-1,0,-1):\n if nums[j] > nums[j-1]:\n y = j-1\n else:\n break\n \n res = x + 1 + n - y\n j = bisect.bisect_right(nums[y:],nums[0]) + y\n res += n - j\n for i in range(1,x+1):\n curr = nums[i]\n while j < n and nums[j] <= curr:\n j += 1\n if j == n:break\n res += n - j\n \n return res + 1\n\n\n```
0
0
['Python3']
0
count-the-number-of-incremovable-subarrays-ii
java binarySearch
java-binarysearch-by-mot882000-hbx9
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
mot882000
NORMAL
2024-04-03T02:57:38.267063+00:00
2024-04-03T02:57:38.267087+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:\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 long incremovableSubarrayCount(int[] nums) {\n\n // 1. subarray \uD55C\uAC1C\uB9CC \uC0AD\uC81C\uAC00 \uAC00\uB2A5\uD558\uBBC0\uB85C \n // \uC0AD\uC81C \uD55C \uB4A4\uC5D0 \uC544\uB798 \uC138\uAC00\uC9C0 \uD615\uD0DC \uC911 \uD55C\uAC00\uC9C0\uB85C \uB0A8\uAC8C \uB41C\uB2E4.\n // 1) 0 ~ x \n // 2) y ~ n-1\n // 3) 0 ~ x, y ~ n-1\n \n // 2. \uAC1C\uC218\n // 1) 0 ~ x : 0~0, 0~1, 0~2 ... 0~x \uCD1D x\uAC1C \n // 2) y ~ n-1 : y~n-1, y+1~n-1, n-1~n-1 \uCD1D n-y\uAC1C \n // 3) 0 ~ x, y ~ n-1 \n // \uC55E\uC5D0 list\uC758 \uB9C8\uC9C0\uB9C9 \uB4A4\uC5D0 \uC774\uC5B4\uC9C8 \uAC12\uC774 \uB4A4\uC5D0 list\uC5D0 \uC788\uB294\uC9C0 \uD655\uC778\uD558\uACE0 \uD574\uB2F9\uD558\uB294 \uACF3\uBD80\uD130 list\uB9C8\uC9C0\uB9C9\uAE4C\uC9C0\uC758 \uAC1C\uC218\n // \u203B binarySearchUpper\uB97C \uC774\uC6A9\uD574 \uC704\uCE58\uB97C \uCC3E\uC544\uC900\uB2E4.\n // ex) 1,2,3 ... 1,2,3 \uD615\uD0DC\uC774\uBA74 \n // \uC55E\uC5D0\uC11C 1\uB9CC \uB0A8\uAE38 \uB54C 2,3 \uB450 \uAC00\uC9C0 \uACBD\uC6B0\uAC00 \uC0DD\uAE34\uB2E4. \n // [1,2,3], [1,3] (\u203B [1]\uC740 1)\uC758 \uACBD\uC6B0\uC5D0 \uD3EC\uD568) \n // \uC55E\uC5D0\uC11C 1,2\uB9CC \uB0A8\uAE38 \uB54C 3 \uD55C \uAC00\uC9C0 \uACBD\uC6B0\uAC00 \uC0DD\uAE34\uB2E4. \n // [1,2,3]\n // \uC55E\uC5D0\uC11C 1,2,3\uC744 \uB0A8\uAE38 \uB54C\uB294 \uB4A4\uC5D0\uC11C \uB0A8\uAE38 \uC218 \uC5C6\uB2E4. \n\n \n List<Integer> frontList = new ArrayList<Integer>();\n List<Integer> backList = new ArrayList<Integer>();\n\n long result = 0;\n\n int before = 0;\n for(int i = 0; i < nums.length; i++) {\n if ( nums[i] > before ) {\n frontList.add(nums[i]);\n before = nums[i];\n } else break;\n }\n\n if ( frontList.size() == nums.length ) {\n\n for(int i = 1; i <= nums.length; i++) result += i;\n return result;\n }\n\n before = Integer.MAX_VALUE;\n for(int i = nums.length-1; i>= 0; i--) {\n if ( nums[i] < before ) {\n backList.add(0, nums[i]);\n before = nums[i];\n } else break;\n }\n\n result = 1; // empty Array\n\n result += frontList.size() + backList.size();\n\n for(int i = 0; i < frontList.size(); i++) {\n int idx = binarySearchUpper(backList, frontList.get(i));\n result += backList.size()-idx;\n }\n\n // System.out.println(frontList + " " + backList);\n\n return result;\n }\n\n private int binarySearchUpper(List<Integer> list, int target) {\n int start = 0;\n int end = list.size();\n int mid;\n\n while(start < end) {\n mid = (start +end)/2;\n\n if ( list.get(mid) > target) {\n end = mid;\n } else{\n start = mid+1;\n }\n }\n\n return end;\n }\n}\n```
0
0
['Binary Search', 'Java']
0
count-the-number-of-incremovable-subarrays-ii
Java Beats 100%, Fastest solution
java-beats-100-fastest-solution-by-laksh-byqv
Intuition\nCheck conitnuous increasing subarrays in start and at the end.\n\nclass Solution {\n public int incremovableSubarrayCount(int[] nums) {\n i
lakshyasaharan1997
NORMAL
2024-03-30T05:32:29.410364+00:00
2024-03-30T05:32:29.410398+00:00
8
false
# Intuition\nCheck conitnuous increasing subarrays in start and at the end.\n```\nclass Solution {\n public int incremovableSubarrayCount(int[] nums) {\n if (nums.length == 1)\n return 1;\n\n int n = nums.length;\n int res = 0;\n\n // left side\n int li = 0, lj = 1;\n while (lj < n) {\n if (nums[lj] <= nums[lj-1])\n break;\n lj++;\n }\n lj--;\n if (lj == n-1)\n return (n * (n + 1)) / 2;\n\n res += lj - li + 1;\n\n // right side\n int ri = n - 2, rj = n - 1;\n while (ri > 0) {\n if (nums[ri] >= nums[ri+1])\n break;\n ri--;\n }\n ri++;\n res += rj - ri + 1;\n\n // middle\n for (int i = li; i <= lj; i++) {\n int j = ri;\n while (j < n) {\n if (nums[j] > nums[i]) {\n res += rj - j + 1;\n break;\n }\n j++;\n }\n }\n\n return res+1;\n }\n}\n```
0
0
['Java']
0
count-the-number-of-incremovable-subarrays-ii
Java Beats 100%, Fastest solution
java-beats-100-fastest-solution-by-laksh-015a
Intuition\nCheck conitnuous increasing subarrays in start and at the end.\n\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n
lakshyasaharan1997
NORMAL
2024-03-30T05:31:22.988377+00:00
2024-03-30T05:31:22.988400+00:00
4
false
# Intuition\nCheck conitnuous increasing subarrays in start and at the end.\n```\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n if (nums.length == 1)\n return 1;\n\n int n = nums.length;\n long res = 0;\n\n // left side\n int li = 0, lj = 1;\n while (lj < n) {\n if (nums[lj] <= nums[lj-1])\n break;\n lj++;\n }\n lj--;\n if (lj == n-1)\n return (n * (n + 1)) / 2;\n\n res += lj - li + 1;\n\n // right side\n int ri = n - 2, rj = n - 1;\n while (ri > 0) {\n if (nums[ri] >= nums[ri+1])\n break;\n ri--;\n }\n ri++;\n res += rj - ri + 1;\n\n // middle\n for (int i = li; i <= lj; i++) {\n int j = ri;\n while (j < n) {\n if (nums[j] > nums[i]) {\n res += rj - j + 1;\n break;\n }\n j++;\n }\n }\n\n return res+1;\n }\n}\n```
0
0
['Java']
0
count-the-number-of-incremovable-subarrays-ii
Simple Binary Search || Easy to understand || Beats 100% || C++
simple-binary-search-easy-to-understand-judzi
Complexity\n- Time complexity:O(nlogn)\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#
dubeyad2003
NORMAL
2024-03-26T10:51:50.372353+00:00
2024-03-26T10:51:50.372385+00:00
5
false
# Complexity\n- Time complexity:$$O(nlogn)$$\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 long long incremovableSubarrayCount(vector<int>& nums) {\n int el = -1;\n int i = 0;\n int n = nums.size();\n while(i < n && nums[i] > el) el = nums[i++];\n int fs = i;\n i = n-1;\n el = 1e9 + 7;\n while(i >= 0 && nums[i] < el) el = nums[i--];\n int ss = i+1;\n long long ans = 0;\n if(fs > ss) return (1LL * fs * (fs + 1)) / 2;\n if(fs <= ss)\n for(int i=0; i<fs; i++){\n int id = upper_bound(nums.begin() + ss, nums.end(), nums[i]) - nums.begin();\n ans += n - id + 1;\n }\n ss = n - ss;\n ans += ss + 1;\n return ans;\n }\n};\n```
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
C++ STL based solution
c-stl-based-solution-by-rishabhrd-66bf
We don\'t have a is_strictly_sorted_until function. (We have a is_sorted_until function though). So, implemented the same and applied sliding window.\ncpp\nusin
RishabhRD
NORMAL
2024-03-19T14:23:50.883612+00:00
2024-03-19T14:23:50.883647+00:00
6
false
We don\'t have a is_strictly_sorted_until function. (We have a is_sorted_until function though). So, implemented the same and applied sliding window.\n```cpp\nusing ll = long long;\n\ntemplate <typename ForwardIter, typename Comparator>\nauto is_strictly_sorted_until(ForwardIter begin, ForwardIter end,\n Comparator cmp) {\n auto pred = std::not_fn(cmp);\n auto itr = std::adjacent_find(begin, end, pred);\n if (itr == end)\n return end;\n return std::next(itr);\n}\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(std::vector<int> &nums) {\n ll const n = nums.size();\n auto begin = nums.begin();\n auto end = nums.end();\n ll cnt = 0;\n auto begin_non_sorted = is_strictly_sorted_until(begin, end, std::less<>{});\n if (begin_non_sorted == end)\n return (n * (n + 1)) / 2;\n auto end_non_sorted =\n is_strictly_sorted_until(std::rbegin(nums), std::rend(nums),\n std::greater<>{})\n .base();\n cnt += (end - end_non_sorted) + 1;\n auto left = begin;\n auto right = end_non_sorted;\n while (left != begin_non_sorted) {\n while (right != end && *right <= *left) {\n ++right;\n }\n cnt += (end - right) + 1;\n ++left;\n }\n return cnt;\n }\n};\n```\n
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
xxx
xxx-by-elitecoder666-h92z
\n\n# Code\n\nuse std::collections::HashSet;\n\nimpl Solution\n{\n pub fn incremovable_subarray_count(nums: Vec<i32>) -> i64\n {\n let mut ans = 1;
elitecoder666
NORMAL
2024-03-02T08:53:47.793254+00:00
2024-03-02T08:53:47.793276+00:00
2
false
\n\n# Code\n```\nuse std::collections::HashSet;\n\nimpl Solution\n{\n pub fn incremovable_subarray_count(nums: Vec<i32>) -> i64\n {\n let mut ans = 1;\n\n let mut l = 0;\n while l < nums.len() && (l == 0 || nums[l] > nums[l - 1])\n {\n ans += 1;\n l += 1;\n }\n\n if l == nums.len()\n {\n let ns = nums.len() as i64;\n return (ns + 1) * ns / 2;\n }\n\n let mut r = nums.len() - 1;\n while r == nums.len() - 1 || nums[r] < nums[r + 1]\n {\n ans += 1;\n r -= 1;\n }\n\n let mut j = r;\n for i in 1..=l\n {\n while j < nums.len() - 1 && nums[i - 1] >= nums[j + 1]\n {\n j += 1;\n }\n\n if j == nums.len() - 1\n {\n break;\n }\n\n ans += (nums.len() - 1 - j) as i64;\n }\n\n return ans;\n }\n}\n```
0
0
['Rust']
0
count-the-number-of-incremovable-subarrays-ii
Hot | 15 lines | Two Pointer | Linear | Python | Interview Thoughts
hot-15-lines-two-pointer-linear-python-i-merg
Two Pointer\nMy first thought is to use dynamic programming to find out the number of increasing subsequences, however it turned out that I was misundrestanding
jandk
NORMAL
2024-03-01T08:26:00.971937+00:00
2024-03-01T08:26:27.912957+00:00
8
false
### Two Pointer\nMy first thought is to use dynamic programming to find out the number of increasing subsequences, however it turned out that I was misundrestanding the problem.\nRemember to read the question carefully, and what it asks is to return the number of strictly increasing subarrays by removing one subarrays.\nOnce you get the idea about what this problem is asking for, you resolved this problem by half.\nSo in order to get the increasing subarray by removing one subarray, we got only 3 patterns removing the subarray, **left end**, **right end** and **middle part**.\nLet\'s use `[1,2,1,2,3,4]` as example to look at how to find the subarray for each patternn.\n\n#### Left end\nLeft end means the subarray we are going to remove starts from index `0` and the rest is increasing after it ends. So it asks us to find the longest increasing subarray ending at the last index. In our example, the subarray is to remove is `[1,2]`, and the longest increasing subarray from right side is `[1,2,3,4]`.\nThen how many incremovable subarrays we can get? the starting poit should be at index `0`, and it can ends at each index in the increasing subarray `[1,2,3,4]`, meaning we got 4, equivalent to the *length* of the longest increasing subarray from right side.\n#### Right end\nSimilarly, right end means the subarray to remove ends at index `n - 1` and the rest is increasing strictly from the beginning of the `nums`, which requires to find out the longest increasing subarray starting at index `0`. And the number of incremovable subarrays equals to the *length* of it.\n\n#### Middle part\nThe middle part means the subarray to remove doesn\'t start with index `0` and end at index `n - 1` either. So we have to guarantee the last num in left end is smaller than the first element of right end. \nIn the example, if we fix left end `[1,2]`, then we have 2 options to remove the subarrays in `[1,2,3,4]`, which are `[1,2]` and `[1,2,3]`, meaning the number of nums that are larger than `[2]` in right part.\nWhy doesn\'t it include `[1,2,3,4]`? because it is already covered by **right end** pattern.\nBut do we need to use binary search to find the number of elements that are larger than each interger in left part?\nNo, we can use two pointer to find the number in linear time. \n\n#### Algorithm\nSo putting them together\n1. We find the longest increasing subarray from left and right side respectively\n2. count the length of left part and right part\n3. Calculate the number of incremovable subarrays using the length\n4. move the pointer`r` for right part to the position where it is larger than the integer indexed at `l` that is last element in the left side.\n5. caculate the number of subarrays for each pair of `l` and `r` while moving `l` to `0` and `r` assuring `nums[r]` is larger than `nums[l]`.\n\n```python\ndef incremovableSubarrayCount(self, nums: List[int]) -> int:\n\tleft = 0\n\tn = len(nums)\n\twhile left + 1 < n and nums[left + 1] > nums[left]:\n\t\tleft += 1\n\tif left == n - 1:\n\t\treturn (1 + n) * n // 2\n\tright = n - 1\n\twhile right - 1 >= 0 and nums[right - 1] < nums[right]:\n\t\tright -= 1\n\tcount = left + 1 + (n - right) + 1 # left end + right end, the last + 1 means the empty subarray \n\tl, r = left, n - 1\n\twhile l >= 0:\n\t\twhile r >= right and nums[r] > nums[l]:\n\t\t\tr -= 1\n\t\tcount += (n - r - 1)\n\t\tl -= 1 \n\treturn count\n```\n\n*Time Complexity* = **O(N)**\n*Space Complexity* = **O(1)**\n\n\n
0
0
['Python']
0
count-the-number-of-incremovable-subarrays-ii
Binary Search | Well Explained Code | O(n*log(n))
binary-search-well-explained-code-onlogn-n4ax
Code\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n // Fast I/O optimization\n ios_base::sync_with_s
coderpriest
NORMAL
2024-02-26T04:59:44.099836+00:00
2024-02-26T04:59:44.099877+00:00
9
false
# Code\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n // Fast I/O optimization\n ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n\n // Initialize variables\n long long n = nums.size(), j = n - 1;\n\n // Find the rightmost index from where the array is not in increasing order upto end\n while (j > 0 and nums[j - 1] < nums[j]) j--;\n\n // If the entire array is in increasing order, return the total count of subarrays\n if (j == 0) return (n * (n + 1)) / 2;\n\n // Initialize variables for the final answer calculation\n long long ans = n - j + 1, last = -1; \n\n // Iterate through the array and count removable subarrays\n for (int i = 0; nums[i] > last; last = nums[i], i++)\n ans += n - (int)(upper_bound(nums.begin() + j, nums.end(), nums[i]) - nums.begin()) + 1;\n\n // Return the final count of increasing removable subarrays\n return ans;\n }\n};\n\n```
0
0
['Array', 'Two Pointers', 'Binary Search', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
:: Kotlin ::
kotlin-by-znxkznxk1030-5a72
Intuition\nSplit array to sorted lists.\nOne starts from left while other starts from right.\n\n# Approach\nSplit array to sorted lists.\nOne starts from left w
znxkznxk1030
NORMAL
2024-02-15T11:40:07.307584+00:00
2024-02-15T11:40:07.307615+00:00
1
false
# Intuition\nSplit array to sorted lists.\nOne starts from left while other starts from right.\n\n# Approach\nSplit array to sorted lists.\nOne starts from left while other starts from right.\nIterate through the list on the right and add the number on the left that is less than each item.\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\n fun incremovableSubarrayCount(nums: IntArray): Long {\n val left = mutableListOf<Int>()\n val right = mutableListOf<Int>()\n val n = nums.size\n\n var prev = 0\n for (i in 0 until n) {\n if (nums[i] <= prev) break\n left.add(nums[i])\n prev = nums[i]\n }\n\n var post = Int.MAX_VALUE\n for (i in n - 1 downTo 0) {\n if (nums[i] >= post) break\n right.add(nums[i])\n post = nums[i]\n }\n right.reverse()\n // left.forEach{ print("$it ")}\n // println()\n // right.forEach{ print("$it ")}\n // println()\n if (left.size == n) return n.toLong() * (n.toLong() + 1L) / 2L\n\n val l = left.size\n val r = right.size\n var result = 1L\n\n result += l.toLong()\n result += r.toLong()\n\n for (i in 0 until r) {\n val target = right[i]\n\n var lo = 0\n var hi = minOf(n - r + i, left.size)\n // println("$lo - $hi")\n while(lo < hi) {\n val mid = lo + (hi - lo) / 2\n\n if (left[mid] < target) {\n lo = mid + 1\n } else {\n hi = mid\n }\n }\n\n // println("lo = $lo")\n if (lo != 0) result += lo.toLong()\n }\n\n return result\n }\n}\n```
0
0
['Kotlin']
0
count-the-number-of-incremovable-subarrays-ii
Count what is left instead of removal
count-what-is-left-instead-of-removal-by-77gb
Intuition\n- focus on what is left after removal\n- it has to be some prefix, concat with, some suffix\n\n# Approach\n- find maximal increasing prefix P and max
lambdacode-dev
NORMAL
2024-02-02T21:39:11.268421+00:00
2024-02-02T21:39:11.268448+00:00
1
false
# Intuition\n- focus on what is left after removal\n- it has to be some prefix, concat with, some suffix\n\n# Approach\n- find maximal increasing prefix `P` and maximal increasing suffix `S`\n- for each prefix of `P`, incrementally count (using two pointers) how many suffix of `S` can be concated to make final increasing array.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n int n = nums.size();\n int I = 0; // last index of increasing prefix \n int J = n - 1; // first index of increasing suffix\n for(int i = 1; i < n && nums[i] > nums[i-1]; ++i, ++I);\n if(I == n-1)\n return n*(n+1)/2;\n \n for(int i = n - 2; i >= 0 && nums[i+1] > nums[i]; --i, --J);\n \n // count what is left, instead removal\n long long ans = \n (I+2) + // only prefix of front inc\n (n-J+1) + // only suffix of back inc\n -1 ; // minus 1 b/c duplicate empty sub array\n \n // prefix [0,i] + some suffix\n for(int i = 0, j = J; i <= I; ++i) { \n while(j < n && nums[j] <= nums[i]) ++j;\n ans += n - j;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
Two Pointer bigO(N), easy to understand.
two-pointer-bigon-easy-to-understand-by-fs2lj
Intuition\nThe key idea is to identify all potential subarrays whose removal would make the entire array strictly increasing. We do this by identifying the long
user1952E
NORMAL
2024-01-31T19:27:30.393035+00:00
2024-01-31T19:27:30.393057+00:00
2
false
# Intuition\nThe key idea is to identify all potential subarrays whose removal would make the entire array strictly increasing. We do this by identifying the longest non-increasing prefix and suffix in the array. Any subarray starting within this prefix and ending within this suffix is a candidate for removal.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Find Longest Non-Increasing Prefix and Suffix: We start by identifying the longest non-increasing prefix and suffix in the array. These will serve as the boundaries for our candidate subarrays.\n\n1. Iterate with Two Pointers: Using two pointers, we iterate through the array to count all valid subarrays. We ensure that:\n\n - The end pointer does not overlap with the start pointer.\n - The element just after the end pointer is greater than the element just before the start pointer.\n# Complexity\n- Time complexity: O(n), where n is the length of the array. We iterate through the array only once with two pointers.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1), as we only use a fixed amount of extra space.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n int n = nums.length;\n int l = 0; // Longest non-increasing prefix\n int r = n - 1; // Smallest non-increasing suffix\n long count = 0;\n\n // Finding the longest non-increasing prefix\n while (l < n - 1 && nums[l + 1] > nums[l]) {\n l++;\n }\n\n // Finding the smallest non-increasing suffix\n while (r > 0 && nums[r - 1] < nums[r]) {\n r--;\n }\n\n l++;\n r--;\n\n // Iterating through the array with two pointers\n for (int i = 0; i <= l && i < n; i++) {\n while (r < n) {\n // Avoid overlap\n if (r < i) {\n r++;\n }\n // Ensure the subarray removal leads to strictly increasing order\n else if ((r <= n - 2 && i >= 1) && nums[r + 1] <= nums[i - 1]) {\n r++;\n } else {\n break;\n }\n }\n count += n - r;\n }\n return count;\n }\n}\n```
0
0
['Two Pointers', 'Java']
0
count-the-number-of-incremovable-subarrays-ii
JAVA 1ms(100%), O(N) with 2-points
java-1ms100-on-with-2-points-by-meringue-x70o
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
meringueee
NORMAL
2024-01-31T06:02:44.278027+00:00
2024-01-31T06:02:44.278064+00:00
5
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 long incremovableSubarrayCount(int[] n) {\n long ans=0;\n int l, r;\n for(l=1; l<n.length&&n[l]>n[l-1]; l++);\n for(r=n.length-2; r>=0&&n[r]<n[r+1]; r--);\n if(r<0) return (long)(n.length+1)*n.length/2L;\n r++;\n ans += n.length-r+1;\n // System.out.println("-1\\t"+r);\n\n for(int i=0; i<l; i++){\n for(;r<n.length&&n[i]>=n[r];r++);\n // System.out.println(i+"\\t"+r);\n ans += n.length-r+1;\n }\n\n return ans;\n }\n}\n```
0
0
['Java']
0
count-the-number-of-incremovable-subarrays-ii
Java solution using binary search 🚀🚀
java-solution-using-binary-search-by-cha-pfjr
\nclass Solution {\n public int finder(int l, int h, int x, int nums[]) {\n int ans = nums.length;\n while (l <= h) {\n int mid = l
charlie-tej-123
NORMAL
2024-01-18T15:05:19.757522+00:00
2024-01-18T15:05:19.757545+00:00
5
false
```\nclass Solution {\n public int finder(int l, int h, int x, int nums[]) {\n int ans = nums.length;\n while (l <= h) {\n int mid = l + (h - l) / 2;\n if (nums[mid] > x) {\n ans = mid; \n h = mid - 1;\n } else {\n l = mid + 1;\n }\n }\n return ans;\n }\n\n public long incremovableSubarrayCount(int[] nums) {\n int n = nums.length;\n int lmax = 0, rmin = n - 1;\n\n int prev = nums[0];\n for (int i = 1; i < n; i++) {\n if (prev < nums[i]) {\n lmax++;\n } else {\n break;\n }\n prev=nums[i];\n }\n\n if (lmax == n-1) {\n return (long) n * (n + 1) / 2;\n }\n\n prev = nums[n - 1];\n for (int i = n - 2; i >= 0; i--) {\n if (prev > nums[i]) {\n rmin--;\n } else {\n break;\n }\n prev=nums[i];\n }\n\n long ans = 1l;\n ans += lmax + 1;\n ans += n - rmin;\n System.out.println(lmax+" "+rmin);\n for (int i = 0; i <=lmax; i++) {\n int p = finder(rmin, n - 1, nums[i], nums);\n //System.out.println(p);\n ans += n - p;\n }\n return ans;\n }\n}\n\n```
0
0
['Binary Search', 'Java']
0
count-the-number-of-incremovable-subarrays-ii
Python Solution | 2-pointer | 627ms, Beats 75% Time
python-solution-2-pointer-627ms-beats-75-6lzq
Approach\n Describe your approach to solving the problem. \nFirst, we identify the sorted prefix and suffix of the given array. We check if the entire array is
hemantdhamija
NORMAL
2024-01-17T05:40:31.501171+00:00
2024-01-17T05:40:31.501203+00:00
15
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, we identify the sorted prefix and suffix of the given array. We check if the entire array is already strictly increasing; if so, we return the total count of subarrays, considering an empty array as strictly increasing. Following that, we initialize a variable (ans) to the sum of the sizes of the prefix and suffix. Using two pointers, we iterate through the prefix and suffix simultaneously, counting subarrays where the last element of the prefix is smaller than the first element of the suffix. The final result is the total count of incremovable subarrays in the given array.\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```python []\nclass Solution:\n def incremovableSubarrayCount(self, nums: List[int]) -> int:\n leadingSubarray, trailingSubarray, sz = [], [], len(nums)\n for idx in range(sz):\n if not leadingSubarray or leadingSubarray[-1] < nums[idx]:\n leadingSubarray.append(nums[idx])\n else: break\n for idx in range(sz - 1, -1, -1):\n if not trailingSubarray or trailingSubarray[-1] > nums[idx]:\n trailingSubarray.append(nums[idx])\n else: break\n if len(leadingSubarray) + len(trailingSubarray) > sz:\n return (sz * (sz + 1)) // 2\n ans = len(leadingSubarray) + len(trailingSubarray)\n ptrLeading = ptrTrailing = 0\n trailingSubarray.reverse()\n while ptrLeading < len(leadingSubarray) and ptrTrailing < len(trailingSubarray):\n if leadingSubarray[ptrLeading] < trailingSubarray[ptrTrailing]:\n ans += (len(trailingSubarray) - ptrTrailing)\n ptrLeading += 1\n else: ptrTrailing += 1\n return ans + 1\n```
0
0
['Array', 'Two Pointers', 'Python', 'Python3']
0
count-the-number-of-incremovable-subarrays-ii
Two pointers to add two sorted arrays || Binary search
two-pointers-to-add-two-sorted-arrays-bi-19wa
\n# Code\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) \n {\n // check hints for the explanations \n
kirolachetan8
NORMAL
2024-01-13T19:35:13.881877+00:00
2024-01-13T19:35:13.881908+00:00
8
false
\n# Code\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) \n {\n // check hints for the explanations \n \n int n=nums.size();\n int X=0,Y=nums.size()-1;\n long long cnt=0;\n bool flagx=1,flagy=1;\n\n for(int i=1;i<nums.size();i++)\n {\n int x = i,y = nums.size()-i;\n\n if(nums[x]>nums[x-1] and flagx) X++;\n else flagx = 0;\n if(nums[y]>nums[y-1] and flagy) Y--;\n else flagy = 0;\n }\n\n if(X>=Y) // whole sorted array case cnt = n+(n-1)+(n-2)+(n-3)+...+1\n n--;\n\n int x=-1;\n\n while(x<=X)\n {\n if(x<0)\n cnt+=(n-Y+1);\n else\n {\n int idx = upper_bound(nums.begin()+Y,nums.end(),nums[x])-nums.begin();\n cnt+=(n-idx+1);\n }\n x++;\n }\n return cnt;\n }\n};\n```
0
0
['Two Pointers', 'Binary Search', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
Unique approach using monotonic stack.
unique-approach-using-monotonic-stack-by-0n90
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nSolution using monotonic stack\n\n# Complexity\n- Time complexity:\nO(n)\
TheBuddhist
NORMAL
2024-01-13T10:35:48.796791+00:00
2024-01-13T10:35:48.796812+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSolution using monotonic stack\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n #define sum(a) (1LL*a*(a+1)/2)\n long long incremovableSubarrayCount(vector<int>& a) {\n if(a.size()==1)return 1;\n if(a.size()==2)return 3;\n vector<int>stk;\n for(int i=0;i<a.size();i++){\n if(stk.empty() || a[stk.back()]<a[i]){\n stk.push_back(i);\n continue;\n }\n while(stk.size() && a[stk.back()]>=a[i])\n stk.pop_back();\n stk.push_back(i);\n }\n int l=0,r=(int)stk.size()-1,r_index=(int)a.size()-1;\n \n while(l<stk.size() && stk[l]==l)l++;\n while(r>=0 && stk[r]==r_index)r--,r_index--;\n int left=l+1;\n int right=(int)a.size()-r_index;\n if(l>r_index)return sum(a.size());\n\n auto ans= 1LL*left*right;\n int ans1=0;\n for(int i=l;i<=r_index;i++){\n if(i==0 || a[i]>a[i-1])ans1++;\n else break;\n }\n int ans2=0;\n r_index++;\n for(int i=l;i<l+ans1;i++){\n while(r_index<a.size() && a[i]>=a[r_index]){\n r_index++;\n }\n if(r_index<a.size() && a[r_index]>a[i])ans2+=(int)a.size()-r_index;\n }\n\n ans+=ans1+ans2;\n return ans;\n\n }\n};\n```
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
A simplfied c++ solution using dp
a-simplfied-c-solution-using-dp-by-gagan-a60a
\n\n# Code\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n long long p=0;\n int n=nums.size();\n
GagAn_R
NORMAL
2024-01-05T04:46:37.783668+00:00
2024-01-05T04:46:37.783698+00:00
25
false
\n\n# Code\n```\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n long long p=0;\n int n=nums.size();\n int dp[n],dp1[n];\n dp[0]=1;\n dp1[n-1]=1;\n for(int i=1;i<n;i++){\n if(nums[i]>nums[i-1]){\n dp[i]=min(dp[i-1],1);\n }else{\n dp[i]=0;\n }\n }\n for(int i=n-2;i>=0;i--){\n if(nums[i]<nums[i+1]){\n dp1[i]=min(dp1[i+1],1);\n }else{\n dp1[i]=0;\n }\n }\n for(int i=0;i<n;i++){\n int l=0;\n if(i!=0){\n l=nums[i-1];\n }\n int j=i,k=n-1;\n int mi=0;\n if(i==0 ||(i>0&& dp[i-1]==1)){\n while(j<=k){\n int mid=(j+k)/2;\n if(mid==n-1){\n mi=mid;\n break;\n }\n if(dp1[mid+1]==1 && nums[mid+1]>l){\n mi=mid;\n k=mid-1;\n }else{\n j=mid+1;\n }\n }\n long long f=n-mi;\n p+=f;\n }\n }\n\nreturn p;\n\n }\n};\n```
0
0
['Dynamic Programming', 'C++']
0
count-the-number-of-incremovable-subarrays-ii
gujju ben ni gamzzat #solution in gujarati # zakkas #bhukka_bolavi_nakhyaaa
gujju-ben-ni-gamzzat-solution-in-gujarat-685n
Intuition\n Describe your first thoughts on how to solve this problem. \nhave su 6e ke mare to incremovable subarray find out karvanu 6e ke jene remove karva pa
Gungun16
NORMAL
2024-01-04T15:33:21.746130+00:00
2024-01-04T15:33:21.746188+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nhave su 6e ke mare to incremovable subarray find out karvanu 6e ke jene remove karva par apdo array strictly increasing bani jase...\nsubarray su 6e => continuous non-empty sequence of elements 6e within an array...\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\naek kam kariye ke sauthi pehla to maximum subarray ke je increasing form thai sake 6e from the left and from the right ae find out karisu...=>\n\n**int n=nums.length;**\n**long ans=0;**\n**int left_idx=0, right_idx=n-1;**\n\nhave ae vastu to dhyan ma levani 6e ke agar jo subarray 6e then sequence vagar to aeno med j nahi padee.. atla mate to jya sudhin ae increasing 6e tya sudhi tame **left_idx** ne vadharta jaoo\n=>\n**while(left_idx+1<n && nums[left_idx]<nums[left_idx+1]){**\n **left_idx++;**\n**}**\n**System.out.println("left_idx: "+left_idx);**\n\n...aevuj similar karo right_idx mate ...jya sudhi increasing subarray made 6e -> tya sudhi tamaro right_idx-- ne decrement karta jaoo....=> \n**while(right_idx-1>=0 && nums[right_idx-1]<nums[right_idx]){**\n **right_idx--;**\n**}**\n**System.out.println("right_idx: "+right_idx);**\n\n//aek aevo base case avi sake before dealing with the normal cases jya ke tamri pase left mathi thodak elements 6e and right mathi thoda elements 6e...\n=> ke jyare tamaro left check chelle sudhi pohchi jai...then aeno matlabke subarray koi pan length ni leso aeno answer tamne mdse jj....=> to aena mate ...\n\n1. 1 length no subarray na options are : n\n2. 2 length na subarray na options are : n-1\n3. 3 length na subarray na options are : n-2\n... \nn. n length no subarray na options are : 1\n=> so evaluating all the answers we get = (n)+(n-1)+ ... 1 \n= ((n)* (n+1)) /2\n\n---\n6, 5, 7, 8 = 6 | 5, 7, 8 \nnow moving to some case ke jyare tamari pase left portion akhuj nathi leta then su karso ... then jetla number of elements tamari pase right ma 6e atla possible subarrays thase ...(have ahiya right ma 3 elements 6e to 3 possible subarrays thay sake 6e ...when we don\'t want to take the left array...=> [5,7,8] , [7,8] , [8])\n=>\n**ans+= (n- right_idx+1);**\n**System.out.println("ans : "+ans);**\n\n---\n**for(int i=0;i<=left_idx;i++){}**\n\n\nfor all the possible left_idx find this particual thing and add into your result...\n\nhave to chalu thai tamari asli talash ...seni ke agar jo hu aa left_idx sudhin elements lai 6e then mara array ma right increasing part mathi kya thi elements ne lai saku 6u...\n\ndekh ke je vache na elements 6e ne => kaya?? **(left_idx+1)** thi laine **(right_idx-1)** sudhin aemne to mare compulsory kadhvaj padse ....ae loko to kasa kamna j nathi...\n\nmara badha left_idx mate aevo right_portion no index find out karo ke maro resulting subarray formed by concatenating= [0,left_idx]+ [ i, n-1] => increasing subarray form kare and vache no portion ne deleted declare kari sakay... [left_idx+1, i-1]\n\naek haji vat samajhva jevi 6e ke i thi laine n-1 sudhi nahi ...to-to aek j subarray thayo ne but ..what I want to do is ke ith index thi laine n-1 sudhi tame have aa left_idx mate values ne lai sako 6o... atle ke subarrays can be \n1.[0, left_idx] + [i, n-1]\n2.[0, left_idx] + [i+1, n-1]\n3.[0, left_idx] + [i+2, n-1]\n...\nn- upper_bound+1 => atla elements bachse for the given upper bound idx to come.\n\ni to just sharuat 6e ke ahiya thi tame lai sako 6o and then aeno and aena agad na ne levo nahi levo ae nirnay to tamara upar j 6e...\n\nto hu mara left_idx vada number mate hu find karis ke aenu upper_bound su 6e ...ke jena thi tya thi laine aena right_portion vada nums mathi find out kari saku....to aena mate to you can find out the upper bound for each such left_idx in the right portion ke kya thi right_portion mathi start karu...\n\n**int upper_bound_idx= get_upper_bound(nums,right_idx,n-1,nums[i]);**\n**System.out.println("i: "+i+" upper_bound_idx: "+upper_bound_idx);**\n**ans+= (n-upper_bound_idx+1 );**\n\n---\n\nupper_bound no matlab ke aena thi to just greater element ne find out karvano 6e...\n\nbinary search j perform karso pan agar jo element tamara target karta nano ke equal madi gyo then search for the possibility ke have to mane ana karta sej j moto element joi 6ee=> atle window ne right side ma shift karidoo...\n=>\n/****************/\n public static int get_upper_bound(int nums[],int low,int high,int key){\n \n while(low<=high){\n **int mid=(low+high)/2;**\n if(nums[mid]<=key){\n low=mid+1;\n }else {\n high=mid-1;\n }\n }\n return low;\n }\n\n/*************/\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\ngetting the left : O(n)\ngetting the right : O(n)\ntraversing through for each left : O(n)\nfor each left get the upperbound in : O(log(n))\n====\nOverall time complexity si : O(n* (log(n)))\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nNo auxillary space is used ... O(1)\n\n# Code\n```\nclass Solution {\n \n public long incremovableSubarrayCount(int[] nums) {\n int n=nums.length;\n long ans=0;\n int left_idx=0, right_idx=n-1;\n\n /*get the left idx */\n while(left_idx+1<n && nums[left_idx]<nums[left_idx+1]){\n left_idx++;\n }\n System.out.println("left_idx: "+left_idx);\n\n while(right_idx-1>=0 && nums[right_idx-1]<nums[right_idx]){\n right_idx--;\n }\n System.out.println("right_idx: "+right_idx);\n\n /*when all the elements in the array are strictly increasing => this is the base case. */\n if(left_idx==n-1){\n ans=(n)* (n+1);\n return ans/2;\n }\n/*have dharoke tame koi pan left portion j nathi leta then */\n ans+= (n- right_idx+1);\n System.out.println("ans : "+ans);\n\n /*now we would go on starting the point from the left */\n for(int i=0;i<=left_idx;i++){\n int upper_bound_idx= get_upper_bound(nums,right_idx,n-1,nums[i]);\n System.out.println("i: "+i+" upper_bound_idx: "+upper_bound_idx);\n ans+= (n-upper_bound_idx+1 );\n }\n return ans;\n }\n public static int get_upper_bound(int nums[],int low,int high,int key){\n \n while(low<=high){\n int mid=(low+high)/2;\n if(nums[mid]<=key){\n low=mid+1;\n }else {\n high=mid-1;\n }\n }\n return low;\n }\n /******************************************* */\n// public long incremovableSubarrayCount(int[] nums) {\n// int n=nums.length;\n// long ans=0;\n// int left_idx=0, right_idx=n-1;\n\n// /*get the left idx */\n// while(left_idx+1<n && nums[left_idx]<nums[left_idx+1]){\n// left_idx++;\n// }\n// System.out.println("left_idx: "+left_idx);\n\n// while(right_idx-1>=0 && nums[right_idx-1]<nums[right_idx]){\n// right_idx--;\n// }\n// System.out.println("right_idx: "+right_idx);\n\n// /*when all the elements in the array are strictly increasing => this is the base case. */\n// if(left_idx==n-1){\n// ans=(n)* (n+1);\n// return ans/2;\n// }\n// /*have dharoke tame koi pan left portion j nathi leta then */\n// ans+= (n- right_idx+1);\n// System.out.println("ans : "+ans);\n// int r=right_idx;\n// /*now we would go on starting the point from the left */\n// for(int l=0;l<=left_idx;l++){\n \n// while(r<n && nums[l]>=nums[r]){\n// r++;\n// }\n// ans+= (n-r+1);\n// }\n// return ans;\n// }\n\n}\n```
0
0
['Java']
0
count-the-number-of-incremovable-subarrays-ii
Java Solution. Detailed Explanation!
java-solution-detailed-explanation-by-aa-r2oc
Intuition\nI was trying randomly to divide into groups of Increasing Sequence. Then thought of 2 cases where there is 1 group and n groups as both these scenari
aakashg1999
NORMAL
2024-01-03T16:38:21.934339+00:00
2024-01-03T16:38:21.934370+00:00
3
false
# Intuition\nI was trying randomly to divide into groups of Increasing Sequence. Then thought of 2 cases where there is 1 group and n groups as both these scenarios will cover all the possible cases.\n\n# Approach\n1. First Do a Traversal to capture all the groups of Increasing Sequence. But we actually require only group 1 and last group so there is room for improvement here. But in worst case same Time complexity will be there so did not think much.\n2. If number of groups is 1 then answer is (n+1)C(2) as we need to pick any 2 indexes from n+1(**not n**) to generate all sub-arrays. where n is number of elements in nums\n3. If there are n Groups, answer is summation of following cases. Let\'s Take the example (6,10,12,15,9,11,14,13,14,16).\nHere Group 1 is (6,10,12,15) and Group n is (13,14,16).\n**3.1.** 1 possible solution is to take all the elements (remove all)\n**3.2.** Then we can make combinations with Group1 only = Length of Group1.\n**3.3.** Same for Group N. \n**3.4.** Then we can take last element of Group1 and see which is the least element in Group N greater than this element for example initially, from\n6,10,12,15 take 15 and see which is greater than 15 in Group N - ans is 16. So there is only 1 element greater. We can make 1 combination thus add it. Again for 12, 13 is the least greater than 12 so that makes it 13,14,16, 3 elements in GroupN are greater than 12 thus 3 combinations - Add them. Similary do for all elements in Group1.\n\n\n# Code\n```\nclass Pair{\n int start;\n int end;\n\n Pair(int start, int end){\n this.start = start;\n this.end = end;\n }\n}\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n // We need to group the strictly increasing subarrays and then the answer depends if 1 group or n group are there.\n // If 1 Group then answer is (n+1)C(2) as we need to pick any 2 index from n+1 index to generate\n // All sub Arrays as 1 group mean we can pick any sub-Array. if N Group then answer depends on group 1 and n.\n\n List<Pair> groups = new ArrayList<>();\n int n = nums.length;\n int start = 0;\n long ans = 0;\n for(int i = 0; i<n; i++){\n if(i!=n-1){\n if(nums[i] >= nums[i+1]){\n groups.add(new Pair(start, i));\n start = i+1;\n }\n }else{\n groups.add(new Pair(start, n-1));\n }\n }\n\n if(groups.size() == 1){\n if(n%2 == 0){\n ans += n+1;\n ans *= (n/2);\n }else{\n ans += n;\n ans *= ((n+1)/(2));\n }\n }else{\n ans += 1; // remove all elements 3.1\n Pair group1 = groups.get(0); \n Pair groupn = groups.get(groups.size()-1);\n\n ans += (group1.end - group1.start + 1); // 3.2\n ans += (groupn.end - groupn.start + 1); // 3.3\n\n int end = group1.end;\n if(nums[group1.start] < nums[groupn.end]){\n while ((end<=group1.end && end>=0)){\n int key = nums[end];\n int res = binarySearchLower(nums, groupn.start, groupn.end, key);\n if(res != -1){\n int numOfEl = groupn.end - res + 1;\n ans += numOfEl;\n }\n end--;\n } \n }\n }\n return ans;\n }\n\n private int binarySearchLower(int[] nums, int start, int end, int key){\n int ans = -1;\n int l = start;\n int r = end;\n while (l<=r){\n int mid = (l+r)/2;\n \n if(nums[mid] <= key){\n l = mid + 1;\n }else{\n ans = mid;\n r = mid - 1;\n }\n }\n return ans;\n }\n}\n```
0
0
['Java']
0
count-the-number-of-incremovable-subarrays-ii
Simple binary Search Solution C++
simple-binary-search-solution-c-by-rahul-rmll
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
rahulss2899
NORMAL
2024-01-03T01:11:22.215187+00:00
2024-01-03T01:11:22.215215+00:00
8
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 long long incremovableSubarrayCount(vector<int>& nums) {\n if(nums.size()==1)return 1;\n vector<long long>suff,pre;\n suff.push_back(nums.back());\n for(int i=nums.size()-2;i>=0;i--){\n if(nums[i]<nums[i+1])suff.push_back(nums[i]);\n else break;\n\n }\n if(suff.size()==nums.size())\n return ((nums.size()*(nums.size()+1))/2);\n \n reverse(suff.begin(),suff.end());\n pre.push_back(nums[0]);\n for(int i=1;i<nums.size();i++){\n if(nums[i]>nums[i-1])pre.push_back(nums[i]);\n else break;\n }\n long long ans=suff.size()+1;\n \n for(auto i:pre){\n ans+=suff.size()-(upper_bound(suff.begin(),suff.end(),i)-suff.begin())+1;\n \n }\n return ans; \n\n }\n};\n```
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
java
java-by-harshaddhongade1-a8kg
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
harshaddhongade1
NORMAL
2024-01-01T08:39:43.587040+00:00
2024-01-01T08:39:43.587065+00:00
3
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 long incremovableSubarrayCount(int[] nums) {\n long ans = 1;\n int r = 1;\n int n = nums.length;\n\n while (r < n && nums[r] > nums[r - 1]) {\n r++;\n }\n\n if (r == n) {\n return (long) n * (n + 1) / 2;\n }\n\n int lst = Integer.MAX_VALUE;\n ans += r;\n\n for (int i = n - 1; i >= 0; i--) {\n if (nums[i] >= lst) {\n break;\n }\n int low = 0, high = r - 1;\n int left = -1;\n\n while (low <= high) {\n int mid = (low + high) >> 1;\n if (nums[mid] < nums[i]) {\n left = mid;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n ans += (left + 2);\n lst = nums[i];\n }\n\n return ans;\n }\n}\n\n\n```
0
0
['Java']
0
count-the-number-of-incremovable-subarrays-ii
best approach
best-approach-by-av_77-fm6l
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\ncount number of elements that are increaing from start [ count1 ].\ncount
AV_77
NORMAL
2023-12-30T17:47:39.075250+00:00
2023-12-30T17:47:39.075301+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ncount number of elements that are increaing from start [ count1 ].\ncount number of element that are decreasing from end [ count2 ].\n\ncount subarray that can be made using combinations of subarray [nums[0]-nums[i]] and subarray [nums[j]-nums[nums.size()-1]] that made increasing subarray\nfor better understanding go through the code .\n\nfinally return ans+1 because (+1 due to empty subarray)\n<!-- Describe your approach to solving the problem. -->\n\n\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 long long incremovableSubarrayCount(vector<int>& nums) {\n long long int ans=0;\n \n int i=0;\n while( i+1<nums.size() && nums[i]<nums[i+1])\n {\n i++;\n ans++;\n }\n ans++;\n \n\n if(ans==nums.size())\n {\n int x= ans*(ans+1);\n return x/2;\n }\n\n int j=nums.size()-1;\n while(j-1>=0 && nums[j]>nums[j-1])\n {\n ans++;\n j--;\n }\n ans++;\n\n // return ans;\n int l=j;\n\n // cout<<i<<" "<<l<<endl;\n for(int k=0;k<=i;k++)\n {\n if(nums[k]<nums[l])\n {\n ans=ans+nums.size()-l;\n }\n else{\n while(l<nums.size() && nums[k]>=nums[l])\n {\n l++;\n if( l<nums.size() && nums[k]<nums[l] )\n {\n ans=ans+nums.size()-l;\n break;\n }\n }\n }\n\n l=j;\n }\n return ans+1;\n\n }\n};\n```
0
0
['C++']
0
count-the-number-of-incremovable-subarrays-ii
Java | Binary Search | Two Pointers
java-binary-search-two-pointers-by-coder-rqp1
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
coderater
NORMAL
2023-12-30T14:48:19.102781+00:00
2023-12-30T14:48:19.102799+00:00
3
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)$$ --> O(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n# Code\n```\nclass Solution {\n public long incremovableSubarrayCount(int[] nums) {\n int l = 0, h = nums.length-1 , n= nums.length;\n while(l < (nums.length -1) && nums[l] < nums[l+1]) l++;\n while(h > 0 && nums[h-1] < nums[h]) h--;\n long res = 0;\n if(l!=n-1) res = res + (n-h)+1; // Game Changer\n for(int i=0;i<=l;i++){\n int target = nums[i];\n int lo = h ,hi = nums.length-1,ans = nums.length;\n while(lo<=hi){\n int mid = (lo+hi)/2;\n if(nums[mid] > target){\n ans = mid;\n hi = mid -1;\n }else{\n lo = mid+1 ;\n }\n }\n System.out.println(ans);\n res = res + (nums.length-ans)+1;\n\n\n }\n return res;\n\n }\n}\n```
0
0
['Java']
0
count-the-number-of-incremovable-subarrays-ii
Upper Bound -> Two Pointers || C++
upper-bound-two-pointers-c-by-ishanc05-gx6q
Binary Search\n*\n*Time Complexity : O(NLogN)\n\nSpace Complexity : O(1)\n\n#define ll long long int\n\nclass Solution {\npublic:\n long long incremovableSub
IshanC05
NORMAL
2023-12-30T08:36:54.307050+00:00
2023-12-30T08:36:54.307099+00:00
5
false
**Binary Search**\n****\n**Time Complexity :** O(NLogN)\n\n**Space Complexity :** O(1)\n```\n#define ll long long int\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n \n ll n = nums.size();\n ll leftIdx = 0, rightIdx = n - 1;\n \n while(leftIdx + 1 < n && nums[leftIdx] < nums[leftIdx + 1])\n ++leftIdx;\n \n while(rightIdx - 1 >= 0 && nums[rightIdx] > nums[rightIdx - 1])\n --rightIdx;\n \n if(leftIdx == n - 1) return (n * (n + 1)) / 2;\n \n ll res = (n - rightIdx + 1);\n \n for(ll i = 0; i <= leftIdx; i++){\n ll ubIdx = upper_bound(nums.begin() + rightIdx, nums.end(), nums[i]) - nums.begin();\n res += (n - ubIdx + 1);\n }\n \n return res;\n }\n};\n```\n\n****\n**Two Pointer**\n****\n**Time Complexity :** O(N)\n\n**Space Complexity :** O(1)\n\n```\n#define ll long long int\n\nclass Solution {\npublic:\n long long incremovableSubarrayCount(vector<int>& nums) {\n \n ll n = nums.size();\n ll leftIdx = 0, rightIdx = n - 1;\n \n while(leftIdx + 1 < n && nums[leftIdx] < nums[leftIdx + 1])\n ++leftIdx;\n \n while(rightIdx - 1 >= 0 && nums[rightIdx] > nums[rightIdx - 1])\n --rightIdx;\n \n if(leftIdx == n - 1) return (n * (n + 1)) / 2;\n \n ll res = (n - rightIdx + 1);\n ll r = rightIdx;\n \n for(ll l = 0; l <= leftIdx; l++){\n while(r < n && nums[l] >= nums[r])\n ++r;\n res += (n - r + 1);\n }\n \n return res;\n }\n};\n```\n\n****\n
0
0
['Two Pointers', 'C', 'Binary Tree']
0
count-the-number-of-incremovable-subarrays-ii
C++ Easy Solution using Sliding Window Technique
c-easy-solution-using-sliding-window-tec-b3hi
\n\n# Complexity\n- Time complexity: O(nlogn)\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)
gangstar_dame29
NORMAL
2023-12-29T20:32:55.544348+00:00
2023-12-29T20:32:55.544375+00:00
10
false
\n\n# Complexity\n- Time complexity: O(nlogn)\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 long long incremovableSubarrayCount(vector<int>& nums) {\n int ml=INT_MIN;\n int mr=INT_MAX;\n int n=nums.size();\n int j=n-1;\n while(j>=0 && nums[j]<mr)\n {\n mr=nums[j];\n j--;\n }\n mr=j+1;\n int i=0;\n while(i<n && nums[i]>ml)\n {\n ml=nums[i];\n i++;\n }\n ml=i-1;\n long long ans=0;\n int k=0;\n while(k<=ml)\n {\n int ind=upper_bound(nums.begin()+mr,nums.end(),nums[k])-nums.begin();\n ans+=(n-ind+1);\n k++;\n }\n if(ml<mr)\n {\n ans+=(n-mr+1); \n }\n return ans;\n }\n};\n```
0
0
['C++']
0