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
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Solution in O(n) in C++
solution-in-on-in-c-by-tk24-ifxr
IntuitionThe approach is similar to a sliding window, where you consider three consecutive nodes at a time: previous, current, and next. As you move through the
Kodertej
NORMAL
2025-02-16T16:05:27.390803+00:00
2025-02-16T16:05:27.390803+00:00
19
false
# Intuition The approach is similar to a sliding window, where you consider three consecutive nodes at a time: previous, current, and next. As you move through the list, you slide this window step by step, checking if the current node is a critical point by comparing it with its neighbors. # Approach The approach slides a window of 3 consecutive nodes (prev, curr, next) across the list, checking if the current node is a critical point. Critical points are stored, and the distances between them are computed to find the minimum and maximum distances. # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```cpp [] class Solution { public: vector<int> nodesBetweenCriticalPoints(ListNode* head) { vector<int> ans = {-1,-1}; if(head == NULL or head->next==NULL or head->next->next==NULL) return ans; ListNode* a =head; ListNode* b =head->next; ListNode* c =head->next->next; vector<int> criticalIndices; int i =1; while(c){ if ((a->val < b->val && b->val > c->val) || (a->val > b->val && b->val < c->val)) { criticalIndices.push_back(i); } a = a->next; b = b->next; c = c->next; i++; } if (criticalIndices.size() < 2) return ans; int lmax = criticalIndices.back() - criticalIndices.front(); int lmin = INT_MAX; for (int j = 1; j < criticalIndices.size(); j++) { lmin = min(lmin, criticalIndices[j] - criticalIndices[j - 1]); } ans[0] = lmin; ans[1] = lmax; return ans; } }; ```
1
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy C++ Solution | | Beats 100%
easy-c-solution-beats-100-by-krishmalviy-qtf9
Complexity Time complexity: O(N) Space complexity: O(N) Code
Krish_004
NORMAL
2025-01-25T23:26:37.542075+00:00
2025-01-25T23:26:37.542075+00:00
13
false
# Complexity - Time complexity: $$O(N)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(N)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: void criticalPoints(ListNode* &head, vector<int> &temp) { ListNode* curr = head; ListNode* prev = nullptr; int count = 1; while(curr) { ListNode* forw = curr->next; if (!prev || !forw) { prev = curr; curr = forw; count++; continue; } if ((curr->val > prev->val && curr->val > forw->val) || (curr->val < prev->val && curr->val < forw->val)) { temp.push_back(count); prev = curr; curr = forw; } else { prev = curr; curr = forw; } count++; } } vector<int> nodesBetweenCriticalPoints(ListNode* head) { vector<int> ans(2, -1); vector<int> temp; criticalPoints(head, temp); if (temp.size() < 2) { return ans; } int mini = INT_MAX; for (int i = temp.size() - 1; i >= 1; --i) { int element = temp[i] - temp[i - 1]; mini = min(mini, element); } int maxi = temp[temp.size() - 1] - temp[0]; ans[0] = mini; ans[1] = maxi; return ans; } }; ```
1
0
['Linked List', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
2 POINTER APPROACH, TC = O(N), SC = O(1)
2-pointer-approach-tc-on-sc-o1-by-dkvmah-8296
IntuitionApproachComplexity Time complexity: O(N) Space complexity: O(1) Code
DkVMAH7YOG
NORMAL
2025-01-10T13:05:31.978151+00:00
2025-01-10T13:05:31.978151+00:00
18
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N) - Space complexity: O(1) # Code ```cpp [] /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: vector<int> nodesBetweenCriticalPoints(ListNode* head) { // empty || single || double || triple node if (head == NULL || head->next == NULL || head->next->next == NULL || head->next->next->next == NULL) return {-1,-1}; // step 01 : traverse forward from 3 to n in [1,n] ListNode* backward = head; ListNode* curr = head->next; ListNode* forward = head->next->next; int minDist = INT_MAX; int maxDist = INT_MIN; int firstCP = -1; int lastCP = -1; int i = 1; while (forward) { // critical point found bool isCP = ((backward->val < curr->val && curr->val > forward->val) || (backward->val > curr->val && curr->val < forward->val)); // first critical point found if (isCP && firstCP == -1) { firstCP = i; lastCP = i; } // next critical point else if (isCP && firstCP != -1) { minDist = min(minDist, i-lastCP); // update lastCP lastCP = i; } ++i; backward = backward->next; curr = curr->next; forward = forward->next; } // if single CP found if (firstCP == lastCP) return {-1,-1}; // update maxDist maxDist = lastCP - firstCP; return {minDist, maxDist}; } }; ```
1
0
['Linked List', 'Two Pointers', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Two pointer Data store || 100% Beat
two-pointer-data-store-100-beat-by-ds_si-22vp
\n### Problem Statement\n\nGiven a singly linked list, a critical point is a node that satisfies one of the following conditions:\n1. It is a local maximum, mea
DS_Sijwali
NORMAL
2024-12-01T11:37:18.852777+00:00
2024-12-01T11:37:18.852798+00:00
6
false
\n### **Problem Statement**\n\nGiven a singly linked list, a **critical point** is a node that satisfies one of the following conditions:\n1. It is a **local maximum**, meaning its value is greater than the values of its adjacent nodes.\n2. It is a **local minimum**, meaning its value is less than the values of its adjacent nodes.\n\nThe task is to:\n1. Find all critical points in the list.\n2. Return an array containing:\n - The **minimum distance** between any two critical points.\n - The **maximum distance** between the first and last critical points.\n\nIf there are fewer than two critical points, return `[-1, -1]`.\n\n---\n\n### **Solution Approach**\n\n1. **Traverse the Linked List**:\n - Identify critical points by comparing the value of each node with its adjacent nodes.\n - Track the positions (indices) of the first and last critical points.\n - Calculate the minimum distance between consecutive critical points.\n\n2. **Handle Edge Cases**:\n - If there are fewer than two critical points, return `[-1, -1]`.\n\n3. **Return Results**:\n - If there are at least two critical points:\n - The **minimum distance** is stored in `smallDis`.\n - The **maximum distance** is the difference between the indices of the first and last critical points.\n\n---\n\n### **Code Walkthrough**\n\n#### **Edge Case Check**\n```java []\nif (head == null || head.next == null) return new int[]{-1, -1};\n```\n- If the list has fewer than two nodes, return `[-1, -1]` because there cannot be any critical points.\n\n#### **Initialization**\n```java []\nint first = -1;\nint last = -1;\nint smallDis = Integer.MAX_VALUE;\nListNode cur = head.next;\nListNode prev = head;\nint index = 1;\n```\n- `first`: Stores the index of the first critical point.\n- `last`: Stores the index of the last critical point.\n- `smallDis`: Tracks the minimum distance between consecutive critical points. Initialized to a large value.\n- `cur` and `prev`: Used to traverse the list and compare adjacent nodes.\n- `index`: Tracks the current node\'s position in the list.\n\n#### **Traverse the List**\n```java []\nwhile (cur.next != null) {\n ListNode next = cur.next;\n if (cur.val > prev.val && cur.val > next.val || cur.val < prev.val && cur.val < next.val) {\n```\n- A node is a critical point if it is either a local maximum or a local minimum.\n\n---\n\n#### **Handle Critical Points**\n```java []\n if (first == -1) {\n first = index;\n } else {\n smallDis = Math.min(smallDis, index - last);\n }\n last = index;\n```\n- If this is the first critical point, store its index in `first`.\n- Otherwise, update the minimum distance (`smallDis`) between consecutive critical points.\n- Update `last` to store the index of the most recent critical point.\n\n---\n\n#### **Move to the Next Node**\n```java []\n prev = cur;\n cur = cur.next;\n index++;\n}\n```\n- Move the `prev` and `cur` pointers forward and increment the index.\n\n---\n\n#### **Final Check and Result**\n```java []\nif (last == first) return new int[]{-1, -1};\nreturn new int[]{smallDis, last - first};\n```\n- If there is only one critical point (i.e., `first == last`), return `[-1, -1]`.\n- Otherwise, return:\n - `smallDis`: Minimum distance between consecutive critical points.\n - `last - first`: Maximum distance between the first and last critical points.\n\n---\n\n### **Example Walkthrough**\n\n#### Example 1\n**Input**: `head = [1, 3, 2, 2, 3, 2, 2, 2, 1]`\n\n**Execution**:\n1. Traverse the list and identify critical points:\n - Index 1: Value = 3, a local maximum.\n - Index 4: Value = 3, a local maximum.\n - Index 8: Value = 1, a local minimum.\n2. Minimum distance: `4 - 1 = 3`.\n3. Maximum distance: `8 - 1 = 7`.\n\n**Output**: `[3, 7]`\n\n---\n\n#### Example 2\n**Input**: `head = [1, 2, 3, 4, 5]`\n\n**Execution**:\n- There are no critical points (no local maxima or minima).\n- Return `[-1, -1]`.\n\n**Output**: `[-1, -1]`\n\n---\n\n### **Time and Space Complexity**\n\n#### **Time Complexity**\n- **Traverse the list**: \\(O(n)\\), where \\(n\\) is the number of nodes in the list.\n- The algorithm processes each node exactly once.\n\nOverall time complexity: **\\(O(n)\\)**.\n\n#### **Space Complexity**\n- The algorithm uses a constant amount of extra space for variables (`first`, `last`, `smallDis`, `prev`, `cur`).\n\nOverall space complexity: **\\(O(1)\\)**.\n\n---\n\n### **Key Takeaways**\n- The algorithm efficiently identifies critical points and computes the required distances in a single traversal of the list.\n- Edge cases (no or only one critical point) are handled gracefully.\n- The time and space complexities make the solution scalable for large linked lists.
1
0
['Linked List', 'Two Pointers', 'Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Best C++ Code (beats 98%)
best-c-code-beats-98-by-souravsinghal200-h43y
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
souravsinghal2004
NORMAL
2024-09-11T07:16:21.979445+00:00
2024-09-11T07:16:21.979467+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ios_base::sync_with_stdio(false);\n if(head==NULL || head->next==NULL ||head->next->next==NULL){\n return {-1,-1};\n }\n ListNode* temp2=head->next;\n ListNode* temp3=head->next->next;\n vector<int>v;\n int i=2;\n while(temp3){\n if((head->val<temp2->val)&&(temp2->val>temp3->val)){\n v.push_back(i);\n }\n else if((head->val>temp2->val)&&(temp2->val<temp3->val)){\n v.push_back(i);\n }\n i++;\n head=head->next;\n temp2=temp2->next;\n temp3=temp3->next;\n }\n if(v.size()<2){\n return {-1,-1};\n }\n int mini=INT_MAX;\n for(int i=1;i<v.size();i++){\n mini=min(mini,(v[i]-v[i-1]));\n }\n return {mini,(v[v.size()-1]-v[0])};\n }\n};\n```
1
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
2058. Simple Traversal Solution with explanation
2058-simple-traversal-solution-with-expl-mf2r
\n\'\'\'\n- At first, we need to find the Positions of Critical Points\n- Either we can store all those Critical Points Positions in some data structure and can
TrGanesh
NORMAL
2024-07-14T18:00:21.772159+00:00
2024-07-14T18:00:21.772198+00:00
3
false
```\n\'\'\'\n- At first, we need to find the Positions of Critical Points\n- Either we can store all those Critical Points Positions in some data structure and can do some processing on it\n- Otherwise we can think about which Critical Points are Necessary/Needed for calculating the Minimum & Maximum Distance\n- Maximum distance will be the distance between the first CP & the last CP\n- For minimum distance we need to consider the CP\'s which are near to each other\n- Finding the Maximum Distance is somewhat simpler\n- So what we will do means, We will traverse the Linked List and if we see a CP then we will compare that position with the position of the previously seen CP\n\'\'\'\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n # A pointer the denoting previous critical point position\n prevCPPosition = 0, 0\n # A pointer the denoting first critical point position\n firstCPPosition = 0\n\n # For finding the Minimum distance,, distance between above two is compared\n\n # As the Boundary Nodes does not belongs to critical points, we have to start from second node\n curNode = head.next \n # Pointer to store 0-indexing based Position of curNode\n curNodePosition = 1 \n\n prevNode = head # Prev Pointer for curNode\n\n minDist = float(\'inf\')\n while curNode.next:\n # For a node to become a CP,, its value should be either greater or smaller than the left and the right notes\n \n if ( (curNode.val > curNode.next.val and curNode.val > prevNode.val) or \n (curNode.val < curNode.next.val and curNode.val < prevNode.val)\n ):\n # If this condition gets satisfies,, \n # What if the Current CP is 1st CP,,\n if firstCPPosition == 0:\n firstCPPosition = curNodePosition\n prevCPPosition = curNodePosition\n else:\n minDist = min(minDist, curNodePosition - prevCPPosition)\n prevCPPosition = curNodePosition\n \n curNodePosition += 1\n prevNode = curNode\n curNode = curNode.next\n \n # After While Loop,, the prevCPPosition stays at the Last CP\n\n if minDist == float(\'inf\'):\n return [-1, -1]\n else:\n maxDist = prevCPPosition - firstCPPosition\n return [minDist, maxDist]\n```\n**Please UpVote if you like the Code & Explanation**
1
0
['Linked List', 'Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy java Solution || Beats 100%
easy-java-solution-beats-100-by-akshay16-64n8
\n\n# Code\n\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListN
akshay1610
NORMAL
2024-07-06T11:05:02.137360+00:00
2024-07-06T11:05:02.137389+00:00
6
false
\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int[] res = new int[2];\n if (head.next == null || head.next.next == null) {\n res[0] = -1;\n res[1] = -1;\n return res;\n }\n int critical = 0;\n int min = Integer.MAX_VALUE;\n int max = 0;\n int count = 1;\n ListNode curr = head.next;\n ListNode prev = head;\n int a = 0;\n int b = 0;\n while (curr!=null && curr.next != null) {\n ++count;\n ListNode next = curr.next;\n if ((curr.val > prev.val && curr.val>next.val) || (curr.val < prev.val && curr.val<next.val)) {\n critical+=1;\n if (critical>=2) {\n min = Math.min(min,count-a);\n max = max+count-a;\n }\n \n a = count;\n }\n prev = curr;\n curr = curr.next;\n }\n if (critical<2) {\n res[0] = -1;\n res[1] = -1;\n return res;\n }\n res[0] = min;\n res[1] = max;\n return res;\n }\n \n}\n```
1
0
['Linked List', 'Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
🔗 Finding Distances Between Critical Points in a Linked List 🔗 | BEATS 100% ✅✅
finding-distances-between-critical-point-bp4z
Intuition\n Describe your first thoughts on how to solve this problem. \nThe idea is to identify critical points in a linked list. A node is a critical point if
Mervis_Mascarenhas
NORMAL
2024-07-06T08:59:06.060966+00:00
2024-07-06T08:59:06.060997+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe idea is to identify critical points in a linked list. A node is a critical point if its value is either a local minimum or a local maximum. We need to traverse the linked list to identify these critical points and then calculate the distances between them.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Initialization:**\n- We start with three pointers p1, p2, and p3 to represent the previous, current, and next nodes, respectively.\n- If the list has fewer than three nodes, return {-1, -1} because it\'s not possible to have a critical point.\n\n**2. Traversal:**\n- Traverse the list using the pointers. For each node p2, check if it\'s a critical point by comparing its value to p1 and p3.\n- If p2 is a critical point, record its position (c).\n\n**3. Distance Calculation:**\n- Maintain variables to keep track of the first critical point (in), the previous critical point (prev), the maximum distance (mx), and the minimum distance (mn).\n- Update these variables as we find new critical points.\n\n**4. Result:**\n- If no critical points are found or only one critical point is found, return {-1, -1}.\n- Otherwise, return the minimum and maximum distances between critical points.\n\n# Complexity\n- **Time complexity:** \uD835\uDC42 ( \uD835\uDC5B ) where \uD835\uDC5B is the number of nodes in the linked list because we traverse the list once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space complexity:** O(1) because we use a fixed amount of extra space for pointers and variables.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* p1 = head;\n if(p1->next == nullptr) return {-1, -1};\n ListNode* p2 = p1->next;\n if(p2->next == nullptr) return {-1, -1};\n ListNode* p3 = p2->next;\n int in=0, c=2, mx, mn=1e9, prev=0; \n while(p2->next != nullptr){\n if((p2->val < p1->val && p2->val < p3->val)||(p2->val > p1->val && p2->val > p3->val)){\n if(!in){\n in = c;\n prev =c;\n }\n else{\n mx=c;\n if(mn > mx-prev)\n mn = mx-prev; \n prev= mx;\n }\n }\n p1=p1->next;\n p2=p2->next;\n p3=p3->next;\n c++;\n }\n if(in == prev) return {-1, -1};\n return {mn, mx-in};\n }\n};\n```
1
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
JAVA | | Time complexity: O(N) | | Space complexity: O(1)
java-time-complexity-on-space-complexity-n2zw
\n# Approach\n- Store the first maxima encountered\n- Store the last maxima encountered\n- Minimum distance will always be the distance between two subsequent m
demetra21104
NORMAL
2024-07-05T21:36:55.398266+00:00
2024-07-05T21:39:14.896756+00:00
2
false
\n# Approach\n- Store the first maxima encountered\n- Store the last maxima encountered\n- Minimum distance will always be the distance between two subsequent maximas, so compute distance as you progress along the linked list\n- Maximum distance will always be = Last maxima encountered - First maxima encountered\n\n\n# Complexity\n- Time complexity: O(N)\n- Space complexity: O(1)\n# Code\n- We have min_maxima to keep track of the first maxima encountered\n- We have max_maxima to keep track of the last maxima encountered\n- If both min_maxima and max_maxima point to the same point, it means only one critical point exists\n- curr_maxima is to keep track of the latest encountered maxima and is used to compute minimum distance when the next maxima is encountered, following the sequence until the end\n- If curr_maxima is still 0 after the iteration, it means there are no critical points\n\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n ListNode prev = head;\n ListNode curr = head.next;\n\n int i=1;\n int min_maxima = Integer.MAX_VALUE;\n int max_maxima = Integer.MIN_VALUE;\n\n int curr_maxima = 0;\n int minDiff_maximas = Integer.MAX_VALUE;\n\n while(curr.next != null) {\n ListNode next = curr.next;\n if(\n (curr.val>prev.val && curr.val>next.val) ||\n (curr.val<prev.val && curr.val<next.val) \n ) {\n min_maxima = Math.min(min_maxima, i+1);\n max_maxima = Math.max(max_maxima, i+1);\n\n if(curr_maxima != 0) {\n int difference = (i+1) - curr_maxima;\n minDiff_maximas = Math.min(minDiff_maximas, difference);\n }\n\n curr_maxima = i+1;\n }\n\n prev = curr;\n curr = next;\n i += 1;\n }\n\n if(curr_maxima==0 || min_maxima==max_maxima) return new int[]{-1, -1};\n\n return new int[]{minDiff_maximas, max_maxima-min_maxima};\n }\n}\n```
1
0
['Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Leetcode Daily #1
leetcode-daily-1-by-dajonas-i2tt
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
dajonas
NORMAL
2024-07-05T20:04:29.784969+00:00
2024-07-05T20:04:29.784997+00:00
14
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n if not head or not head.next:\n return [-1, -1]\n pos = 0\n prev = head\n cur = head.next\n nxt = head.next.next\n firstDisctinct = -1\n lastDisctinct = -1\n minDistance = float("inf")\n while nxt:\n if (cur.val > prev.val and cur.val > nxt.val) or (\n cur.val < prev.val and cur.val < nxt.val\n ):\n if firstDisctinct == -1:\n firstDisctinct = pos\n else:\n minDistance = min(minDistance, pos - lastDisctinct)\n lastDisctinct = pos\n prev = prev.next\n cur = cur.next\n nxt = nxt.next\n pos += 1\n if firstDisctinct == -1 or lastDisctinct == firstDisctinct:\n return [-1, -1]\n return [minDistance, lastDisctinct - firstDisctinct]\n\n```
1
0
['Python3']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
O(n) Solution | Single Pass | Basic Logic | O(1) Memory Complexity
on-solution-single-pass-basic-logic-o1-m-h1p9
Intuition\nThe problem is very straight forward, we need to know the positions of minimums and maximums and have to find mininum distance and maximum difference
sauram228
NORMAL
2024-07-05T19:35:46.314407+00:00
2024-07-05T19:35:46.314437+00:00
10
false
# Intuition\nThe problem is very straight forward, we need to know the positions of minimums and maximums and have to find mininum distance and maximum difference between all the pairs.\n\nNow, I will be using critical point to symbolize either minimum/maximnum\n\nMaximum distance is simple which is ```last critical point - first critical point```\n\nBut what about minimum distance, well, it is also simple, just ```\nfind the difference between every pair of adjacent elements and the minimum of them would be the minimum distance.``` \n\n# Approach\n\n1. Initialize a new List to contain the indexes of critical points\n2. Traverse the linked list and keeping pushing back the critial points index into the new list.\n3. Traverse the list to find the minimum and maximum distance.\n\n```\nWell, this would solve the problem but can we optimize it?\n\nSure we can.\n```\n\nWe don\'t need to waste memory to keep the list of indices, which will also result in not traversing the list later, saving some computation time.\n\nEssentially, we need to know 3 things\n\n1. The index of first critical point. (say, first)\n2. The index of previous critical point.(say, prev)\n3. The index of current critical point, if any. (say, current)\n\nThus, this is how our formula for maximum distance and minimum distance would look.\n\n```\nmaximum distance = max(max distance, current - first);\n```\n```\nminimum distance = min(min distance, current - prev);\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```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int minDistance=INT_MAX;\n int maxDistance=-1;\n int first=-1;\n int second=-1;\n int temp=-1;\n int prevVal=head->val;\n head=head->next;\n int count=1;\n while(head && head->next){\n if((prevVal>head->val && (head->next)->val > head->val)\n || (prevVal<head->val && (head->next)->val < head->val)\n ){\n if(first==-1){\n first=count;\n temp=count;\n }else{\n second=count;\n minDistance= min(minDistance, second-temp);\n maxDistance= max(maxDistance, second-first);\n temp=second;\n }\n }\n count++;\n prevVal=head->val;\n head=head->next;\n }\n if(maxDistance==-1) return {-1,-1};\n return {minDistance, maxDistance};\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
✅☑[C++/Java/Python/JavaScript] || Easy Implementation || EXPLAINED🔥
cjavapythonjavascript-easy-implementatio-n4bn
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n1. Map Structure: Uses a map<pair<char, int>, int> to store the count of ch
MarkSPhilip31
NORMAL
2023-12-31T04:25:05.151185+00:00
2023-12-31T04:25:05.151209+00:00
3,799
false
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n1. **Map Structure:** Uses a `map<pair<char, int>, int>` to store the count of character sequences along with their lengths.\n1. **Iterating through String:** Iterates through the string to count the length of each character sequence.\n1. **Storing Counts:** Stores the count of each character sequence along with its length in the map.\n1. **Finding Maximum Length:** Traverses the map and finds the maximum length of sequences that appear at least three times.\n1. **Return Value:** Returns the maximum length of the sequence that appears at least three times, else returns -1.\n\n\n# Complexity\n- Time complexity:\n $$O(n^2)$$\n \n\n- Space complexity:\n $$O(n^2)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maximumLength(string st) {\n // Map to store the count of character sequences along with their lengths\n map<pair<char, int>, int> mps;\n int count = 0;\n\n // Iterate through the string\n for (int i = 0; i < st.length(); i++) {\n count = 1;\n // Store the count of each character sequence along with its length\n mps[{st[i], count}]++;\n\n // Check for consecutive characters\n for (int j = i; j < st.length(); j++) {\n if (st[j] == st[j + 1]) {\n count++;\n // Store the count of each character sequence along with its length\n mps[{st[i], count}]++;\n } else {\n break;\n }\n }\n }\n\n int ans1 = 0;\n\n // Iterate through the stored character sequences and their lengths\n for (auto x : mps) {\n // If a sequence appears at least three times, update the maximum length\n if (x.second >= 3) {\n ans1 = max(x.first.second, ans1);\n }\n }\n\n // Return the maximum length of the sequence that appears at least three times\n return (ans1 == 0) ? -1 : ans1;\n }\n};\n\n\n\n\n```\n```Java []\n\n\nclass Solution {\n public int maximumLength(String st) {\n Map<Map.Entry<Character, Integer>, Integer> mps = new HashMap<>();\n int count;\n\n for (int i = 0; i < st.length(); i++) {\n count = 1;\n mps.put(Map.entry(st.charAt(i), count), mps.getOrDefault(Map.entry(st.charAt(i), count), 0) + 1);\n\n for (int j = i; j < st.length(); j++) {\n if (j + 1 < st.length() && st.charAt(j) == st.charAt(j + 1)) {\n count++;\n mps.put(Map.entry(st.charAt(i), count), mps.getOrDefault(Map.entry(st.charAt(i), count), 0) + 1);\n } else {\n break;\n }\n }\n }\n\n int ans1 = 0;\n for (Map.Entry<Map.Entry<Character, Integer>, Integer> x : mps.entrySet()) {\n if (x.getValue() >= 3) {\n ans1 = Math.max(x.getKey().getValue(), ans1);\n }\n }\n return (ans1 == 0) ? -1 : ans1;\n }\n}\n\n\n\n```\n```python3 []\n\nclass Solution:\n def maximumLength(self, st: str) -> int:\n from collections import defaultdict\n mps = defaultdict(int)\n count = 0\n \n for i in range(len(st)):\n count = 1\n mps[(st[i], count)] += 1\n\n for j in range(i, len(st)):\n if j + 1 < len(st) and st[j] == st[j + 1]:\n count += 1\n mps[(st[i], count)] += 1\n else:\n break\n \n ans1 = 0\n for key, value in mps.items():\n if value >= 3:\n ans1 = max(ans1, key[1])\n \n return ans1 if ans1 != 0 else -1\n\n\n```\n```javascript []\nclass Solution {\n maximumLength(st) {\n const mps = new Map();\n let count;\n\n for (let i = 0; i < st.length; i++) {\n count = 1;\n const key = [st[i], count];\n mps.set(JSON.stringify(key), (mps.get(JSON.stringify(key)) || 0) + 1);\n\n for (let j = i; j < st.length; j++) {\n if (j + 1 < st.length && st[j] === st[j + 1]) {\n count++;\n const innerKey = [st[i], count];\n mps.set(JSON.stringify(innerKey), (mps.get(JSON.stringify(innerKey)) || 0) + 1);\n } else {\n break;\n }\n }\n }\n\n let ans1 = 0;\n for (const [key, value] of mps.entries()) {\n if (value >= 3) {\n ans1 = Math.max(ans1, JSON.parse(key)[1]);\n }\n }\n return (ans1 === 0) ? -1 : ans1;\n }\n}\n\n\n\n```\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
30
2
['String', 'Ordered Map', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
8
find-longest-special-substring-that-occurs-thrice-i
Python 3 || 7 lines, groupby and dict || T/S: 85% / 54%
python-3-7-lines-groupby-and-dict-ts-85-q6vdy
Here\'s the plan: \n1. We parse the the string into a list of strings of one character. (For example: \'aabeee\' --> [\'aa\', \'b\', \'eee\'])\n1. We increment
Spaulding_
NORMAL
2023-12-31T21:44:45.320313+00:00
2024-12-10T00:36:29.756731+00:00
516
false
Here\'s the plan: \n1. We parse the the string into a list of strings of one character. (For example: `\'aabeee\' --> [\'aa\', \'b\', \'eee\']`)\n1. We increment a dict to track the beautiful strings; the trick here is to account for all substrings in a particular beautiful string, as there are also shorter beautiful strings in the same character.\n\n2. We filter the dict keys for all beautiful strings that occur three times and return the maximum length of all such beautiful strings. \n``` Python3 []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n\n d = defaultdict(int)\n subs = [\'\'.join(sub) for _, sub in groupby(s)] # <-- 1.\n \n for sub in subs: #\n d[sub]+= 1 # <-- 2.\n if len(sub) > 1: d[sub[1:]]+= 2 #\n if len(sub) > 2: d[sub[2:]]+= 3 #\n\n return max(map(len,filter(lambda x: d[x] > 2, # <-- 3.\n d)), default = -1)\n \n```\n```cpp []\nclass Solution {\npublic:\n int maximumLength(std::string s) {\n std::unordered_map<std::string, int> d;\n std::vector<std::string> subs;\n\n for (int i = 0; i < s.length(); ) { // <-- 1)\n char current = s[i];\n std::string sub;\n while (i < s.length() && s[i] == current) {\n sub += current;\n i++;\n }\n subs.push_back(sub);}\n\n for (const auto& sub : subs) { // <-- 2)\n d[sub]++;\n if (sub.length() > 1) d[sub.substr(1)] += 2;\n if (sub.length() > 2) d[sub.substr(2)] += 3; }\n\n int maxLength = -1; // <-- 3)\n for (const auto& entry : d) {\n if (entry.second > 2) {\n maxLength = std::max(maxLength, static_cast<int>(entry.first.length()));}\n }\n\n return maxLength;}\n};\n```\n```java []\nclass Solution {\n public int maximumLength(String s) {\n Map<String, Integer> d = new HashMap<>();\n StringBuilder sub = new StringBuilder();\n\n \n for (int i = 0; i < s.length(); ) { // <- 1)\n char current = s.charAt(i);\n sub.setLength(0);\n \n while (i < s.length() && s.charAt(i) == current) {\n sub.append(current);\n i++;}\n \n String group = sub.toString(); // <- 2)\n d.put(group, d.getOrDefault(group, 0) + 1);\n\n if (group.length() > 1) d.put(group.substring(1),\n d.getOrDefault(group.substring(1), 0) + 2);\n\n if (group.length() > 2) d.put(group.substring(2), \n d.getOrDefault(group.substring(2), 0) + 3);\n }\n\n int maxLength = -1; // <- 3)\n for (Map.Entry<String, Integer> entry : d.entrySet()) {\n if (entry.getValue() > 2) {\n maxLength = Math.max(maxLength, entry.getKey().length());}\n }\n\n return maxLength;}\n}; \n```\n[https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1133338922/](https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1133338922/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(s)`.
16
0
['C++', 'Java', 'Python3']
4
find-longest-special-substring-that-occurs-thrice-i
✅🔥Brute Force to Optimized ✅🔥 - Fully Explained
brute-force-to-optimized-fully-explained-1fmq
Problem \nYou are given a string s. Your task is to find the maximum length of a special substring in s that is occuring atleast 3 times. A special substring is
harsh_reality_
NORMAL
2023-12-31T04:19:43.490688+00:00
2023-12-31T04:19:43.490719+00:00
1,844
false
# Problem \nYou are given a string ```s```. Your task is to find the maximum length of a special substring in ```s``` that is occuring atleast 3 times. A special substring is defined as a substring in which all characters are the same.\n\nWrite a function maximumLength to solve the problem.\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first approach was to make all substrings and then count manually. But that will obviously give TLE. So, I thought about optimizing the solution\n\n# Approach\nThe optimized approach involves iterating through the string s and counting consecutive characters. We can use a hash table to store these counts for each character. After counting, we sort the counts in descending order for each character.\n\nWe then iterate through the hash table entries and consider the top counts for each character. We calculate the maximum length of a special substring based on these counts.\n\n# PLEASE UPVOTE and ask for doubts\n\n# Complexity\n- Time complexity: O(n * n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code - Brute Force \n```\nclass Solution:\n def maximumLength(self, s: str) -> int:\n def is_special(substring):\n return len(set(substring)) == 1\n\n max_length = -1\n hash = defaultdict(int)\n for i in range(len(s)):\n for j in range(i + 1, len(s)+1):\n substring = s[i:j]\n if is_special(substring):\n hash[substring] += 1\n for x, y in hash.items():\n if y >= 3:\n max_length = max(max_length, len(x))\n return max_length\n```\n\n# Complexity\n- Time complexity: O(n * logn) -> (nlogn for sorting in the second loop)\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# How we determine the max length substring?\nFor each charater as we are storing consecutive lengths in hash dictionary, the maximum length substring can be found in 3 ways.\n\n- Either take all 3 substrings from the same consective substring, so the length would be ```lis[0] - 2```. For example, ```"aaaa"```, we can get three ```"aa"```\n- Take two substrings from the longest and one from second longest, so the length would be ```min(lis[0]-1, lis[1])```. For example, from `"aaa"`, we can get two `"aa"`\n- Take the three substrings from separate consecutives, so the length would be ```min(lis[0], lis[1], lis[2])```. This is obvious.\n\n# Code - Optimized\n```C++ []\nclass Solution {\npublic:\n int maximumLength(string s) {\n unordered_map<char, vector<int>> hash;\n\n int n = s.length();\n int i = 0;\n while (i < n) {\n int temp = 1;\n char ch = s[i];\n while (i < n - 1 && s[i] == s[i + 1]) {\n temp += 1;\n i += 1;\n }\n hash[ch].push_back(temp);\n i += 1;\n }\n\n int maxi = -1;\n for (auto& entry : hash) {\n vector<int>& lis = entry.second;\n sort(lis.rbegin(), lis.rend());\n \n if (lis[0] >= 3) {\n maxi = max(maxi, lis[0] - 2);\n }\n \n if (lis.size() >= 2) {\n if (lis[0] >= 2) {\n maxi = max(maxi, min(lis[0] - 1, lis[1]));\n }\n if (lis.size() >= 3) {\n maxi = max(maxi, min({lis[0], lis[1], lis[2]}));\n }\n }\n }\n\n return maxi;\n }\n};\n```\n```python []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n hash = defaultdict(list)\n \n n = len(s)\n i = 0\n while i < n:\n temp = 1\n ch = s[i]\n while i < n-1 and s[i] == s[i+1]:\n temp += 1\n i += 1\n hash[ch].append(temp)\n i += 1\n \n maxi = -1\n for ch, lis in hash.items():\n lis.sort(reverse=True)\n if lis[0] >= 3:\n maxi = max(maxi, lis[0]-2)\n if len(lis) >= 2:\n if lis[0] >= 2:\n maxi = max(maxi, min(lis[0]-1, lis[1]))\n if len(lis) >= 3:\n maxi = max(maxi, min(lis[:3]))\n \n return maxi\n```\n```Java []\nclass Solution {\n public int maximumLength(String s) {\n Map<Character, List<Integer>> hash = new HashMap<>();\n\n int n = s.length();\n int i = 0;\n while (i < n) {\n int temp = 1;\n char ch = s.charAt(i);\n while (i < n - 1 && s.charAt(i) == s.charAt(i + 1)) {\n temp += 1;\n i += 1;\n }\n hash.computeIfAbsent(ch, k -> new ArrayList<>()).add(temp);\n i += 1;\n }\n\n int maxi = -1;\n for (List<Integer> lis : hash.values()) {\n lis.sort(Collections.reverseOrder());\n \n if (lis.get(0) >= 3) {\n maxi = Math.max(maxi, lis.get(0) - 2);\n }\n \n if (lis.size() >= 2) {\n if (lis.get(0) >= 2) {\n maxi = Math.max(maxi, Math.min(lis.get(0) - 1, lis.get(1)));\n }\n if (lis.size() >= 3) {\n maxi = Math.max(maxi, Math.min(lis.get(0), Math.min(lis.get(1), lis.get(2))));\n }\n }\n }\n\n return maxi;\n }\n}\n```
15
0
['Hash Table', 'Sliding Window', 'Sorting', 'Python', 'C++', 'Java', 'Python3']
3
find-longest-special-substring-that-occurs-thrice-i
✅ Java Solution | Easy to understand
java-solution-easy-to-understand-by-hars-7e9t
solution\n Save all the substrings, and it\'s counted in HashMap\n Iterate through all the strings in the map\n Check string contains the same characters and oc
Harsh__005
NORMAL
2023-12-31T04:10:29.576434+00:00
2023-12-31T04:10:29.576458+00:00
975
false
## solution\n* Save all the substrings, and it\'s counted in HashMap\n* Iterate through all the strings in the map\n* Check string contains the same characters and occurrences more than 3 times\n* Take the longest string as an answer\n\n## code\n```\npublic int maximumLength(String s) {\n\tint res = -1;\n\n\tchar[] arr = s.toCharArray();\n\tMap<String, Integer> map = new HashMap<>();\n\n\tfor(int i=0; i<arr.length; i++){\n\t\tfor(int j=i; j<arr.length; j++){\n\t\t\tString curr = s.substring(i, j+1);\n\t\t\tmap.put(curr, map.getOrDefault(curr, 0)+1);\n\t\t}\n\t}\n\n\tfor(String str : map.keySet()){\n\t\tif(map.get(str) >= 3){\n\t\t\tboolean flag = true;\n\n\t\t\tchar ch = str.charAt(0);\n\t\t\tfor(int i=1; i<str.length()&&flag; i++){\n\t\t\t\tif(str.charAt(i) != ch) flag = false;\n\t\t\t}\n\t\t\tif(flag) res = Math.max(res, str.length());\n\t\t}\n\t}\n\n\treturn res;\n}\n```
15
0
['Java']
6
find-longest-special-substring-that-occurs-thrice-i
[C++ & Java] Explained - Using only map O(N) & using binary search O(N.logN) solution
using-map-very-simple-and-easy-to-unders-imuw
Approach\n- track the continuous occurance count of each item in s\n- Keep pushing the occurance count in the map against that character\n- Now we have diff chu
kreakEmp
NORMAL
2023-12-31T04:04:58.482260+00:00
2024-12-10T12:02:18.393562+00:00
4,161
false
# Approach 1 ( using only map & storing the continuous chars group count) :\n- track the continuous occurance count of each item in s\n- Keep pushing the occurance count in the map against that character\n- Now we have diff chunk of occurance count in the map for each character\n- So keep checking each character\'s max possible answer\n - For each char we have vector where we have there cont. occurance count\n - Find the largest 3 cont. occurances count from the vector.\n - Now check for the max possible answer : which is either largest - 2 or second largest \n\n\n#### Cases to be considered :\nThe largest three number can have possible values: \n - All three item equal {3,3,3} here answer is 3\n - Max two items are equal but third is not {3,3,2} here ans is 2\n - Largest is large than a diff of 2 than second -> {5, 2, 1} here ans is 5 - 2 = 3\n - Minimum possible values for which we have a valid answer {1, 1, 1} or {2, 1, 0} or {3, 0, 0}. All three cases answer will be 1.\n \n\n### Complexity \n- Time complexity : O(N)\n- Space complexity : O(N)\n\n# Code\n```cpp []\nint maximumLength(string s) {\n int count = 0, last = s[0], ans = 0;\n unordered_map<char, vector<int>> ump; // this store the cont. occurance counts against each character\n for(auto c: s){ // compute all the cont. char count and add it to the corresponding char in the map\n if(c == last) count++;\n else{\n ump[last].push_back(count);\n count = 1; last = c;\n }\n }\n ump[last].push_back(count);\n \n for(auto [k, v]: ump){ // For each char evaluate the max 3 occuarance count and check for possible max triplate count \n int l1 = 0, l2 = 0, l3 = 0;\n for(auto e: v){ \n if(l1 < e) { l3 = l2; l2 = l1; l1 = e; }\n else if(l2 < e) { l3 = l2; l2 = e; }\n else if(l3 < e) { l3 = e; }\n }\n if(l1 == l2 && l1 > l3) l2--; // This is to handle the case when the largest 3 occurances are 2, 2, 1\n if(l1 + l2 + l3 >= 3) ans = max({ans, l1 - 2, l2 }); //max triplet can be either largest - 2 or the second largest\n }\n return ans != 0?ans: -1; // if ans is zero return -1 otherwise return ans.\n}\n```\n\n```Java []\npublic int maximumLength(String s) {\n int count = 0, last = s.charAt(0), ans = 0;\n Map<Character, List<Integer>> ump = new HashMap<>(); // this store the cont. occurance counts against each character\n for(char c: s.toCharArray()){ // compute all the cont. char count and add it to the corresponding char in the map\n if(c == last) count++;\n else{\n if(!ump.containsKey((char)last)) ump.put((char)last, new ArrayList<>());\n ump.get((char)last).add(count);\n count = 1; last = c;\n }\n }\n if (!ump.containsKey((char) last)) ump.put((char) last, new ArrayList<>());\n ump.get((char) last).add(count);\n \n for(Map.Entry<Character,List<Integer>> entry: ump.entrySet()){ // For each char evaluate the max 3 occuarance count and check for possible max triplate count \n int l1 = 0, l2 = 0, l3 = 0;\n for(int e: entry.getValue()){\n if(l1 < e) { l3 = l2; l2 = l1; l1 = e; }\n else if(l2 < e) { l3 = l2; l2 = e; }\n else if(l3 < e) { l3 = e; }\n }\n if(l1 == l2 && l1 > l3) l2--; // This is to handle the case when the largest 3 occurances are 2, 2, 1\n if(l1 + l2 + l3 >= 3) ans = Math.max(ans, Math.max(l1 - 2, l2) ); //max triplet can be either largest - 2 or the second largest\n }\n return ans != 0?ans: -1; // if ans is zero return -1 otherwise return ans.\n}\n```\n\n\n# Approach 2 (Using binary search):\n\n- Here we need to think like we need to search a window size, which have at least 3 window where all chars are same\n- This is a typical way to implement binary search in problems where we keep searching for an optimal window size that is sufficient to pass the condition.\n- For validation if the we have widow size is valid or not, we simply keep track of unique chars and a map for storing it in char freq and then another map to keep track of how many window we found where all chars are same ( i.e unique chars count = 1) \n\n# Complexity :\n- Time : O(N.logN)\n- Space : O(1)\nNote : space complexity is O(1) as the maps used here have a max size of 26, irrespective of size of the input and it will remain constant.\n\n# Code\n```cpp []\nbool isValid(string s, int mid, int count){\n unordered_map<char, int> freq;\n unordered_map<char, int> charMap;\n for(int i = 0, j = 0, unique = 0; j < s.size(); ++j){\n freq[s[j]]++;\n if(freq[s[j]] == 1) unique++;\n if(j >= mid) {\n freq[s[i]]--;\n if(freq[s[i]] == 0) unique--;\n ++i;\n }\n if(j >= mid-1 && unique == 1) {\n charMap[s[j]]++;\n if(charMap[s[j]] == 3) return true;\n }\n }\n return false;\n}\n\nint maximumLength(string s) {\n int ans = -1, start = 1, end = s.size();\n while(start <= end){\n int mid = start + ( end - start)/2;\n if(isValid(s, mid, 3)){ ans = mid; start = mid + 1; }\n else{ end = mid -1; }\n }\n return ans;\n}\n```\n```Java []\nboolean isValid(String s, int mid, int count){\n Map<Character, Integer> freq = new HashMap<>();\n Map<Character, Integer> charMap = new HashMap<>();\n for(int i = 0, j = 0, unique = 0; j < s.length(); ++j){\n freq.put(s.charAt(j), freq.getOrDefault(s.charAt(j), 0)+1);\n if(freq.get(s.charAt(j)) == 1) unique++;\n if(j >= mid) {\n freq.put(s.charAt(i), freq.getOrDefault(s.charAt(i), 0)-1);\n if(freq.get(s.charAt(i)) == 0) unique--;\n ++i;\n }\n if(j >= mid-1 && unique == 1) {\n charMap.put(s.charAt(j), charMap.getOrDefault(s.charAt(j), 0) + 1);\n if(charMap.get(s.charAt(j)) == 3) return true;\n }\n }\n return false;\n}\n\nint maximumLength(String s) {\n int ans = -1, start = 1, end = s.length();\n while(start <= end){\n int mid = start + ( end - start)/2;\n if(isValid(s, mid, 3)){ ans = mid; start = mid + 1; }\n else{ end = mid -1; }\n }\n return ans;\n}\n```\n\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---\n\n
15
0
['C++', 'Java']
6
find-longest-special-substring-that-occurs-thrice-i
✅ One Line Solution
one-line-solution-by-mikposp-a57p
null
MikPosp
NORMAL
2024-12-10T11:12:41.764786+00:00
2024-12-10T21:29:50.658121+00:00
648
false
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - Five Lines\nTime complexity: $$O(26n)$$. Space complexity: $$O(n)$$.\n```python3\nclass Solution:\n def maximumLength(self, s: str) -> int:\n res = -1\n for c in {*s}:\n l = [*nlargest(3,map(len,findall(c+\'+\',s))),0,0]\n res = max(res, l[0]-2, l[1]-(l[0]==l[1]), l[2])\n\n return res or -1\n```\n\n# Code #1.2 - One Line\n```python3\nclass Solution:\n def maximumLength(self, s: str) -> int:\n return max(max((l:=[*nlargest(3,map(len,findall(c+\'+\',s))),0,0])[0]-2,l[1]-(l[0]==l[1]),l[2]) for c in {*s}) or -1\n```\n\n(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be \'true\' oneliners - please, remind about drawbacks only if you know how to make it better)
12
0
['String', 'Python', 'Python3']
0
find-longest-special-substring-that-occurs-thrice-i
Freq count+nth_element vs size 3 arrays||Beats 100%
freq-countnth_element3ms-beats-9662-by-a-cpy3
null
anwendeng
NORMAL
2024-12-10T02:03:31.657556+00:00
2024-12-10T06:53:09.416743+00:00
269
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse freq count & nth_element to solve.\n\nSame solution can also pass [2982. Find Longest Special Substring That Occurs Thrice II](https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-ii/solutions/4483637/c-find-special-substring-3x-using-array-nth-element-114ms-beats-100/)\n\n2nd approach it uses 3 lengths for each letter inspired by [Sergei\'s solution](https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/solutions/4483269/keeping-top-3-lengths-in-a-static-array-o-n-no-vectors-c-0-ms-java-2-ms-beating-100/)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Declare `n, s, alphabet` as member variables where `alphabet` is 2D array.\n2. Define function `table()` to construct `alphabet` by using an argument 2-pointer. The 1D array `alphabet[x]` stores the lengths of segments containing of only char \'a\'+x.\n3. Define function `int maxLen3x(vector<int>& v)` where `nth_element` \nis in use & can perform in a linear time.\n4. In `int maximumLength(string& s)` the previous defined functions are in use.\n5. Call `table()`\n6. Use a loop to transverse `lens=alphabet[x]` for x=0...25. When `lens` is not empty update `ans=max(ans, maxLen3x(lens))`\n7. return `ans`\n8. 2nd approach it uses 3 lengths for each letter inspired by [Sergei\'s solution](https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/solutions/4483269/keeping-top-3-lengths-in-a-static-array-o-n-no-vectors-c-0-ms-java-2-ms-beating-100/)\n9. The main idea in 2nd C++ code is **to keep the most 3 lengths for each letter**, it can not only save the space, but also increase the speed. Different from Sergei\'s implementation, `std::exchange` can be very efficient for this task. It needs a function `push`(instead of `vector::push_back`) as follows\n```\nint alphabet[26][3];// static C-array is good \ninline void push(int x, int lens[3]){\n if (x>=lens[0]){\n lens[2]=exchange(lens[1], lens[0]);// exchange is good\n lens[0]=x;\n }\n else if (x>=lens[1]) lens[2]=exchange(lens[1], x);\n else if (x>=lens[2]) lens[2]=x;\n}\n```\n10. Suppose that the size 3 array v satisfying `v[0]>=v[1]>=v[2]`; if `v[0]` is big enough, just choose only from this segment, i.e. the substring with Len=`v[0]-2` can be rightly shifted by 0,1,2; when chosing from the longest 2 segments, it will be `min(v[0]-1, v[1])`; when choosing 3 longest segments, maxLen=`v[2]`. \n11. The function ` maxLen3x(int* v)` is simpfied into\n```\nint maxLen3x(int* v){ // v is ordered by \'>\'\n return max({v[2], min(v[0]-1, v[1]), v[0]-2});\n}\n```\n# Note on std::exchange\n`x=exchange(y, z)` has the effect\n```\nx=y;\ny=z;\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code||Adding inline in C++ 0ms Beats 100%\n```cpp []\nclass Solution {\npublic:\n int n;\n string s;\n vector<vector<int>> alphabet;\n inline void table(){\n char prev=s[0]; \n int f=1;\n for(int i=1; i<n; i++){\n if (s[i]==prev)\n f++;\n else{\n alphabet[prev-\'a\'].push_back(f);\n f=1;\n prev=s[i]; \n } \n }\n alphabet[s.back()-\'a\'].push_back(f);\n }\n\n void print(){\n int i=0;\n for (auto& vect: alphabet){\n i++;\n if (vect.empty()) continue;\n cout<<char(\'a\'+i-1)<<":";\n for(auto& l:vect)\n cout<<l<<", ";\n cout<<endl;\n }\n }\n inline int maxLen3x(vector<int>& v){\n int sz=v.size();\n switch(sz){\n case 1:\n return v[0]-2;\n case 2:\n // sort(v.begin(), v.end(), greater{});\n \n if (v[0]<v[1]) swap(v[0], v[1]);\n // cout<<"sz=2,"<<v[0]<<", "<<v[1]<<endl;\n return max(v[0]-2, min(v[0]-1, v[1]));\n default:\n nth_element(v.begin(), v.begin()+2, v.end(),greater{});\n if (v[0]<v[1]) swap(v[0], v[1]);\n // cout<<"sz="<<sz<<","<<v[0]<<","<<v[1]<<","<<v[2]<<endl;\n return max({v[2], min(v[0]-1, v[1]), v[0]-2});\n }\n }\n int maximumLength(string& s) {\n this->s=s;\n // cout<<s<<":";\n n=s.size();\n // cout<<n<<endl;\n alphabet.assign(26, vector<int>());\n table();\n // print();\n int ans=-1;\n for (auto& lens: alphabet){\n if (lens.empty()) continue;\n ans=max(ans, maxLen3x(lens));\n }\n return ans<=0?-1:ans;\n }\n};\n\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# 2nd approach inspired by @Sergei||C++ 0ms beats 100%\n```\nclass Solution {\npublic:\n int n;\n string s;\n int alphabet[26][3];\n inline void push(int x, int lens[3]){\n if (x>=lens[0]){\n lens[2]=exchange(lens[1], lens[0]);\n lens[0]=x;\n }\n else if (x>=lens[1]) lens[2]=exchange(lens[1], x);\n else if (x>=lens[2]) lens[2]=x;\n }\n inline void table(){\n char prev=s[0]; \n int f=1;\n for(int i=1; i<n; i++){\n if (s[i]==prev)\n f++;\n else{\n push(f, alphabet[prev-\'a\']);\n f=1;\n prev=s[i]; \n } \n }\n push(f, alphabet[s.back()-\'a\']);\n }\n inline int maxLen3x(int* v){\n return max({v[2], min(v[0]-1, v[1]), v[0]-2});\n }\n\n int maximumLength(string& s) {\n this->s=s;\n n=s.size();\n memset(alphabet, -1, sizeof(alphabet));\n table();\n int ans=-1;\n for (int* lens: alphabet){\n if (lens[0]==-1) continue;\n ans=max(ans, maxLen3x(lens));\n }\n return ans<=0?-1:ans;\n }\n};\n\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```
5
0
['Two Pointers', 'String', 'Counting', 'C++']
5
find-longest-special-substring-that-occurs-thrice-i
Simple Binary Search 100% Beats
simple-binary-search-100-beats-by-sumeet-j06x
null
Sumeet_Sharma-1
NORMAL
2024-12-10T01:11:52.528424+00:00
2024-12-10T01:18:37.828925+00:00
1,634
false
# \uD83D\uDE80 Intuition \nWe are tasked with finding the **maximum length** \\( x \\) of a **special substring** that occurs at least **three times** in the given string `s`. \nA **special substring** contains only one unique character (e.g., `"aaa"`, `"bbbb"`). \nThe solution uses **binary search** combined with **sliding window validation** for efficiency.\n\n---\n\n# \uD83E\uDDE0 Approach \n\n### \uD83D\uDD0D 1. Binary Search \n- The goal is to identify the **largest \\( x \\)** such that a special substring of length \\( x \\) exists at least three times. \n- **Why binary search?** \n Binary search is effective because the problem exhibits **monotonic behavior**:\n - If \\( x \\) is valid (i.e., there exists a special substring of length \\( x \\)), then all smaller lengths \\( < x \\) are also valid.\n - Conversely, if \\( x \\) is invalid, then all larger lengths \\( > x \\) are also invalid. \n- We search in the range \\( [1, n] \\), where \\( n \\) is the length of the string:\n - Start with \\( l = 1 \\) (minimum substring length). \n - End with \\( r = n \\) (maximum substring length). \n\n---\n\n### \uD83D\uDD27 2. Validation (Helper Function) \nTo check if a given \\( x \\) is valid:\n1. Use a **sliding window** of size \\( x \\) to iterate over all substrings.\n2. For each window:\n - Ensure that all characters in the substring are identical.\n - Count the number of occurrences of this substring in the string.\n3. If any substring appears **at least three times**, \\( x \\) is valid.\n\nThe sliding window approach ensures efficient computation in \\( O(n) \\) for each validation.\n\n---\n\n### \uD83D\uDD04 3. Iterative Binary Search \n### Perform binary search to find the largest valid \\( x \\):\n\n1. Compute the midpoint: \n [mid = l + r/2]\n\n2. Use the helper function to validate \\( \\text{mid} \\): \n - If mid is valid, move the lower bound up l = mid . \n - If mid is invalid, move the upper bound down r =mid.\n\n3. Repeat until \\( l + 1 < r \\).\n\n- After the search:\n - If \\( l \\) is valid, return \\( l \\) as the result.\n - Otherwise, return `-1`.\n\n---\n\n### \uD83D\uDED1 Edge Cases \n- If the string contains no repeating characters, return `-1`.\n- For single-character strings, \\( x \\) can equal the entire string length.\n\n---\n\n# \uD83D\uDCCA Complexity \n\n### \u23F1 Time Complexity \n1. **Binary Search**: \\( O(log n) \\) iterations for \\( n \\) length of the string. \n2. **Sliding Window Validation**: Each check runs in \\( O(n) \\). \n3. **Total**: \\( O(nlog n) \\).\n\n### \uD83D\uDCBE Space Complexity \n- A frequency array or sliding window uses \\( O(1) \\) space.\n\n---\n![Screenshot 2024-12-10 063811.png](https://assets.leetcode.com/users/images/41701152-2633-43b3-b543-f3d5346e3395_1733792910.395723.png)\n\n\n# \uD83C\uDF1F Insights \n\n1. **Binary Search + Monotonicity**: \n Binary search works effectively when the validity condition is monotonic. \n \n2. **Sliding Window Optimization**: \n Instead of evaluating all substrings naively, the sliding window updates counts efficiently for each new substring.\n\n3. **Edge Cases**: \n - Handle edge cases where no valid substring exists, or the string length is too small.\n\n---\n\n# \uD83D\uDD17 Example Walkthrough \n\n### Example 1: \n**Input**: `s = "aabccc"` \n- \\( x = 1 \\): Valid (all single-character substrings). \n- \\( x = 3 \\): Valid (substring `"ccc"` occurs 3 times). \n- \\( x = 4 \\): Invalid (no substring of length 4 occurs 3 times). \n- **Output**: \\( 3 \\).\n\n### Example 2: \n**Input**: `s = "abcdef"` \n- \\( x = 1 \\): Valid (all single-character substrings). \n- \\( x = 2 \\): Invalid (no repeating substrings). \n- **Output**: \\( -1 \\).\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n int n = s.size();\n int l = 1, r = n;\n\n if (!helper(s, n, l)) return -1;\n\n while (l + 1 < r) {\n int mid = (l + r) / 2;\n if (helper(s, n, mid)) l = mid;\n else r = mid;\n }\n\n return l;\n }\n\nprivate:\n bool helper(const string& s, int n, int x) {\n vector<int> cnt(26, 0);\n int p = 0;\n\n for (int i = 0; i < n; i++) {\n while (s[p] != s[i]) p++;\n if (i - p + 1 >= x) cnt[s[i] - \'a\']++;\n if (cnt[s[i] - \'a\'] > 2) return true;\n }\n\n return false;\n }\n};\n```\n```Java []\npublic class Solution {\n public int maximumLength(String s) {\n int n = s.length();\n int l = 1, r = n;\n\n if (!helper(s, n, l)) return -1;\n\n while (l + 1 < r) {\n int mid = (l + r) / 2;\n if (helper(s, n, mid)) l = mid;\n else r = mid;\n }\n\n return l;\n }\n\n private boolean helper(String s, int n, int x) {\n int[] cnt = new int[26];\n int p = 0;\n\n for (int i = 0; i < n; i++) {\n while (s.charAt(p) != s.charAt(i)) p++;\n if (i - p + 1 >= x) cnt[s.charAt(i) - \'a\']++;\n if (cnt[s.charAt(i) - \'a\'] > 2) return true;\n }\n\n return false;\n }\n}\n```\n```Python3 []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n n = len(s)\n l, r = 1, n\n\n if not self.helper(s, n, l):\n return -1\n\n while l + 1 < r:\n mid = (l + r) // 2\n if self.helper(s, n, mid):\n l = mid\n else:\n r = mid\n\n return l\n\n def helper(self, s: str, n: int, x: int) -> bool:\n cnt = [0] * 26\n p = 0\n\n for i in range(n):\n while s[p] != s[i]:\n p += 1\n if i - p + 1 >= x:\n cnt[ord(s[i]) - ord(\'a\')] += 1\n if cnt[ord(s[i]) - ord(\'a\')] > 2:\n return True\n\n return False\n```\n```Javascript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar maximumLength = function(s) {\n let n = s.length;\n let l = 1, r = n;\n\n if (!helper(s, n, l)) return -1;\n\n while (l + 1 < r) {\n let mid = Math.floor((l + r) / 2);\n if (helper(s, n, mid)) l = mid;\n else r = mid;\n }\n\n return l;\n};\n\n/**\n * @param {string} s\n * @param {number} n\n * @param {number} x\n * @return {boolean}\n */\nfunction helper(s, n, x) {\n let cnt = new Array(26).fill(0);\n let p = 0;\n\n for (let i = 0; i < n; i++) {\n while (s[p] !== s[i]) p++;\n if (i - p + 1 >= x) cnt[s[i].charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n if (cnt[s[i].charCodeAt(0) - \'a\'.charCodeAt(0)] > 2) return true;\n }\n\n return false;\n}\n```\n```Ruby []\nclass Solution\n def maximum_length(s)\n n = s.length\n l, r = 1, n\n\n return -1 unless helper(s, n, l)\n\n while l + 1 < r\n mid = (l + r) / 2\n if helper(s, n, mid)\n l = mid\n else\n r = mid\n end\n end\n\n return l\n end\n\n def helper(s, n, x)\n cnt = Array.new(26, 0)\n p = 0\n\n s.each_char.with_index do |char, i|\n while s[p] != char\n p += 1\n end\n if i - p + 1 >= x\n cnt[char.ord - \'a\'.ord] += 1\n end\n return true if cnt[char.ord - \'a\'.ord] > 2\n end\n\n false\n end\nend\n```\n```C []\n#include <stdio.h>\n#include <string.h>\n\nint helper(const char* s, int n, int x) {\n int cnt[26] = {0};\n int p = 0;\n\n for (int i = 0; i < n; i++) {\n while (s[p] != s[i]) p++;\n if (i - p + 1 >= x) cnt[s[i] - \'a\']++;\n if (cnt[s[i] - \'a\'] > 2) return 1; // Return true if more than 2 occurrences of a character\n }\n\n return 0; // Return false if no character appears more than twice\n}\n\nint maximumLength(char* s) {\n int n = strlen(s);\n int l = 1, r = n;\n\n if (!helper(s, n, l)) return -1;\n\n while (l + 1 < r) {\n int mid = (l + r) / 2;\n if (helper(s, n, mid)) l = mid;\n else r = mid;\n }\n\n return l;\n}\n\nint main() {\n char s[] = "aabccc";\n printf("%d\\n", maximumLength(s)); // Output: 3\n return 0;\n}\n```\n```C# []\npublic class Solution {\n public int MaximumLength(string s) {\n int n = s.Length;\n int l = 1, r = n;\n\n // Call helper function for the initial condition\n if (!Helper(s, n, l)) return -1;\n\n while (l + 1 < r) {\n int mid = (l + r) / 2;\n if (Helper(s, n, mid)) l = mid;\n else r = mid;\n }\n\n return l;\n }\n\n private bool Helper(string s, int n, int x) {\n int[] cnt = new int[26]; // Array to count character frequencies\n int p = 0;\n\n for (int i = 0; i < n; i++) {\n while (s[p] != s[i]) p++; // Move p until we find the matching character\n if (i - p + 1 >= x) cnt[s[i] - \'a\']++; // Increment the count for the character\n if (cnt[s[i] - \'a\'] > 2) return true; // If any character appears more than twice, return true\n }\n\n return false; // Return false if no character appears more than twice\n }\n}\n```
5
0
['Binary Search', 'C', 'C++', 'Java', 'Python3', 'Ruby', 'JavaScript', 'C#']
20
find-longest-special-substring-that-occurs-thrice-i
One pass | Beat 100%
one-pass-beat-100-by-quanhuy-7i5x
Complexity\n- Time complexity: O(N)\n\n# Code\n\nclass Solution:\n def maximumLength(self, s: str) -> int:\n last = s[0]\n cnt = 0\n d =
quanhuy
NORMAL
2023-12-31T15:44:28.808491+00:00
2024-12-11T14:57:35.061637+00:00
362
false
# Complexity\n- Time complexity: O(N)\n\n# Code\n```\nclass Solution:\n def maximumLength(self, s: str) -> int:\n last = s[0]\n cnt = 0\n d = defaultdict(list)\n\n for c in s:\n if c == last:\n cnt += 1\n else:\n cnt = 1\n last = c\n heapq.heappush(d[last], cnt)\n if len(d[last]) > 3:\n heapq.heappop(d[last])\n\n ans = -1\n for listFreq in d.values():\n if len(listFreq) < 3:\n continue\n ans = max(ans, listFreq[0])\n return ans\n\n```
4
0
['Hash Table', 'Heap (Priority Queue)', 'Python3']
3
find-longest-special-substring-that-occurs-thrice-i
C++ || sorting and binary search || map || explanation || optimized approach || Easy to understand
c-sorting-and-binary-search-map-explanat-qx73
Intuition\n Describe your first thoughts on how to solve this problem. \n1. store the total count of the characters of the string in the array a \n2. sort all t
garima1609
NORMAL
2023-12-31T05:04:58.631917+00:00
2023-12-31T05:04:58.631946+00:00
242
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. store the total count of the characters of the string in the array a \n2. sort all the characters \n3. apply binary search and check if a character\'s occurence is greater than 3 and then find the character with maximum count together \n4. return answer \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing 2d vector to store different occurence of characters like \nstring a= "fffif"\nso for i->1, f->3,1\n\nUsing binary search we will find a character\'s maximum count like \nin above example we will have for f->1,3 after sorting and after applying binary search mid= 1+(1-1)/2 -> mid= 1\nans= max(0, 1)\nans=1 \n\n# Complexity\n- Time complexity:$$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n bool check(int mid,vector<int> &a)\n {\n int cnt=0;\n \n for(auto x:a)\n {\n cnt+=max(0,x-mid+1);\n }\n \n return cnt>=3;\n }\n \n int maximumLength(string s) {\n \n vector<vector<int>> a(26);\n \n int cnt=1;\n \n for(int i=1;i<s.length();i++)\n {\n if(s[i]!=s[i-1])\n {\n a[s[i-1]-\'a\'].push_back(cnt);\n cnt=1;\n }\n else\n {\n cnt++;\n }\n }\n \n a[s.back()-\'a\'].push_back(cnt);\n \n int ans=-1;\n \n for(int i=0;i<26;i++)\n {\n if(a[i].size()==0)\n {\n continue;\n }\n \n sort(a[i].begin(),a[i].end());\n int start=1,end=a[i].back();\n \n while(start<=end)\n {\n int mid=start+(end-start)/2;\n \n if(check(mid,a[i]))\n {\n ans=max(ans,mid);\n start=mid+1;\n }\n else\n {\n end=mid-1;\n }\n }\n }\n \n return ans;\n }\n};\n```
4
0
['Binary Search', 'Ordered Map', 'Sorting', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
easy solution with explantaion (brute force approach)
easy-solution-with-explantaion-brute-for-tkof
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nLet\'s break down the code and understand the approach:\n\n Map Initia
pahadi_rawat
NORMAL
2023-12-31T04:04:47.302686+00:00
2023-12-31T10:20:20.762532+00:00
771
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nLet\'s break down the code and understand the approach:\n\n Map Initialization:\n The code uses a std::map named mp to store substrings and their frequencies.\n temp is an empty string to store the current substring.\n\n Iteration over the Input String:\n The code iterates through the input string s starting from the second character.\n If the current character is the same as the previous one, it increments the counter ct and appends the character to the temp string.\n If the current character is different, it resets the counter to 1 and updates the temp string.\n\n Substring Generation and Counting:\n Inside the loop, the code generates all possible substrings of temp and increments their count in the map mp.\n It uses a nested loop to iterate through all possible substrings of temp.\n\n Finding Maximum Length:\n After processing the entire string, the code iterates over the map and checks for substrings that appear at least three times (a.second >= 3).\n For such substrings, it calculates their length and updates the maximum length (ans) if the current length is greater.\n\n Return:\n The function returns the maximum length found. If no such substring is found, it returns -1.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(n*k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumLength(string s) {\n map<string, int> mp;\n string temp = "";\n temp += s[0];\n mp[temp]++;\n\n for (int i = 1; i < s.size(); i++) {\n if (s[i] == s[i - 1]) {\n ct++;\n temp += s[i];\n } else {\n ct = 1;\n temp = s[i];\n }\n\n for (int j = 0; j < temp.size(); j++) {\n string local = temp.substr(0, j + 1);\n mp[local]++;\n }\n }\n\n int ans = 0;\n for (auto a : mp) {\n if (a.second >= 3) {\n int size = a.first.size();\n ans = max(ans, size);\n }\n }\n return ans == 0 ? -1 : ans;\n\n }\n};\n```
4
0
['C++']
3
find-longest-special-substring-that-occurs-thrice-i
💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100
easiestfaster-lesser-cpython3javacpython-1tbx
null
Edwards310
NORMAL
2024-12-10T16:07:30.609062+00:00
2024-12-10T16:07:30.609062+00:00
303
false
![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/9fc46acb-7ba4-42e1-864c-3b0e7e0e82b6_1730795144.4340796.jpeg)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n- ***JavaScript Code -->*** https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1475378761\n- ***C++ Code -->*** https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1475215095\n- ***Python3 Code -->*** https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1475362171.com/problems/special-array-ii/submissions/1473978130\n- ***Java Code -->*** https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1475222312\n- ***C Code -->*** https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1475375634\n- ***Python Code -->*** https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1475238484\n- ***C# Code -->*** https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1475376805\n- ***Go Code -->*** https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1475380444\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n![th.jpeg](https://assets.leetcode.com/users/images/210cfa24-4d86-44b3-92eb-2a3190fcdde5_1733846736.4873493.jpeg)\n
3
0
['Hash Table', 'C', 'Sliding Window', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'C#']
1
find-longest-special-substring-that-occurs-thrice-i
simple and clean code
simple-and-clean-code-by-don_quixxote-xber
null
Don_quixxote
NORMAL
2024-12-10T14:55:10.672851+00:00
2024-12-10T14:55:10.672851+00:00
70
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nmap to store - character\'s length and that length\'s count\nthen another map (while looping over one character)to store length\'s frequency \nfor string with length n, you can make 3 n-2 length string (n > 2)\nor n - 1 strings and taking one n - 1 string complete (if available) \nedge cases - length of 1 and 2\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n #define pci pair<char, int>\n\n int maximumLength(string s) {\n int n = s.size();\n map<pci, int> mp;\n\n // {char, length} -> occ.\n for (int i = 0; i < n;) {\n int idx = i;\n while (idx < n && s[idx] == s[i]) idx++;\n mp[{s[i], idx - i}]++;\n i = idx;\n }\n\n int ans = -1;\n for (auto it = mp.begin(); it != mp.end(); ) {\n char ch = it->first.first;\n map<int, int> cnt;\n\n while (it != mp.end() && it->first.first == ch) {\n cnt[it->first.second] += it->second;\n it++;\n }\n\n for (auto& [a, b] : cnt) { // length, occ\n if (b > 2) {\n ans = max(ans, a); // Use the full length\n }\n if (a > 2) {\n ans = max(ans, a - 2); // Remove 2 from the length\n if (cnt[a - 1] || b > 1) {\n ans = max(ans, a - 1); // Remove 1\n }\n }\n if (a == 2) {\n if (b >= 3) ans = max(ans, 2); // Fully utilize 2\'s\n else if (b == 2 || cnt[1]) ans = max(ans, 1); // Handle 2 and 1\n }\n if (a == 1 && b > 2) ans = max(ans, 1); // Single characters\n }\n }\n return ans;\n }\n};\n\n```
3
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Most Optimized with Time complexity of O(NLogN) and beats 99% user in runtime. 🔥🔥🔥
most-optimized-with-time-complexity-of-o-v6dw
null
dev_bhatt202
NORMAL
2024-12-10T04:01:14.216238+00:00
2024-12-10T04:01:14.216238+00:00
154
false
# Complexity\n- Time complexity: O(NLogN)\n\n![Screenshot 2024-12-10 091539.png](https://assets.leetcode.com/users/images/2eeca300-9563-466e-96fa-37f3c5281b4c_1733803143.6100464.png)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```java []\npublic class Solution {\n public int maximumLength(String s) {\n int n = s.length();\n int l = 1, r = n;\n\n if (!helper(s, n, l)) return -1;\n\n while (l + 1 < r) {\n int mid = (l + r) / 2;\n if (helper(s, n, mid)) l = mid;\n else r = mid;\n }\n\n return l;\n }\n\n private boolean helper(String s, int n, int x) {\n int[] cnt = new int[26];\n int p = 0;\n\n for (int i = 0; i < n; i++) {\n while (s.charAt(p) != s.charAt(i)) p++;\n if (i - p + 1 >= x) cnt[s.charAt(i) - \'a\']++;\n if (cnt[s.charAt(i) - \'a\'] > 2) return true;\n }\n\n return false;\n }\n}\n```
3
0
['Java']
1
find-longest-special-substring-that-occurs-thrice-i
Python: Well Explained O(N) Solution Using Two Counters (Dictionaries)
python-well-explained-on-solution-using-9y7ay
Sep 16, 2024:\nRuntime beats 97.53% | Memory beats 47.58%\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nNaive solution would be
PTLin84
NORMAL
2024-09-05T04:51:15.841904+00:00
2024-09-20T16:39:11.215828+00:00
315
false
**Sep 16, 2024:**\nRuntime beats 97.53% | Memory beats 47.58%\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNaive solution would be to find all substrings, count the ones that are special (repeating one letter), and return the maximum length. However, this will very likely be too slow given that finding all substrings is **O(N^2)**, and getting the substring value using `s[ind1:ind2]` (refer to Python slicing) is itself an **O(N)** operation because it is making a new string. This will make this naive solution to be **O(N^3)** for time complexity.\n\nA better approach is to consider what **special** means. It means a repeated sequence of the same English letter. So instead of checking all possible substrings, we can only check for repeated sequences, which requires only one pass and thus **O(N)** runtime. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**STEP 1**\nTo check for repeated sequences, we can use two pointers and a while loop to achieve this easily. In the meantime, we use a dictionary counter to count the frequency of each unique repeated sequence, where `key=substring` and `value=frequency`, e.g., `counter = {"aaa": 1}`. ***\u26A0\uFE0FNote that these repeated sequences are not overlapping.***\n\n**STEP 2**\nHere comes the next question: how about the repeated sequences inside a repeated sequence? For example, repeated sequence **"aaa"** contains two **"aa"** and three **"a"** in it, and these are not counted in **STEP 1**. (Let\'s call them *sub-repeated-sequences*)\n\nTherefore, we need to process the repeated sequences we found from **STEP 1** to extract and count the *sub-repeated-sequences* inside them. We can use a for loop to loop from `i=1` to `i=len(repeated_sequence) - 1`, where `i` is the length of a *sub-repeated-sequences*, and the frequency of these *sub-repeated-sequences* will simply be `len(repeated_sequence) - i + 1`.\n\n***\u26A0\uFE0FNote that we need to create a copy of the counter from STEP 1 to avoid iterating while modifying the dictionary.***\n\n**STEP 3**\nFinally, we have the `processed_counter` which contains all special substrings, including *sub-repeated-sequences*. So, we can simply iterate through the dictionary\'s key-value pairs, and find the one that has the longest string length.\n\n# Complexity\n- Time complexity: **O(N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nFinding all repeated sequences is **O(N)**. Processing repeated sequences is also **O(N)** because these repeated sequences are not overlapped, we will at most iterate through each character in `s` once. Iterating through `processed_counter` is **O(N)**.\n- Space complexity: **O(N)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nBoth `counter` and `processed_counter` are **O(N)**. The rest are simply **O(1)**.\n\n# Code\n```python3 []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n \n # Step1:\n # Time=O(N), Space=O(N)\n # two pointers to go through all repeated letter substrings (no overlap)\n counter = dict()\n l, r = 0, 1\n\n while r <= len(s):\n if not r == len(s) and s[l] == s[r]:\n r += 1\n else:\n substring = s[l] * (r - l)\n counter[substring] = counter.get(substring, 0) + 1\n l, r = r, r + 1\n\n # Step2:\n # Time=O(N), Space=O(N)\n # process substrings within substrings\n processed_counter = counter.copy()\n for key, val in counter.items():\n if len(key) > 1:\n for i in range(1, len(key)):\n substring = key[0] * i\n frequency = (len(key) - i + 1) * val # initial substrings are not overlapped\n processed_counter[substring] = processed_counter.get(substring, 0) + frequency\n\n # Step3:\n # Time=O(N), Space=O(1)\n # Examine the processed_counter and return final answer\n max_length = -1\n for key, val in processed_counter.items():\n if val >= 3:\n max_length = max(max_length, len(key))\n \n return max_length\n\n```
3
0
['Hash Table', 'Counting', 'Python3']
1
find-longest-special-substring-that-occurs-thrice-i
O(n) Solution | Sliding Window | C++
on-solution-sliding-window-c-by-darkaadi-h700
Approach\n Describe your approach to solving the problem. \n1) Think about sliding window approach to consider substrings to find the longest special substring
darkaadityaa
NORMAL
2024-01-02T16:51:35.107342+00:00
2024-01-02T16:51:35.107364+00:00
416
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Think about sliding window approach to consider substrings to find the longest special substring according to conditons provided.\n\n2) Maintain a map to keep track of various substring and it\'s occurences. For each current substring into consideration, check for occurence which is greater than 2. \n\n3) If any such substring occurs, where result is less than current substring\'s length, consider this length as the new result. If no such present, check and return -1. Else return result. \n\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<br>\n\n**If you find this solution helpful, consider giving it an upvote!**\n\n# Code\n```\nclass Solution {\npublic:\n int maximumLength(string s){\n int n=s.size(), i=0, j=1, result=INT_MIN;\n unordered_map<string,int> mp;\n string temp="";\n temp+=s[0];\n while(j<n){\n if(s[j]==s[j-1]) temp+=s[j];\n else{\n int currLen=j-i-2;\n mp[temp]++;\n temp.pop_back();\n if(temp.size()>0) mp[temp]+=2;\n if(currLen>0) result=max(result,currLen);\n i=j;\n temp=s[j];\n }\n j++;\n }\n mp[temp]++;\n temp.pop_back();\n if(temp.size()>0) mp[temp]+=2;\n int currLen=j-i-2;\n if(currLen>0) result=max(result,currLen);\n for(auto it : mp){\n if(it.second>2){\n auto str=it.first.size();\n result=max(result,static_cast<int>(str));\n }\n }\n return result==INT_MIN ? -1 : result; \n }\n};\n```
3
0
['Hash Table', 'Sliding Window', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
BEATS 100% || RECURSIVE SOLUTION
bears-100-recursive-solution-by-shyam4kb-takf
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
shyam4KB
NORMAL
2023-12-31T04:04:51.573520+00:00
2024-12-10T04:03:30.336758+00:00
28
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 HashMap<String,Integer> map ;\n public int maximumLength(String s) {\n int ans = -1;\n map = new HashMap<>();\n for (int i = 0; i < s.length(); i++)\n helper("",s,i);\n\n for (String str : map.keySet()){\n if (map.get(str) >= 3){\n int temp = str.length();\n if (temp > ans) ans = temp;\n }\n }\n if (ans == 0) return -1;\n return ans;\n }\n \n private void helper(String up,String p,int j){\n if (j >= p.length()) {\n if (map.containsKey(up)) map.put(up, map.get(up) + 1);\n else map.put(up, 1);\n \n return;\n }\n if (up.length() == 0 || up.charAt(up.length() -1) == p.charAt(j))\n helper(up + p.charAt(j), p, j + 1);\n helper(up,p,p.length());\n \n }\n}\n```
3
0
['Java']
0
find-longest-special-substring-that-occurs-thrice-i
Easy and Clear Java Solution Using HashMap
easy-and-clear-java-solution-using-hashm-yhcm
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
20R01A66D7
NORMAL
2023-12-31T04:03:35.842261+00:00
2023-12-31T04:03:35.842294+00:00
573
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maximumLength(String s) {\n HashMap<String,Integer>map=new HashMap<>();\n int n=s.length();\n for(int i=0;i<n;i++){\n String str="";\n for(int j=i;j<n;j++){\n str+=s.charAt(j);\n if(special(str)){\n if(map.containsKey(str)) map.put(str,map.get(str)+1);\n else map.put(str,1);\n }\n }\n }\n int max=-1;\n for(String s1:map.keySet()){\n if(map.get(s1)>2) max=Math.max(max,s1.length());\n }\n return max;\n }\n \n public boolean special(String str){\n for(int i=0;i<str.length()-1;i++){\n if(str.charAt(i)!=str.charAt(i+1)) return false;\n }\n return true;\n }\n}\n```
3
0
['Java']
1
find-longest-special-substring-that-occurs-thrice-i
✅ C++ | Brute Force |
c-brute-force-by-sirius_108-glkd
Approach\n Describe your approach to solving the problem. \nBrute Force\n\n# Code\n\nclass Solution {\npublic:\n int maximumLength(string s) {\n int N
sirius_108
NORMAL
2023-12-31T04:00:57.431050+00:00
2023-12-31T08:58:52.869463+00:00
244
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nBrute Force\n\n# Code\n```\nclass Solution {\npublic:\n int maximumLength(string s) {\n int N = s.length();\n for(int i = N-2; i>=1; i--)\n {\n for(char c = \'a\'; c<=\'z\'; c++)\n {\n int cnt = 0;\n for(int j = 0; j<=N-i; j++)\n {\n if(s[j] != c) continue;\n string str = s.substr(j, i);\n if(str == string(i, c))\n {\n cnt++;\n }\n }\n if(cnt>=3)\n return i;\n }\n }\n return -1;\n }\n};\n```\n> # Please Upvote\n![rocket.gif](https://assets.leetcode.com/users/images/fbd969bd-d430-49f5-9eff-dda7571aadcf_1703994648.0157042.gif)\n
3
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
[Python3] - Very simple O(n) solution beats 100%, 0ms runtime 🔥🔥🔥
python3-very-simple-on-solution-beats-10-dou3
null
starlex
NORMAL
2024-12-10T14:37:51.465157+00:00
2024-12-10T14:57:40.263656+00:00
50
false
# Key Idea\nWe decompose the original string into runs of identical characters. For example, if s = "aaabaaa", we have runs (a,3), (b,1), (a,3). Each run (c, length) represents a contiguous segment of the character c repeated length times. For these segments we want to count how many times they appear in this case the counts would be `counts[(a, 3)] = 2` and `counts[(b, 1)] = 1` \n\nThen we just do some case-work to check for the solution based on this, if a string is of length n, we know that it has at least 3 substrings with length n-2 and at least 2 with length n - 1.\n\n# Code\n```python3 []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n n = len(s)\n prev_char = s[0]\n prev_len = 1\n counts = defaultdict(int)\n for i in range(1, n):\n if s[i] == prev_char:\n prev_len += 1\n else:\n counts[(prev_char, prev_len)] += 1\n prev_char = s[i]\n prev_len = 1\n counts[(prev_char, prev_len)] += 1\n res = -1 \n for (char, length), appearances in counts.items():\n if appearances >= 3:\n res = max(res, length)\n if appearances == 2 or (char, length - 1) in counts:\n res = max(res, length - 1)\n\n res = max(res, length - 2)\n return res if res != 0 else -1\n\n```\n\n![image.png](https://assets.leetcode.com/users/images/70b2dea0-acb2-4f05-a7fa-9b7fe38fe851_1733841462.943793.png)\n
2
0
['Hash Table', 'String', 'Counting', 'Python3']
2
find-longest-special-substring-that-occurs-thrice-i
C++ Code ✅✅ || Simple Approach✅✅
c-code-simple-approach-by-yashm01-30al
null
yashm01
NORMAL
2024-12-10T11:42:52.870024+00:00
2024-12-10T11:42:52.870024+00:00
35
false
# "Every solution starts with a thought, and every thought leads to a solution. \uD83D\uDCA1"\n\n# Intuition \uD83E\uDD14\nThe idea is to identify **"special substrings"** \uD83C\uDF1F, where all characters are the same. We will check every substring in the given string \uD83D\uDD0D and count the occurrences of these substrings. Once any substring occurs 3 or more times \uD83D\uDD04, we update the maximum length found so far.\n\n# Approach \uD83D\uDE80\n1. Initialize an unordered map (`umap`) to track the occurrences of substrings \uD83D\uDDFA\uFE0F.\n2. Iterate over all possible starting points of substrings in the given string \uD83D\uDCCF.\n3. For each starting point, generate substrings by extending them character by character as long as the substring remains a "special substring" (i.e., all characters are the same) \uD83D\uDCAC.\n4. If a substring appears at least 3 times \uD83D\uDD01, check if it\'s the longest special substring found so far \uD83C\uDFC6.\n5. Return the length of the longest such substring \uD83D\uDCD0.\n\n# Complexity \uD83E\uDDEE\n- **Time complexity**: $$O(n^2)$$, where $$n$$ is the length of the string. For each character, we try to extend the substring up to the length of the string \uD83D\uDD04.\n- **Space complexity**: $$O(k)$$, where $$k$$ is the number of unique substrings stored in the unordered map \uD83D\uDCCA.\n\n# Code \uD83D\uDCBB\n```cpp\nclass Solution {\npublic:\n int maximumLength(string s) {\n int size = s.size();\n int ans = -1;\n unordered_map<string,int> umap;\n \n for(int i = 0; i < size; i++) {\n string str = "";\n for(int j = i; j < size; j++) {\n if (str.empty() || s[j] == str[0]) {\n str += s[j]; // Add to the current special substring \uD83D\uDCDD\n umap[str]++; // Count the occurrences of this substring \uD83D\uDCC8\n // If the substring has occurred at least 3 times, update the answer \uD83C\uDFAF\n if (umap[str] >= 3) {\n ans = max(ans, (int)str.size());\n }\n } else {\n break; // Exit the loop when characters are different \uD83D\uDEAA\n }\n }\n }\n return ans; // Return the longest special substring \uD83D\uDCCF\n }\n};\n
2
0
['Hash Table', 'String', 'Counting', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Simple & Efficient Substring Enumeration and Frequency Counting for Maximum Special Substring Length
simple-efficient-substring-enumeration-a-mq8v
null
anand_shukla1312
NORMAL
2024-12-10T08:48:11.757948+00:00
2024-12-10T08:48:11.757948+00:00
9
false
# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n # Create a dictionary to store frequency of all substrings\n substring_count = {}\n n = len(s)\n\n # Generate substrings and count their occurrences\n for i in range(n):\n substring = ""\n for j in range(i, n):\n # Append characters to form substrings\n substring += s[j]\n # Check if the substring is "special"\n if len(set(substring)) == 1:\n substring_count[substring] = substring_count.get(substring, 0) + 1\n\n # Find the maximum length substring with at least 3 occurrences\n max_length = -1\n for substring, count in substring_count.items():\n if count >= 3:\n max_length = max(max_length, len(substring))\n\n return max_length\n```\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A
2
0
['Hash Table', 'String', 'Counting', 'Python3']
0
find-longest-special-substring-that-occurs-thrice-i
🔥BEATS 💯 % 🎯 |✨SUPER EASY BEGINNERS 👏
beats-super-easy-beginners-by-codewithsp-t6ml
null
CodeWithSparsh
NORMAL
2024-12-10T07:23:22.499982+00:00
2024-12-10T07:37:50.185149+00:00
239
false
![image.png](https://assets.leetcode.com/users/images/e32a27ea-1eb4-4ada-8a19-882a666b3f52_1733815208.9234703.png)\n\n\n---\n\n![1000029376.png](https://assets.leetcode.com/users/images/a4066160-f7b3-4203-bf13-9df70cb6bc21_1733816255.5412245.png)\n\n---\n\n# Intuition\nTo solve the problem:\n1. We need to find the longest substring of the input string `s` that appears at least three times.\n2. Brute force is an intuitive approach: check all possible substrings of length `1` to `n-2` and count their occurrences.\n3. Use a `Map` or `HashMap` to store the counts of substrings and track the maximum length of substrings that meet the condition.\n\n---\n\n# Approach\n1. Iterate over all possible substring lengths, starting from `1` up to `n-2` (since a substring must appear at least three times).\n2. For each substring length, extract all possible substrings of that length using a sliding window approach.\n3. Use a hash table to count occurrences of each substring.\n4. If any substring has a count of `3` or more, update the maximum length.\n5. Return the maximum length found.\n\n---\n\n# Complexity\n- **Time Complexity**: \n $$O(n^3)$$ (worst-case scenario, iterating over all substrings of varying lengths).\n- **Space Complexity**: \n $$O(n^2)$$ for storing substrings in the hash map.\n\n---\n\n\n```dart []\nclass Solution {\n int maximumLength(String s) {\n int minRange = 1;\n int maxRange = s.length - 2;\n int length = -1;\n\n for (int i = minRange; i <= maxRange; i++) {\n Map<String, int> record = {};\n for (int j = 0; j <= s.length - i; j++) {\n String sub = s.substring(j, j + i);\n record[sub] = (record[sub] ?? 0) + 1;\n }\n record.forEach((key, value) {\n if (value >= 3) length = i;\n });\n }\n\n return length;\n }\n}\n```\n\n\n```python []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n min_range = 1\n max_range = len(s) - 2\n length = -1\n\n for i in range(min_range, max_range + 1):\n record = {}\n for j in range(len(s) - i + 1):\n sub = s[j:j + i]\n record[sub] = record.get(sub, 0) + 1\n for key, value in record.items():\n if value >= 3:\n length = i\n\n return length\n```\n\n\n```cpp []\n#include <string>\n#include <unordered_map>\n#include <set>\nusing namespace std;\n\nclass Solution {\npublic:\n int maximumLength(string s) {\n int minRange = 1, maxRange = s.size() - 2, length = -1;\n\n for (int i = minRange; i <= maxRange; i++) {\n unordered_map<string, int> record;\n\n for (int j = 0; j <= s.size() - i; j++) {\n string sub = s.substr(j, i);\n record[sub]++;\n }\n\n for (auto &entry : record) {\n if (entry.second >= 3) length = i;\n }\n }\n\n return length;\n }\n};\n```\n\n\n```java []\nimport java.util.HashMap;\n\nclass Solution {\n public int maximumLength(String s) {\n int minRange = 1;\n int maxRange = s.length() - 2;\n int length = -1;\n\n for (int i = minRange; i <= maxRange; i++) {\n HashMap<String, Integer> record = new HashMap<>();\n for (int j = 0; j <= s.length() - i; j++) {\n String sub = s.substring(j, j + i);\n record.put(sub, record.getOrDefault(sub, 0) + 1);\n }\n for (String key : record.keySet()) {\n if (record.get(key) >= 3) length = i;\n }\n }\n\n return length;\n }\n}\n```\n\n\n```javascript []\nvar maximumLength = function(s) {\n let minRange = 1, maxRange = s.length - 2, length = -1;\n\n for (let i = minRange; i <= maxRange; i++) {\n let record = {};\n for (let j = 0; j <= s.length - i; j++) {\n let sub = s.substring(j, j + i);\n record[sub] = (record[sub] || 0) + 1;\n }\n for (let key in record) {\n if (record[key] >= 3) length = i;\n }\n }\n\n return length;\n};\n```\n\n\n```go []\npackage main\n\nfunc maximumLength(s string) int {\n minRange, maxRange := 1, len(s)-2\n length := -1\n\n for i := minRange; i <= maxRange; i++ {\n record := make(map[string]int)\n for j := 0; j <= len(s)-i; j++ {\n sub := s[j : j+i]\n record[sub]++\n }\n for _, value := range record {\n if value >= 3 {\n length = i\n }\n }\n }\n\n return length\n}\n```\n\n---\n\n![image.png](https://assets.leetcode.com/users/images/d81a7cee-fa73-41a2-82dc-65bf475d960c_1722267693.3902693.png) {:style=\'width:250px\'}
2
0
['Hash Table', 'String', 'C', 'Sliding Window', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'Dart']
3
find-longest-special-substring-that-occurs-thrice-i
Simple Approach || Binary Search with hashmap
simple-approach-binary-search-with-hashm-7759
null
akshatchawla1307
NORMAL
2024-12-10T06:17:47.386347+00:00
2024-12-10T06:17:47.386347+00:00
14
false
# Intuition\n**Given that special substring should occur thrice, then the maxiumum size that it can hold is (n-2). Whereas minimum possible size is 1. So, i used binary search with start=1 and end-n-1 to check that whether any value in range(1,n-2) could be a possible solution or not.**\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize \'ans\' with -1, so that if no answer is found than -1 could be returned.\n2. Implement binary search from start=1 to end-n-2. We will check that for each value of mid=(start+end)/2, whether mid is our answer or not.\n3. To check that \'mid\' is answer, initialize a map \'m\', iterating through the string, if freq of any character becomes equal to mid, than we can say that a special substring of that character of size mid is found. So we will increment the value of that character in the map.\n4. After checking for each character in string s, if any special substring is found atleast thrice than we will store the value of mid in ans and again check for a greater value of mid(i.e. start=mid+1).\n5. If no special substring is found atleast thrice, than we will check for smaller values of mid (i.e. end=mid-1)\n6. Time complexity: log N for binary search and N for searching in string s. So, overall TC=O(N*logN)\n7. Space complexity: O(N) because of map m.\n<!-- Describe your approach to solving the problem. -->\n\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```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n int n=s.size();\n int ans=-1;\n int start=1,end=n-2;\n while(start<=end)\n {\n int mid=start+(end-start)/2;\n int freq=1;\n unordered_map<int,int>m;\n if(freq==mid)\n m[s[0]]++;\n for(int i=1;i<n;i++)\n {\n if(s[i]==s[i-1])\n freq++;\n else\n freq=1;\n if(freq>=mid)\n m[s[i]]++; \n }\n int flag=1;\n for(auto i:m)\n {\n if(i.second>=3)\n {\n ans=max(ans,mid);\n start=mid+1;\n flag--;\n break;\n }\n }\n if(flag)\n end=mid-1;\n }\n return ans;\n \n }\n};\n```
2
0
['Hash Table', 'Binary Search', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Simple Approach || Binary Search with hashmap
simple-approach-binary-search-with-hashm-aki8
null
akshatchawla1307
NORMAL
2024-12-10T05:44:04.217878+00:00
2024-12-10T05:44:04.217878+00:00
6
false
# Intuition\nGiven that special substring should occur thrice, then the maxiumum size that it can hold is (n-2). Whereas minimum possible size is 1. So, i used binary search with start=1 and end-n-1 to check that whether any value in range(1,n-2) could be a possible solution or not.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize \'ans\' with -1, so that if no answer is found than -1 could be returned.\n2. Implement binary search from start=1 to end-n-2. We will check that for each value of mid=(start+end)/2, whether mid is our answer or not.\n3. To check that \'mid\' is answer, initialize a map \'m\', iterating through the string, if freq of any character becomes equal to mid, than we can say that a special substring of that character of size mid is found. So we will increment the value of that character in the map.\n4. After checking for each character in string s, if any special substring is found atleast thrice than we will store the value of mid in ans and again check for a greater value of mid(i.e. start=mid+1).\n5. If no special substring is found atleast thrice, than we will check for smaller values of mid (i.e. end=mid-1)\n6. Time complexity: log N for binary search and N for searching in string s. So, overall TC=O(N*logN)\n7. Space complexity: O(N) because of map m.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: **O(N*logN)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(N)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n int n=s.size();\n int ans=-1;\n int start=1,end=n-2;\n while(start<=end)\n {\n int mid=start+(end-start)/2;\n int freq=1;\n unordered_map<int,int>m;\n if(freq==mid)\n m[s[0]]++;\n for(int i=1;i<n;i++)\n {\n if(s[i]==s[i-1])\n freq++;\n else\n freq=1;\n if(freq>=mid)\n m[s[i]]++; \n }\n int flag=1;\n for(auto i:m)\n {\n if(i.second>=3)\n {\n ans=max(ans,mid);\n start=mid+1;\n flag--;\n break;\n }\n }\n if(flag)\n end=mid-1;\n }\n return ans;\n \n }\n};\n```
2
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
C++ || Brute Force
c-try-every-special-substring-by-ahmedsa-0hzo
null
AhmedSayed1
NORMAL
2024-12-10T00:21:29.654225+00:00
2024-12-10T01:48:12.098596+00:00
42
false
\n# Explaining\n <h3> Try every special substrings and follow the comments between the code for more explaining </h3>\n\n# Complexity\n- <h3>O(n * n * log(n))</h3>\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n map<string, int>mp;\n\n int ans = -1;\n for(int i = 0; i < s.size() ; i++){ // Try every special substring \n set<char>st;\n string t;\n\n for(int j = i ; j < s.size() ; j++){\n st.insert(s[j]);\n if(st.size() > 1)break; // if number of Distinct Characters > 1 break;\n\n t += s[j], mp[t]++; // Makes frequency of every valid substring\n }\n }\n\n for(auto [a, b] : mp)\n if(b > 2)ans = max(ans, (int)a.size()); // maximize the size answer if its frequnce at least thrice\n\n return ans;\n }\n};\n```\n\n![hhh.png](https://assets.leetcode.com/users/images/f96694bb-97ed-4614-b21c-f026fc74bfe5_1733641265.743601.png)
2
0
['Hash Table', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Easy Fully explained solution | Sliding Window + Binary Search | O(nlogn) solution
easy-fully-explained-solution-sliding-wi-nlg1
Intuition\nThe problem is about finding the maximum length of a substring that appears at least three times in a given string s. The core intuition is to use a
sakshamsharma809
NORMAL
2024-08-24T10:14:56.814229+00:00
2024-08-24T10:16:45.092453+00:00
67
false
# Intuition\nThe problem is about finding the maximum length of a substring that appears at least three times in a given string s. The core intuition is to use a sliding window approach to check for repeating substrings and then use binary search to efficiently find the maximum length of such substrings.\n\n# Approach\n## Sliding Window:\n\nThe ableToFindString method checks if there is any substring of a given windowSize that appears at least three times in the string s.\n\nWe use a sliding window to traverse through the string s:\nAs we iterate through s, we form substrings of size windowSize using a StringBuilder.\n\nIf the substring matches the windowSize, we store it in a HashMap where the key is the substring and the value is the frequency of that substring.\n\nIf the frequency of any substring reaches 3, we return true.\n\nIf no such substring is found, we return false.\n\n\n## Binary Search for Maximum Length:\n\nTo efficiently determine the maximum length of such a substring, we use binary search:\n\nWe set the search range between 1 (smallest possible length) and s.length() (the entire string).\n\nWe calculate the middle value mid and check if there is a substring of length mid that appears at least three times using the ableToFindString method.\n\nIf such a substring exists, it means we can potentially find a longer one, so we move our search to the right half (low = mid + 1).\n\nIf not, we move our search to the left half (high = mid - 1).\n\nThe binary search continues until low exceeds high. The maximum length found will be stored in high.\n\nAfter the binary search completes, if high is 0, it means no such substring was found, so we return -1.\n\nOtherwise, we return high, which is the maximum length of a substring that appears at least three times.\n\n# Complexity\n- Time complexity:\n\n- Sliding Window (ableToFindString):\nEach substring check takes O(n) time, where n is the length of s.\nThe HashMap operations (insert and lookup) generally take O(1) on average.\n\n- Binary Search:\nThe binary search runs O(log n) iterations.\nEach iteration calls the ableToFindString method, which takes O(n) time.\n\n- Overall Time Complexity:\nThe overall time complexity is O(n log n), where n is the length of the string s.\n\n- Space complexity:\nThe space complexity is primarily due to the HashMap and StringBuilder used in the ableToFindString method.\n\n- HashMap: In the worst case, the HashMap could store all possible substrings of size mid, but this is usually far less than n.\n\n- StringBuilder: The size of the StringBuilder is proportional to the windowSize, which is O(n).\n\n- Overall Space Complexity:\nThe overall space complexity is O(n) due to the auxiliary space used by the HashMap and StringBuilder.\n\n# Code\n```java []\nclass Solution {\n\n private boolean ableToFindString(String s, int windowSize){\n HashMap<String, Integer> map = new HashMap<>();\n int j = 0;\n StringBuilder sb = new StringBuilder();\n\n while(j<s.length()){\n if(j == 0 || (sb.length() > 0 && sb.charAt(sb.length() - 1) == s.charAt(j)))\n sb.append(s.charAt(j));\n else{\n sb = new StringBuilder();\n sb.append(s.charAt(j));\n }\n\n if(sb.length() > windowSize){\n sb.deleteCharAt(0);\n }\n\n if(sb.length() == windowSize){\n map.put(sb.toString(), \n map.getOrDefault(sb.toString(), 0) + 1);\n\n if(map.get(sb.toString()) >= 3)\n return true;\n }\n\n j++;\n }\n\n return false;\n }\n\n public int maximumLength(String s) {\n int low = 1, high = s.length();\n\n while(low<=high){\n int mid = low + (high - low)/2;\n\n if(ableToFindString(s, mid))\n low = mid + 1;\n else\n high = mid - 1;\n }\n\n return (high == 0)?-1:high;\n }\n}\n```\n\nPlease upvote if you find it useful.....
2
0
['Hash Table', 'String', 'Binary Search', 'Sliding Window', 'Counting', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
BEATS 97%|| EASY || 3STEPS|| Same as 2982
beats-97-easy-3steps-same-as-2982-by-abh-dre1
Intuition\n Describe your first thoughts on how to solve this problem. \n# THE SAME CODE WILL WORK FOR 2982 ON LEETCODE AS WELL.\nThis code determines the maxim
Abhishekkant135
NORMAL
2024-01-09T08:45:18.739519+00:00
2024-01-09T08:45:18.739551+00:00
787
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# THE SAME CODE WILL WORK FOR 2982 ON LEETCODE AS WELL.\nThis code determines the maximum length of a substring that can be formed by deleting at most one character from the input string s, such that the substring contains only one distinct character (i.e., all characters are the same).\n# THANKS TO GEEKSTOCODE\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Count Substrings:\n\nCreate a HashMap called mp to store the count of occurrences of each unique substring in s.\nIterate through s using two pointers (i and j) to identify substrings with consecutive identical characters.\nFor each identified substring, increment its count in mp.\n2. Find Maximum Length:\n\nInitialize ans to -1 to track the maximum length found so far.\nIterate through the keys of mp (each key representing a unique substring).\n3. For each substring:\nIf its length is 1 and its count is at least 3, update ans to 1 (e.g., "aaa").\nIf its length is 2 or more:\nCheck for various conditions based on its count and whether removing one character can still create a valid substring.\nUpdate ans accordingly, considering factors like the substring\'s length and the presence of sub-substrings.\n4. Return Maximum Length:\n\nReturn the final value of ans, representing the maximum length of a valid substring that can be forme\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWORST CASE ITS QUADRATIC.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maximumLength(String s) {\n HashMap<String,Integer> hm=new HashMap<>();\n int j=0;\n for(int i=0;i<s.length();){\n while(j<s.length() && s.charAt(i)==s.charAt(j)){\n j++;\n }\n hm.put(s.substring(i,j),hm.getOrDefault(s.substring(i,j),0)+1);\n i=j;\n }\n int ans=-1;\n for(String it : hm.keySet()){\n int len = it.length();\n int value = hm.get(it);\n if(len==1 && value>=3){\n ans=Math.max(ans,1);\n }\n else if(len>=2){\n if(value>=3){\n ans=Math.max(ans,len);\n }\n else if(value==2){\n ans=Math.max(ans,len-1);\n }\n else if(value==1 && hm.containsKey(it.substring(0,len-1))){\n ans=Math.max(ans,len-1);\n }\n\n else if (len >= 3) {\n ans = Math.max(ans, len - 2);\n }\n\n }\n }\n return ans;\n }\n}\n```
2
0
['Hash Table', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
[C++] Brute Force, Try All Possible Special Substring
c-brute-force-try-all-possible-special-s-ntz0
Intuition\n Describe your first thoughts on how to solve this problem. \n- Try all possible special substring\n- Get the occurrence of the special substring\n\n
pepe-the-frog
NORMAL
2024-01-03T04:06:06.829823+00:00
2024-01-03T04:06:06.829853+00:00
588
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Try all possible special substring\n- Get the occurrence of the special substring\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Slide the window with width `len`\n- Count the occurrence of the special substring\n\n# Complexity\n- Time complexity: $$O(n ^ 3)$$\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 // time/space: O(n ^ 3)/O(1)\n int maximumLength(string s) {\n int n = s.size();\n int result = -1;\n // try all possible special substring\n for (char c = \'a\'; c <= \'z\'; c++) {\n for (int len = 1; len <= n; len++) {\n // get the occurrence of the special substring\n if (getOccurrence(s, c, len) >= 3) result = max(result, len);\n }\n }\n return result;\n }\nprivate:\n int getOccurrence(const string& s, char c, int len) {\n int occurrence = 0;\n // slide the window with width `len`\n for (int i = 0; (i + len) <= s.size(); i++) {\n bool matched = true;\n for (int j = 0; j < len; j++) {\n if (s[i + j] != c) {\n matched = false;\n break;\n }\n }\n if (matched) occurrence++;\n }\n return occurrence;\n }\n};\n```
2
0
['Sliding Window', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Are You Special❓|| T.C. : O(n^3) || S.C. : (n)
are-you-special-tc-on3-sc-n-by-algorhyth-9vl3
Intuition\n Describe your first thoughts on how to solve this problem. \n- Given a string s, we have to return the maximum length of special substring that occu
AlgoRhythmic_Minds
NORMAL
2024-01-01T17:13:14.865340+00:00
2024-01-02T13:47:36.024906+00:00
406
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Given a string s, we have to return the maximum length of special substring that occurs at least thrice time in a string s.\n- A special substring is a string having all the same characters. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Use a map to count the frequency of special substring.(where substring act as key), set ans to 0.\n- for every substring check whether it is special or not.\n- if yes, increment its count by 1.\n- Now, set an iterator for map and check whether the frequency of string acting as key is more than or equal to 3. if yes, update ans to max(ans,length of string).\n- return ans.\n# Complexity\n- Time complexity: O(n * n * n/2) ~ O(n^3)\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 {\nprivate:\n bool special(string &s,int i,int j){\n while(i<j){\n if(s[i]!=s[i+1]) return false;\n i++;\n }\n return true;\n}\npublic:\n int maximumLength(string s) {\n int i,j;\n map<string,int> count;\n for(i=0;i<s.length();i++){\n for(j=i;j<s.length();j++){\n if(special(s,i,j)){\n count[s.substr(i,j-i+1)]++;\n }\n }\n }\n int ans=0;\n for(auto i : count){\n string str=i.first;\n if(i.second>=3 && str.length()>ans) ans=str.length();\n }\n if(ans==0) return -1;\n return ans;\n }\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
2
0
['Ordered Map', 'C++']
2
find-longest-special-substring-that-occurs-thrice-i
✅✅✅Beats 100% using HashMap in java
beats-100-using-hashmap-in-java-by-jaiva-84rx
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires to check longest special substring which occurs thrice or more. To
jaivant_manki
NORMAL
2023-12-31T15:22:56.549078+00:00
2024-01-01T11:48:17.172934+00:00
30
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires to check longest special substring which occurs thrice or more. To find this out we have to check all the possible substrings that can be formed and the number of times they occur. Thus we need to find a way to keep track of the special substring we need to store:\n\n- **the special substring**\n- **the length of the string** (ie.the number of times the character has been repeated in the string)\n- **and the number of times it occurs**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. To solve this problem we use **HashMap** to maintain a record of the above. We use the interface **Map.Entry** to store a HashMap structure as the key and an integer as the value;\n```\nMap<Map.Entry<Character,Integer>,Integer> map = new HashMap<>();\n```\nwhere, \n- **The inner hashMap is the outer hashMap\'s key** : Map.Entry<Character,Integer> is used to store the repeated character in the string and stores the number of times the character has occured(ie. also the length of the substring) \nExample : Stores \'a\' for the substring \'aaa\' and stores 3 as \'a\' occured 3 times in \'aaa\' `Key< a , 3 >` will the key for above example.\n- **Outer hashMap\'s value** : The value stored for the above HashMap or key is the number of occurences of the same special substring.\n\n2. We iterate through the string till the end and inside it we initialize a variable `int count = 1;` which helps to count the occurences of the character in the string.\n\n3. Then we store the `Key<character,number of characters in the string>` and it\'s occurence is checked and updated everytime it forms the same substring.\n\n4.In the inner for loop, we iterate from the current index till the end of the string and check for the codition,\n```\nif(j+1<l && st.charAt(j+1)==st.charAt(j))\n```\nwhich checks if the subtring\'s next consecutive characters are same thus forming the special substring. Everytime it is evaluated to,\n- **True** : we increment the `count++` and the number of occurences of the string in the hashmap\n- **False** : It means that the next charcter encountered is not of the same character in the substring and thus we end the creation of substring from that particular `index i`.\n4. Finally, we iterate through the hashmap and check if the number of times a substring has occured is greater than or equal to 3.If,\n- **True** : We use `res` to store the maximum length of the substring encountered.\n- **False** : We ignore the substring as it has less than 3 occurences.\n\n# Time complexity\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(n X m), where \n\n- n : the length of the string\n- m : the length of substring from current index to the final index ie. (n-i)\n\n# Code\n```\nclass Solution {\n public int maximumLength(String st) {\n int res = -1;\n Map<Map.Entry<Character,Integer>,Integer> map = new HashMap<>();\n int l = st.length();\n for(int i=0;i<l;i++){\n int count = 1;\n map.put(Map.entry(st.charAt(i),count),map.getOrDefault(Map.entry(st.charAt(i),count),0)+1);\n for(int j=i;j<l;j++){\n if(j+1<l && st.charAt(j+1)==st.charAt(j)){\n count++;\n map.put(Map.entry(st.charAt(i),count),map.getOrDefault(Map.entry(st.charAt(i),count),0)+1);\n }\n else break;\n }\n }\n for(Map.Entry<Map.Entry<Character,Integer>,Integer> entry:map.entrySet()){\n if(entry.getValue()>=3) res=Math.max(entry.getKey().getValue(),res);\n }\n return res;\n }\n}\n```\n# KINDLY UPVOTE!!! \uD83D\uDE0A
2
0
['Hash Table', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
Keeping Top 3 Lengths in a Static Array. O(N). No Vectors. C++ 0 ms, Java 1 ms. Beating 100%.
keeping-top-3-lengths-in-a-static-array-qegkj
Intuition\n\nActually this task has been first solved using a prefix tree-based square-complexity algorithm to count substrings. That solution was too generic a
sergei99
NORMAL
2023-12-31T12:42:29.421900+00:00
2024-12-10T02:51:40.185761+00:00
263
false
# Intuition\n\nActually this task has been first solved using a prefix tree-based square-complexity algorithm to count substrings. That solution was too generic and too slow (21 ms vs top 4 ms at the moment). So we have adapted the linear solution here.\n\nAll the background can be found in [the solution to the second version of this task](https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-ii/solutions/4483094/keeping-top-3-lengths-in-a-static-array-o-n-no-vectors-c-71-ms-java-22-ms-beating-100/), except that the input string may not exceed 50 characters.\n\n# Approach\n\nSimilarly to the version two algorithm, we count string lengths in a statically allocated array, only we are using byte-size counters instead of a 32-bit integer. The rest of code is exactly same except some type casts applied/removed and STL `max` type parameter is specified explicitly to counter the arithmetic expression type promotion.\n\n# Complexity\n- Time complexity: $O(N \\times M^2 + A \\times M)$\n- Space complexity: $O(A \\times M)$\n where $N$ is the string length, $A$ is the alphabet size ($26$ in our case), and $M$ is the number of substring occurrences to consider ($3$ in our case).\n\n# Micro-optimizations\n\nExactly same as in [the solution to the second version of this task](https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-ii/solutions/4483094/keeping-top-3-lengths-in-a-static-array-o-n-no-vectors-c-71-ms-java-22-ms-beating-100/).\n\n# Measurements\n\nSince the measurement system has changed recently, updating record and publishing new measurements.\n\n## Dec 31, 2023\n\n| Language | Algorithm | Time | Beating | Memory | Beating | Submission |\n|-|-|-|-|-|-|-|\n| C++ | Linear | 0 ms | 100% | 6.7 Mb | 100% | https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1133009319/ |\n| C++ | Trie-based Quadratic | 21 ms | 20% | 14.7 Mb | 20% | https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1132690584/ |\n| Java | Linear | 2 ms | 99.13% | 41.8 Mb | 100% | https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1133015808/ |\n| Scala | Linear | 818 ms | 100% | 55.18 Mb | 100% | https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1133018417/ |\n\n(Scala has not enough submissions, as usually, so everything is rated 100%)\n\n## Dec 10, 2024\n\n| Language | Algorithm | Time | Beating | Memory | Beating | Submission |\n|-|-|-|-|-|-|-|\n| Java | Linear | 1 ms | 100% | 42.07 Mb | 98.88% | https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1474827611 |\n| Scala | Linear | 34 ms | 100% | 57.47 Mb | 100% | https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-i/submissions/1474835143 |\n\n# Code\n``` C++ []\nclass Solution {\nprivate:\n static uint8_t lens[26][3];\n\npublic:\n static int maximumLength(const string &s) {\n const char *const sc = s.c_str();\n const uint8_t n = s.length();\n uint8_t start = 0;\n char last = *sc;\n for (uint8_t i = 1; i < n; i++) {\n const char c = sc[i];\n if (c != last) {\n uint8_t len = i - start;\n auto entry = lens[last-\'a\'];\n if (len > entry[0]) swap(len, entry[0]);\n if (len > entry[1]) swap(len, entry[1]);\n if (len > entry[2]) swap(len, entry[2]);\n start = i;\n last = c;\n }\n }\n {\n uint8_t len = n - start;\n auto entry = lens[last-\'a\'];\n if (len > entry[0]) swap(len, entry[0]);\n if (len > entry[1]) swap(len, entry[1]);\n if (len > entry[2]) swap(len, entry[2]);\n }\n uint8_t maxlen = 0;\n for (auto entry : lens) {\n if (!entry[0]) continue;\n const uint8_t len = entry[1] == entry[0]\n ? entry[0] - (entry[2] < entry[0])\n : max<uint8_t>(entry[1] + 2u, entry[0]) - 2u;\n maxlen = max<uint8_t>(maxlen, len);\n entry[0] = entry[1] = entry[2] = 0;\n }\n return maxlen ? maxlen : -1;\n }\n};\n\nuint8_t Solution::lens[26][3];\n```\n``` Java []\nclass Solution {\n private static final byte[] lens = new byte[26 * 3];\n\n public static int maximumLength(final String s) {\n final byte n = (byte)s.length();\n byte start = 0;\n char last = s.charAt(0);\n for (byte i = 1; i < n; i++) {\n final char c = s.charAt(i);\n if (c != last) {\n byte len = (byte)(i - start);\n final byte b = (byte)((last - \'a\') * 3);\n if (len > lens[b]) {\n final byte t = lens[b];\n lens[b] = len;\n len = t;\n }\n if (len > lens[b + 1]) {\n final byte t = lens[b + 1];\n lens[b + 1] = len;\n len = t;\n }\n if (len > lens[b + 2])\n lens[b + 2] = len;\n start = i;\n last = c;\n }\n }\n {\n byte len = (byte)(n - start);\n final byte b = (byte)((last - \'a\') * 3);\n if (len > lens[b]) {\n final byte t = lens[b];\n lens[b] = len;\n len = t;\n }\n if (len > lens[b + 1]) {\n final byte t = lens[b + 1];\n lens[b + 1] = len;\n len = t;\n }\n if (len > lens[b + 2])\n lens[b + 2] = len;\n }\n byte maxlen = 0;\n for (int j = 0; j < 78; j += 3) {\n if (lens[j] != 0) {\n final byte len = (byte)(lens[j+1] == lens[j]\n ? lens[j] - (lens[j+2] < lens[j] ? 1 : 0)\n : lens[j+1] > lens[j] - 2 ? lens[j+1] : lens[j] - 2);\n if (maxlen < len) maxlen = len;\n lens[j] = lens[j+1] = lens[j+2] = 0;\n }\n }\n return maxlen > 0 ? maxlen : -1;\n }\n}\n```\n``` Scala []\nobject Solution {\n private[this] val lens = Array.fill[Byte](26 * 3)(0)\n\n def maximumLength(s: String): Int = {\n val n = s.length\n var start = 0\n var last = s(0)\n for (i <- (1 until n)) {\n val c = s(i)\n if (c != last) {\n var len = (i - start).toByte\n val b = (last - \'a\') * 3\n if (len > lens(b)) {\n val t = lens(b)\n lens(b) = len\n len = t\n }\n if (len > lens(b + 1)) {\n val t = lens(b + 1)\n lens(b + 1) = len\n len = t\n }\n if (len > lens(b + 2))\n lens(b + 2) = len\n start = i\n last = c\n }\n }\n {\n var len = (n - start).toByte\n val b = (last - \'a\') * 3\n if (len > lens(b)) {\n val t = lens(b)\n lens(b) = len\n len = t\n }\n if (len > lens(b + 1)) {\n val t = lens(b + 1)\n lens(b + 1) = len\n len = t\n }\n if (len > lens(b + 2))\n lens(b + 2) = len\n }\n var maxlen: Byte = 0\n for (j <- (0 until 78 by 3)) {\n if (lens(j) != 0) {\n val len = (if (lens(j+1) == lens(j))\n lens(j) - (if (lens(j+2) < lens(j)) 1 else 0)\n else\n if (lens(j+1) > lens(j) - 2) lens(j+1) else lens(j) - 2).toByte\n if (maxlen < len) maxlen = len\n lens(j) = 0\n lens(j+1) = 0\n lens(j+2) = 0\n }\n }\n if (maxlen > 0) maxlen else -1\n }\n}\n```
2
1
['Array', 'String', 'Sorting', 'Counting', 'C++', 'Java', 'Scala']
3
find-longest-special-substring-that-occurs-thrice-i
ON^3 - Brute Force + Explanation
on3-brute-force-explanation-by-biggesto-85pu
Intuition\nCreate dictionary that holds all possible special single characters. While iterating through the string, keep count of how many times any special sin
biggesto
NORMAL
2023-12-31T08:57:12.308084+00:00
2024-06-15T15:30:11.193132+00:00
317
false
# Intuition\nCreate dictionary that holds all possible special single characters. While iterating through the string, keep count of how many times any special single characters appear. \n\n# Approach\nCreate a dictionary and set return value of -1 initially. \n\nIterate through the string with a nested for loop to go through all sequential possbilities.\n\nUse set to remove repeats for each substring, if lenth == 1 then we know it is special.\n\nStore any special substrings into the dictionary with value of 1 initially, if it is already in dictionary, increment value by 1.\n\nHave a if condition to check if value is larger or equal to 3. If it is, use max() to store the larger value as new return value.\n\nOnce string has been fully read, return the res\n\n# Complexity\n- Time complexity:\nON^3\n\n- Space complexity:\nNot sure XD\n\n# Code\n```\nclass Solution(object):\n def maximumLength(self, s):\n """\n :type s: str\n :rtype: int\n """\n h = {}\n res = -1\n\n for i in range(len(s)):\n for j in range(i + 1, len(s) + 1):\n if len(set(s[i:j])) == 1:\n if s[i:j] not in h:\n h[s[i:j]] = 1\n else:\n h[s[i:j]] += 1\n if h[s[i:j]] >= 3:\n res = max(res, len(s[i:j]))\n return res\n```
2
0
['Python', 'Python3']
1
find-longest-special-substring-that-occurs-thrice-i
✅ C++ | Brute Force | Map
c-brute-force-map-by-harshadkhandare9000-1u60
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
harshadkhandare9000
NORMAL
2023-12-31T06:50:29.101963+00:00
2023-12-31T06:50:29.101983+00:00
154
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n int maximumLength(string s) {\n unordered_map<string,int>mp;\n\n for(int i = 0 ; i < s.length(); i++){\n string temp = "";\n temp += s[i];\n mp[temp]++;\n for(int j = i+1 ; j < s.length() ; j++){\n if(s[i] == s[j]){\n temp += s[j];\n mp[temp]++;\n }\n else{\n break;\n }\n \n \n }\n }\n\n int size = INT_MIN;\n for(auto it : mp){\n if(it.second >= 3 ){\n int val = it.first.size();\n size = max(val,size);\n }\n }\n\n return size == INT_MIN ? -1 : size;\n }\n};\n```
2
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
C++ SIMPLE AND OPTIMAL SOLUTION FOR BEGNNERS USING HASHMAP :)
c-simple-and-optimal-solution-for-begnne-flon
Intuition\n Describe your first thoughts on how to solve this problem. \nFIND FREQ AND MAKE A COUNT FOR THE NO. OF TIMES THAT FREQ CAME FOR EVERY CHAR\nTHEN CAL
Dhiraj_Mohata
NORMAL
2023-12-31T05:07:53.338903+00:00
2023-12-31T05:07:53.338929+00:00
161
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFIND FREQ AND MAKE A COUNT FOR THE NO. OF TIMES THAT FREQ CAME FOR EVERY CHAR\nTHEN CALCUALATE THE ANS BY MAX BY THIS STEPS FOR ALL FREQ:\na) FREQ - 2;\nb) CHECK IF WE HAVE GEATER FREQ AVALABLE OR NOT\nc) IF WE HAVE SAME FREQ 2 TIMES THEN WE CAN MAKE FREQ - 1 3 TIMES\nd) IF WE HAVE SAME FREQ 3 OR MORE TIMES WE CAN TAKE FREQ\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFIND FREQ AND MAKE A COUNT FOR THE NO. OF TIMES THAT FREQ CAME FOR EVERY CHAR\nTHEN CALCUALATE THE ANS BY MAX BY THIS STEPS FOR ALL FREQ:\na) FREQ - 2;\nb) CHECK IF WE HAVE GEATER FREQ AVALABLE OR NOT\nc) IF WE HAVE SAME FREQ 2 TIMES THEN WE CAN MAKE FREQ - 1 3 TIMES\nd) IF WE HAVE SAME FREQ 3 OR MORE TIMES WE CAN TAKE FREQ\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumLength(string s) \n {\n map<char , map<int,int>> m;\n vector<int> v(26,0);\n \n char c = s[0];\n int x = 0;\n for(int i=0; i<s.size(); i++)\n {\n if(s[i] == c)\n {\n x++;\n }\n else\n {\n m[c][x]++;\n c = s[i];\n x = 1;\n }\n }\n m[c][x]++;\n\n \n int ans = 0;\n \n for(auto [key,val] : m)\n {\n int x = 0;\n for(auto [key1 , val1] : val)\n {\n ans = max(ans , key1-2);\n if(val.size()-1 > x)\n ans = max(ans , key1);\n if(val1 == 2)\n ans = max(ans , key1 - 1);\n if(val1 >= 3)\n ans = max(ans , key1);\n x++;\n }\n \n }\n \n if(ans == 0)\n return -1;\n return ans;\n }\n};\n```
2
0
['Hash Table', 'Greedy', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Brute Force || check for each substring
brute-force-check-for-each-substring-by-7gopj
Code\n\nclass Solution {\npublic:\n bool same(string s){\n sort(s.begin(), s.end());\n return s[0]==s.back();\n }\n bool has(string &s, i
calm_porcupine
NORMAL
2023-12-31T04:02:09.198481+00:00
2023-12-31T04:02:09.198509+00:00
570
false
# Code\n```\nclass Solution {\npublic:\n bool same(string s){\n sort(s.begin(), s.end());\n return s[0]==s.back();\n }\n bool has(string &s, int n){\n unordered_map<string, int>mp;\n for(int i = 0;i+n<=s.length();i++){\n string aux = s.substr(i, n);\n if(same(aux))\n mp[aux]++;\n if(mp[aux]>=3)\n return true;\n }\n return false;\n }\n int maximumLength(string s) {\n int n = s.length();\n int ans = -1;\n for(int i = 1;i<n;i++){\n if(has(s, i))\n ans = i;\n }\n return ans;\n }\n};\n```
2
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Brute Force Trying all the sub-strings
brute-force-trying-all-the-sub-strings-b-j0li
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
Minato_10
NORMAL
2023-12-31T04:01:50.062294+00:00
2023-12-31T04:01:50.062319+00:00
321
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 private:\n bool ok(string s){\n int n = s.size();\n if(n<=0) return false;\n char ch = s[0];\n for(auto it: s){\n if(it!=ch) return false;\n }\n return true;\n }\npublic:\n int maximumLength(string s) {\n map<string,int> mp;\n int n = s.size();\n for(int i=0;i<n;i++){\n for(int j=1;j<=n-i;j++){\n mp[s.substr(i,j)]++;\n \n }\n }\n int maxi = -1;\n for(auto & it: mp){\n if(it.second>=3){\n if(ok(it.first))\n maxi = max(maxi,(int)(it.first.size()));\n }\n }\n if(maxi == 0) return -1;\n return maxi;\n }\n};\n```
2
0
['Ordered Map', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Easy HashMap solution | Java
easy-hashmap-solution-java-by-hee_maan_s-nakt
IntuitionApproachComplexity Time complexity: Space complexity: Code
hee_maan_shee
NORMAL
2025-01-19T08:24:33.240906+00:00
2025-01-19T08:24:33.240906+00:00
31
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maximumLength(String s) { int n = s.length(); List<int[]> groups = new ArrayList<>(); // Stores (char, length) //Grouping consecutive characters int i = 0; while (i < n) { char c = s.charAt(i); int start = i; while (i < n && s.charAt(i) == c) { i++; } groups.add(new int[]{c, i - start}); } //Counting occurrences of different lengths for each character Map<Character, Map<Integer, Integer>> lengthCount = new HashMap<>(); for (int[] group : groups) { char c = (char) group[0]; int length = group[1]; lengthCount.putIfAbsent(c, new HashMap<>()); // Counting all possible special substrings of different lengths for (int l = 1; l <= length; l++) { lengthCount.get(c).put(l, lengthCount.get(c).getOrDefault(l, 0) + (length - l + 1)); } } int maxLength = -1; for (char c : lengthCount.keySet()) { for (int length : lengthCount.get(c).keySet()) { if (lengthCount.get(c).get(length) >= 3) { maxLength = Math.max(maxLength, length); } } } return maxLength; } } ```
1
0
['Hash Table', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
Well Explained & Optimal Solution even for higher constraint like leetcode 2982 || Runs 0ms
well-explained-optimal-solution-even-for-vddo
This Solution can also work fine on Leetcode 2982Find Longest Special Substring That Occurs Thrice II: https://leetcode.com/problems/find-longest-special-substr
Harsh-X
NORMAL
2025-01-10T01:36:49.248239+00:00
2025-01-10T01:36:49.248239+00:00
30
false
![image.png](https://assets.leetcode.com/users/images/42c957d8-3d63-46fd-bf1e-878894dfe6a1_1736472209.7965877.png) ##### This Solution can also work fine on Leetcode 2982 **Find Longest Special Substring That Occurs Thrice II**: [https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-ii/description/]() **My Solution for that Problem:** [https://leetcode.com/problems/find-longest-special-substring-that-occurs-thrice-ii/solutions/6257686/well-explained-optimal-solution-with-som-xfi7/]() # Approach <!-- Describe your approach to solving the problem. --> - We group the length of each character like: a = [0, 4, 3, 2, 1] so, it means at [4] we have count 1 means "aaaa" appears 1 time, "aaa" 2 times, "aa" 3 times, "a" 4 times - And we can see that is cummulative sum because while traversing string we will have array look like : **[0, 1, 1, 1, 1]**. - So, we start making sum from back because "aaaa" have "aaa" as well so our array becomes [0, 4, 3, 2, 1] and soon as we get **[j] >= 3 we take that j because that shows the longest length for that character** # Complexity - Time complexity: **O(26*N)** <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: **O(26*N)** <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] #pragma GCC optimize("O3,unroll-loops,Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") static const auto harsh = []() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }(); #define LC_HACK #ifdef LC_HACK const auto __ = []() { struct ___ { static void _() { std::ofstream("display_runtime.txt") << 0 << '\n'; } }; std::atexit(&___::_); return 0; }(); #endif class Solution { public: int maximumLength(string s) { int n = s.length(); int maxlen = -1; vector<vector<int>> alpha(26, vector<int>(n+1, 0)); alpha[s[0]-'a'][1]++; int len = 1; for(int i = 1; i<n; i++){ if(s[i] == s[i-1]){ len++; } else{ len = 1; } alpha[s[i]-'a'][len]++; } for(int i = 0; i<26; i++){ int sum = 0; // To get the count of each length of [i] we maintain cummulative sum from last for(int j = n; j>=0; j--){ sum += alpha[i][j]; if(sum >= 3){ maxlen = max(maxlen, j); break; } } } return maxlen == 0 ? -1 : maxlen; } }; ```
1
0
['Array', 'String', 'Counting', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Easy Python Solution (easy to understand)
easy-python-solution-easy-to-understand-b0r9k
```\nclass Solution:\n def maximumLength(self, s: str) -> int:\n hsh={}\n for i in range(len(s)):\n for j in range(i+1,len(s)+1):\n
gokulram2221
NORMAL
2024-12-10T12:30:47.266904+00:00
2024-12-10T12:30:47.266948+00:00
31
false
```\nclass Solution:\n def maximumLength(self, s: str) -> int:\n hsh={}\n for i in range(len(s)):\n for j in range(i+1,len(s)+1):\n if s[i:j] in hsh.keys() :\n hsh[s[i:j]]+=1\n else:\n hsh[s[i:j]]=1\n mx=-1\n res=[]\n for i in hsh.keys():\n if hsh[i]>=3 and len(i)>mx and len(set(i))==1:\n res.append(i)\n mx=len(i)\n return(mx)
1
0
[]
1
find-longest-special-substring-that-occurs-thrice-i
Simple Solution | Sliding window | 94% Beats in Memory | C++
simple-solution-sliding-window-94-beats-0i7tw
Self explanatory code:\n\n\nclass Solution {\npublic:\n \n int maximumLength(string s) \n {\n int n = s.size();\n int ans = -1;\n
tirth_rami
NORMAL
2024-12-10T05:50:40.370532+00:00
2024-12-10T05:50:40.370573+00:00
12
false
Self explanatory code:\n\n```\nclass Solution {\npublic:\n \n int maximumLength(string s) \n {\n int n = s.size();\n int ans = -1;\n int i=0, j= 0;\n while(j < n)\n {\n // take substring from i to j\n string ola = s.substr(i,j-i+1);\n int cnt = 0;\n // count its occurrences in the whole string\n for(int i=ola.size()-1;i<n;i++)\n {\n string curr = s.substr(i-ola.size()+1, ola.size());\n if(curr == ola)\n {\n cnt++;\n }\n }\n // if count >= 3 then maximize our answer with length of current string\n if(cnt >= 3)\n {\n ans = max(ans,(int)ola.size());\n }\n // if next char is equal to current char then we could take it as a special string\n if(j+1 < n && s[j] == s[j+1])\n {\n j++;\n }\n // otherwise we need to find new string from next index\n else\n {\n i = j+1;\n j++;\n }\n }\n return ans;\n }\n};\n```
1
0
['C', 'Sliding Window']
0
find-longest-special-substring-that-occurs-thrice-i
Not that fast, but simple to understand with Priority Queue
not-that-fast-but-simple-to-understand-w-x3qg
null
wildclown
NORMAL
2024-12-10T22:03:25.832027+00:00
2024-12-10T22:03:25.832027+00:00
15
false
# \uD83D\uDE80 Intuition\n### After a while trying to understand the problem, saw that in order to get certain letter value, there was a pattern... Now I was only in need of how to find its max... To find it I used a\n\n# \uD83E\uDDE0 Approach\n#### Two pointers with Max Priority Queue! Would place the letters windows in a priority queue, and while I don\'t have a letter that has 3 numbers, I will continue getting my letters... the stop condition may be optimized, let me know in comments if you were able!\n\n# \uD83D\uDCCA Complexity\n## Time complexity:\n- Slidding Window\n - O(N)\n- Priority Queue\n - We will have at most N items, but PQ inserts in logN, so here we have O(NLogN)\n\n## Space complexity:\n- We have to store at most N items in our Priority Queue, also we have a sort of array of letters... But this array won\'t be bigger than N, so we have O(N) as space complexity\n\n# Code\n```javascript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar maximumLength = function(s) {\n let explodedAlphabet = explodeStringWithPriority(s);\n let answer = -1;\n for(let i = 0; i< explodedAlphabet.length; i++){\n let results = [\n getSize1Result(explodedAlphabet[i]),\n getSize2Result(explodedAlphabet[i]),\n getSize3Result(explodedAlphabet[i])\n ];\n\n answer = Math.max(answer,...results)\n }\n\n return answer;\n};\n\nfunction getSize1Result(item){\n //console.log(`In size 1 ${item} and ${item[0]}`)\n if(item[0] < 3) {\n return -1;\n }\n\n return item[0]-2;\n}\n\nfunction getSize2Result(item){\n //console.log(`In size 2 ${item}`)\n if(item.length < 2) return -1;\n if(item[0] == 1 && item[1] == 1) return -1;\n\n return Math.min(item[0] -1, item[1]);\n\n}\n\nfunction getSize3Result(item){\n //console.log(`In size 3 ${item}`)\n if(item.length < 3) return -1;\n\n return Math.min(...item)\n}\n\nfunction explodeStringWithPriority(s){\n let alphabet = new Array(26);\n for(let i = 0; i< 26; i++) alphabet[i] = [];\n\n let priorityQueue = new PriorityQueue({\n compare: (a,b) => {\n return b[0] - a[0]\n }\n })\n\n let i = 0;\n while(i<s.length){\n let nextPointer = i;\n\n while(s[i] == s[nextPointer] && nextPointer < s.length){\n nextPointer++;\n }\n\n priorityQueue.enqueue([nextPointer - i, i])\n i = nextPointer\n }\n\n while(priorityQueue.size() > 0){\n let [val, pos] = priorityQueue.dequeue();\n let stringPos = s.charCodeAt(pos) - \'a\'.charCodeAt(0)\n alphabet[stringPos].push(val)\n if(alphabet[stringPos].length == 3) break;\n }\n\n return alphabet.filter((a) => {return a.length > 0 });\n}\n```
1
0
['Sliding Window', 'Heap (Priority Queue)', 'JavaScript']
0
find-longest-special-substring-that-occurs-thrice-i
🚀✅Optimize Solution✅ || ✅beats 100% in both TC and SC✅🚀💯
optimize-solution-beats-100-in-both-tc-a-ibnr
null
R_Patel_007
NORMAL
2024-12-10T19:28:39.567750+00:00
2024-12-10T19:28:39.567750+00:00
7
false
# \uD83E\uDDE0 Intuition \nWhen solving this problem, the idea is to find the **maximum length of substrings** that satisfy a specific condition using **binary search** and **bit manipulation**. We\u2019ll use a sliding window and a frequency map to track substrings dynamically. \uD83D\uDE80 \n\n---\n\n# \uD83D\uDD0D Approach \n1. **Binary Search on Length**: \n We\'ll try to maximize the length of the substring by using binary search between `1` and `size - 2`. \n\n2. **Check Feasibility (pos)**: \n - Use a sliding window approach and a **bitset** to track the frequency of characters. \n - If the substring contains **only one unique character** and repeats at least three times, then it satisfies the condition. \n\n3. **Return the Result**: \n If a valid substring of length `mid` is found, update the maximum length and continue searching. \n\n---\n\n# \uD83D\uDD22 Complexity \n- **Time Complexity**: \n $$O(n \\cdot \\log(n))$$ \n Binary search on the length requires $$\\log(n)$$ iterations, and each iteration uses $$O(n)$$ sliding window traversal. \n\n- **Space Complexity**: \n $$O(1)$$ for bitset and frequency vector. \n $$O(n)$$ in worst case for unordered_map.\n\n---\n\n# \uD83E\uDDD1\u200D\uD83D\uDCBB Code \n\n```cpp\nclass Solution {\npublic:\n\n // \uD83E\uDDE9 Helper Function: Check feasibility for a given size\n bool pos(int size, string &s) {\n unordered_map<bitset<26>, int> mp; // \uD83D\uDD10 Tracks substrings\n bitset<26> fr; // \uD83D\uDCCA Tracks unique chars\n vector<int> frr(26, 0); // \uD83D\uDD22 Frequency array\n fr.reset(); // \uD83D\uDD04 Reset bitset\n int l = 0, r = 0;\n\n // \uD83C\uDF1F Initial sliding window of \'size\'\n for (r; r < size; r++) {\n frr[s[r] - \'a\']++;\n fr[s[r] - \'a\'] = 1; // Update bitset\n }\n if (fr.count() == 1) mp[fr]++; // \u2705 Check unique char condition\n\n // \uD83C\uDFC3 Sliding the window across the string\n for (r; r < s.size(); r++, l++) {\n frr[s[l] - \'a\']--; // \uD83D\uDD04 Shrink window\n fr[s[l] - \'a\'] = (frr[s[l] - \'a\'] >= 1); // Update bitset\n frr[s[r] - \'a\']++; // Expand window\n fr[s[r] - \'a\'] = 1; // Update bitset\n \n // \u2705 Check condition\n if (fr.count() == 1) {\n mp[fr]++;\n if (mp[fr] >= 3) return true; \n }\n }\n return false;\n }\n\n int maximumLength(string s) {\n int ans = -1;\n int l = 1, r = s.size() - 2;\n\n while (l <= r) {\n int mid = l + (r - l) / 2; \n if (pos(mid, s)) { \n l = mid + 1; \n ans = mid;\n } else {\n r = mid - 1; \n }\n }\n return ans;\n }\n};\n\nauto init = []() {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return 0;\n}();\n```\n\n---\n\n# \uD83D\uDD25 Highlights \n- **Binary Search + Sliding Window** = \uD83D\uDCA1 Optimal solution. \n- **Bit Manipulation** = \uD83C\uDFAF Efficient character tracking. \n- **Compact and Elegant Implementation** = \u26A1 High performance. \n\n---\n\nHope you find this explanation fun and engaging! Let me know if you need more help! \uD83D\uDE0A
0
0
['Hash Table', 'String', 'Binary Search', 'Sliding Window', 'Counting', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Easy Code and very Simple , you can say brute Force
easy-code-and-very-simple-you-can-say-br-yq2t
null
AtithiShekhar1
NORMAL
2024-12-10T11:28:21.859911+00:00
2024-12-10T11:28:21.859911+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe time and space are not good but the code is simple and easy to unserstand \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ni created 3 functions , one is main function provided by leetcode which will check if string is special and also count the overlapping characters and return the maxlength, second is function to check s string is special or not by traversing in the array of characters and third is to count the overlapping characters by traversing a pointer in string length - sub length\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^3)\nwhere n is the length of the string \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\nfor storing substrings and auxiliary variables\n\n# Code\n```java []\nclass Solution {\n public int maximumLength(String s) {\n int maxLength = -1;\n for (int i = 0; i < s.length(); i++) {\n for (int j = i + 1; j <= s.length(); j++) {\n String sub = s.substring(i, j);\n if (isSpecial(sub)) {\n int occurrences = countOverlappingOccurrences(s, sub);\n if (occurrences >= 3) {\n maxLength = Math.max(maxLength, sub.length());\n }\n }\n }\n }\n return maxLength;\n }\n\n private boolean isSpecial(String str) {\n char firstChar = str.charAt(0);\n for (char c : str.toCharArray()) {\n if (c != firstChar) {\n return false;\n }\n }\n return true;\n }\n\n private int countOverlappingOccurrences(String s, String sub) {\n int count = 0;\n for (int i = 0; i <= s.length() - sub.length(); i++) {\n if (s.substring(i, i + sub.length()).equals(sub)) {\n count++;\n }\n }\n return count;\n }\n}\n\n```
1
0
['Java']
0
find-longest-special-substring-that-occurs-thrice-i
Simple Readable | Linear Time O(N) | Constant O(1) space | PQ
simple-readable-linear-time-on-constant-satkn
null
Apakg
NORMAL
2024-12-10T11:13:55.686264+00:00
2024-12-10T11:13:55.686264+00:00
18
false
# Code\n```java []\nclass Solution {\n public int maximumLength(String s) {\n PriorityQueue<Integer>[] all = new PriorityQueue[26];\n for (int i = 0; i < 26; i++) {\n all[i] = new PriorityQueue<>();\n }\n\n char last = \'?\';\n int n = 0;\n for (char ch : s.toCharArray()) {\n if (last == ch) {\n ++n;\n } \n else {\n n = 1;\n last = ch;\n }\n int idx = ch - \'a\';\n all[idx].add(n);\n\n if (all[idx].size() > 3) {\n all[idx].poll(); // remove the smallest element.\n }\n }\n\n int res = -1;\n for (PriorityQueue<Integer> pq : all) {\n if (pq.size() == 3) {\n res = Math.max(res, pq.peek()); // Get smallest ele from PQ.\n }\n }\n\n return res;\n }\n /**\n private boolean isSpecialString(String s){\n if(s.length() == 1) return true;\n int bitMaskAcc = 0;\n for (char ch : s.toLowerCase().toCharArray()) {\n if (ch >= \'a\' && ch <= \'z\') {\n int bit = 1 << (ch - \'a\'); // unique bit for each letter\n if ((bitMaskAcc & bit) == 1) { // Check if the bit is already set\n return true; // Found duplicate letter\n }\n bitMaskAcc ^= bit; \n }\n }\n\n return false;\n }\n */\n \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)$$ -->
1
0
['Array', 'Heap (Priority Queue)', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
best code in java
best-code-in-java-by-notaditya09-2ha8
null
NotAditya09
NORMAL
2024-12-10T09:07:09.862643+00:00
2024-12-10T09:07:09.862643+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```java []\nclass Solution {\n public int maximumLength(String s) {\n final int n = s.length();\n int ans = -1;\n int runningLen = 0;\n char prevLetter = \'@\';\n // counts[i][j] := the frequency of (\'a\' + i) repeating j times\n int[][] counts = new int[26][n + 1];\n\n for (final char c : s.toCharArray())\n if (c == prevLetter) {\n ++counts[c - \'a\'][++runningLen];\n } else {\n runningLen = 1;\n ++counts[c - \'a\'][runningLen];\n prevLetter = c;\n }\n\n for (int[] count : counts) {\n ans = Math.max(ans, getMaxFreq(count, n));\n }\n\n return ans;\n }\n\n // Returns the maximum frequency that occurs more than three times.\n private int getMaxFreq(int[] count, int maxFreq) {\n int times = 0;\n for (int freq = maxFreq; freq >= 1; --freq) {\n times += count[freq];\n if (times >= 3)\n return freq;\n }\n return -1;\n }\n}\n```
1
0
['Java']
0
find-longest-special-substring-that-occurs-thrice-i
Easiest Python Solution
easiest-python-solution-by-sumittripathi-z1bc
null
sumittripathi004
NORMAL
2024-12-10T08:43:05.479136+00:00
2024-12-10T08:43:05.479136+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $O(N^2)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(N^2)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n # Dictionary to store frequency of special substrings\n substring_count = {}\n\n # Generate all special substrings and get their counts\n for i in range(len(s)):\n char = s[i]\n length = 1\n while i + length <= len(s) and s[i:i + length] == char * length:\n substring = s[i:i + length]\n substring_count[substring] = substring_count.get(substring, 0) + 1\n length += 1\n\n # Find the longest substring that occurs at least 3 times\n max_length = -1\n for substring, count in substring_count.items():\n if count >= 3:\n max_length = max(max_length, len(substring))\n\n return max_length\n\n```
1
0
['Hash Table', 'String', 'Counting', 'Python3']
0
find-longest-special-substring-that-occurs-thrice-i
easy to understand simple brute force not sliding window
easy-to-understand-simple-brute-force-no-4w8c
null
codedominator7
NORMAL
2024-12-10T06:53:25.104854+00:00
2024-12-10T06:53:25.104854+00:00
113
false
# Intuition\nbrute forse will work try to simulate the question you can generate all possible substring to solve it \n\n# Approach\n1)you will generate all possible substring\n2)iterate in map and check if the subtring count is greater than 3\n3)if yes then check if special \n4)store its lenght in ans variable\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool check(string s){\n for(int i=1;i<s.size();i++){\n if(s[i-1]!=s[i]) return 0;\n }\n return 1;\n }\n int maximumLength(string s) {\n unordered_map<string ,int> m;\n for(int i=0;i<s.size();i++){\n for(int j=i;j<s.size();j++){\n m[s.substr(i,j-i+1)]++;\n }\n }\n int ans=0;\n for(auto x : m){\n if(x.second>=3&&check(x.first)){\n ans=max(ans,(int)x.first.size());\n }\n }\n return (!ans)?-1:ans;\n }\n};\n```
1
0
['Hash Table', 'String', 'Simulation', 'Counting', 'C++']
7
find-longest-special-substring-that-occurs-thrice-i
Simple Solution | Using HashMap | Java ✅✅
simple-solution-using-hashmap-java-by-ab-3kok
null
abhinavtilwar1501
NORMAL
2024-12-10T06:49:45.375701+00:00
2024-12-10T06:49:45.375701+00:00
20
false
\n# Complexity\n- Time complexity: $$O(n^2)$$ \n\n- Space complexity: $$O(m)$$ $$m$$ $$is$$ $$the$$ $$size$$ $$of$$ $$hashtable$$\n\n# Code\n```java []\nclass Solution {\n public int maximumLength(String s) {\n int max = -1;\n HashMap<String,Integer> map=new HashMap();\n int[] freq=new int[26];\n for(int i=0;i<s.length();i++){\n freq[s.charAt(i)-\'a\']++;\n }\n for(int i=0;i<s.length();i++){\n for(int j=i;j<s.length();j++){\n char ch=s.charAt(i);\n if(s.charAt(j)!=ch) break;\n map.put(s.substring(i,j+1),map.getOrDefault(s.substring(i,j+1),0)+1);\n }\n }\n for(Map.Entry<String,Integer> entry:map.entrySet()){\n // System.out.println(entry.getKey()+" "+entry.getValue());\n if(entry.getValue()>=3){\n max=Math.max(max,entry.getKey().length());\n }\n }\n if(max==-1){\n for(int i=0;i<26;i++){\n if(freq[i]>=3) return 1;\n }\n }\n return max;\n }\n}\n\n```
1
0
['Hash Table', 'String', 'Sliding Window', 'Counting', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
C++ Sliding Window + Map Solution | O(N) - Time | O(k * N) - Space
c-sliding-window-map-solution-on-time-ok-u7q8
null
lakshyamahawar14
NORMAL
2024-12-10T06:36:13.312266+00:00
2024-12-10T06:36:13.312266+00:00
12
false
# Intuition\nNote that a special string have all of its characters same, hence we only need to consider such substrings. We can apply sliding window approach here.\n\n# Approach\nA string of length n (>= 3) will have a substring of length (n - 2) appear thrice, hence we\'ve got one of our answer and we don\'t need to worry about its substrings having length less than (n - 2). Now, the number of substrings with length (n - 1) will be 2 and length n will be 1. Store the count of these substrings in a map. After the end of iteration, just check for the substrings stored in the map and take the maximum of their length if their count is greater than or equal to 3.\n\n# Complexity\n- Time complexity:\nO(N) (use unordered_map for O(1) insertion)\n\n- Space complexity:\nO(k * N) - here k depends upon the number longest special string length (idk, just correct me if i\'m wrong);\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n int n = (int)s.length();\n map<string, int> m;\n int ans = -1;\n int i = 0;\n while (i < n) {\n int j = i + 1, cnt = 1;\n while (j < n && s[j] == s[j - 1]) {\n cnt++;\n ++j;\n }\n if (cnt >= 3) {\n ans = max(ans, cnt - 2);\n }\n m[string(cnt - 1, s[i])] += 2;\n m[string(cnt, s[i])]++;\n i = j;\n }\n for (auto& [a, x] : m) {\n int k = (int)a.length();\n if (k > 0 && x >= 3) {\n ans = max(ans, k);\n }\n }\n return ans;\n }\n};\n```
1
0
['Ordered Map', 'Sliding Window', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
Simple and Easy to Understand HashMap Solution || With Explanation || Clean Code
simple-and-easy-to-understand-hashmap-so-43ig
null
dhruvdangi03
NORMAL
2024-12-10T06:16:30.391652+00:00
2024-12-10T06:16:30.391652+00:00
4
false
\n\n# Code\n```java []\nclass Solution {\n public int maximumLength(String s) {\n // First create a HashMap\n HashMap<String, Integer> freq = new HashMap<>();\n\n // Then loop through the String \n for(int i = 0; i < s.length(); i++){\n // Store the current character\n char ch = s.charAt(i);\n for(int j = i +1; j <= s.length(); j++){\n // Now compare the stored character with the character at "j -1" index \n // Since we need to find Longest Special Substring \n // A Special Substring according to this problem is the one which is made up of only a single character\n // If the characters are not equal then just break the loop\n if(ch != s.charAt(j -1)) break;\n\n // If they are equal then save the substring in the freq map and increase the frequency \n String temp = s.substring(i, j);\n freq.put(temp, freq.getOrDefault(temp, 0) +1);\n }\n }\n // Now make a variable to store the answer\n // Put -1 in it for the cases where there is no special substring occuring three or more times\n int ans = -1;\n\n // Now loop through the HashMap\n for (Map.Entry<String, Integer> entry : freq.entrySet()){\n // Check if the frequency is Greater then or equal to 3\n // If it is then update the ans by using Math.max function\n // To put the length of the special substring with the maximum length \n if(entry.getValue() >= 3) ans = Math.max(ans, entry.getKey().length());\n }\n\n // Now return the variable which was storing the answer\n return ans;\n }\n}\n```
1
0
['Hash Table', 'String', 'Counting', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
C++ O(26N) Solution without Binary Search
c-o26n-solution-by-retire-m2sg
null
Retire
NORMAL
2024-12-10T05:13:26.908855+00:00
2024-12-10T05:15:02.720960+00:00
18
false
# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n int n = s.size();\n vector<vector<int>> cnt(26, vector<int>(n + 1, 0));\n int l = 0, r = 0;\n while (r < n) {\n if (s[l] != s[r]) {\n cnt[s[l] - \'a\'][r - l] += 1;\n l = r;\n }\n r += 1;\n }\n cnt[s[l] - \'a\'][r - l] += 1;\n for (int j = n; j >= 1; j--) {\n for (int i = 0; i < 26; i++) {\n if (j + 1 <= n) cnt[i][j] += cnt[i][j + 1] * 2;\n if (cnt[i][j] >= 3) return j;\n }\n }\n return -1;\n }\n};\n```
1
0
['Counting', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
[C++] Simple implementation, check for every length substring occurences
c-simple-implementation-check-for-every-ew82k
null
bora_marian
NORMAL
2024-12-10T05:10:01.207335+00:00
2024-12-10T05:10:01.207335+00:00
15
false
Check every for every length the number of substring occurrences which has only 1 character. If the number of occurrences >= 3 then this length is our result.\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n int n = s.size(), res = -1;\n for (int l = 1; l <= n; l++) {\n int occur = check_length(s, l);\n if (occur >= 3) {\n res = l;\n }\n }\n return res;\n }\n int check_length(string& s, int len) {\n int sz = s.size(), res = 0;\n unordered_map<char, int>mp;\n unordered_map<char, int> charact_seq;\n for (int i = 0; i < sz; i++) {\n mp[s[i]]++;\n if (i < len - 1) {\n continue;\n }\n\n if (i >= len) {\n mp[s[i-len]]--;\n if (mp[s[i-len]] == 0) {\n mp.erase(s[i-len]);\n }\n } \n if (mp.size() == 1) {\n charact_seq[s[i]]++;\n res = max(charact_seq[s[i]], res);\n }\n } \n return res;\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
C# Solution for Find Longest Special Substring That Occurs Thrice I Problem
c-solution-for-find-longest-special-subs-dko6
null
Aman_Raj_Sinha
NORMAL
2024-12-10T04:56:17.522457+00:00
2024-12-10T04:56:17.522457+00:00
13
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to find the longest special substring (a substring made up of identical characters) that appears at least three times. Since longer substrings are harder to satisfy the condition of occurring thrice, we can use binary search on the substring length to efficiently narrow down the search space.\n\nInstead of iterating over all possible substring lengths (as in the brute-force approach), we divide the problem into smaller chunks by testing the feasibility of a specific length using hashing (rolling hash). This allows us to check substring occurrences efficiently.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tBinary Search:\n\t\u2022\tThe possible lengths of special substrings range from 1 to n (length of the string).\n\t\u2022\tUse binary search to test the middle length mid. If a substring of length mid is valid (appears at least three times), increase the search range to look for longer lengths. Otherwise, decrease the range to shorter lengths.\n\t\u2022\tContinue until the range is exhausted.\n2.\tRolling Hash:\n\t\u2022\tUse a rolling hash to efficiently calculate hash values of substrings while sliding the window. This avoids recomputing hash values from scratch.\n\t\u2022\tIf a hash value occurs multiple times, validate it using the IsSpecial helper function to ensure the substring is truly special (consists of identical characters).\n3.\tValidation:\n\t\u2022\tFor each length mid, track the hash values and their frequencies in a dictionary.\n\t\u2022\tIf any special substring of length mid occurs at least three times, mark it as valid and update the result.\n4.\tHelper Function:\n\t\u2022\tUse the IsSpecial helper function to verify whether all characters in a substring are the same.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1.\tBinary Search:\n\t\u2022\tRuns for O(log n) iterations (as we halve the range in each step).\n2.\tRolling Hash and Validation:\n\t\u2022\tFor a fixed substring length len:\n\t\u2022\tComputing the initial hash: O(len)\n\t\u2022\tSliding the window over the string: O(n - len)\n\t\u2022\tValidating each substring using IsSpecial: O(len)\n\t\u2022\tTotal work per length: O(n . len)\n3.\tOverall Complexity:\n\t\u2022\tFor all iterations of binary search: O(log n) x O(n . len) approx O(n^2 log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1.\tHash Map:\n\t\u2022\tStores at most O(n) entries for the hash values of substrings.\n2.\tAuxiliary Variables:\n\t\u2022\tRolling hash computation requires O(1) space for constants and intermediate values.\n\nOverall Space Complexity: O(n).\n\n# Code\n```csharp []\npublic class Solution {\n public int MaximumLength(string s) {\n int n = s.Length;\n int left = 1, right = n;\n int result = -1;\n\n while (left <= right) {\n int mid = (left + right) / 2;\n\n if (HasSpecialSubstringOfLength(s, mid)) {\n result = mid; \n left = mid + 1; \n } else {\n right = mid - 1; \n }\n }\n\n return result;\n }\n private bool HasSpecialSubstringOfLength(string s, int len) {\n Dictionary<long, int> hashCount = new Dictionary<long, int>();\n long hash = 0;\n long baseValue = 31; \n long mod = 1000000007; \n\n long basePower = 1;\n for (int i = 1; i < len; i++) {\n basePower = (basePower * baseValue) % mod;\n }\n\n for (int i = 0; i < len; i++) {\n hash = (hash * baseValue + (s[i] - \'a\' + 1)) % mod;\n }\n hashCount[hash] = 1;\n for (int i = len; i < s.Length; i++) {\n hash = (hash - (s[i - len] - \'a\' + 1) * basePower % mod + mod) % mod;\n hash = (hash * baseValue + (s[i] - \'a\' + 1)) % mod;\n\n if (IsSpecial(s, i - len + 1, i)) {\n if (!hashCount.ContainsKey(hash)) {\n hashCount[hash] = 0;\n }\n hashCount[hash]++;\n if (hashCount[hash] >= 3) {\n return true;\n }\n }\n }\n\n return false;\n }\n private bool IsSpecial(string s, int start, int end) {\n char firstChar = s[start];\n for (int i = start; i <= end; i++) {\n if (s[i] != firstChar) {\n return false;\n }\n }\n return true;\n }\n}\n```
1
0
['C#']
1
find-longest-special-substring-that-occurs-thrice-i
Java Solution for Find Longest Special Substring That Occurs Thrice I Problem
java-solution-for-find-longest-special-s-3m95
null
Aman_Raj_Sinha
NORMAL
2024-12-10T04:49:18.085297+00:00
2024-12-10T04:49:18.085297+00:00
57
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves finding the longest special substring that appears at least three times in a given string. A substring is considered special if all its characters are the same. The key observations are:\n1.\tFor a substring to be valid, it must consist of only one unique character (e.g., \u201Caaa\u201D, \u201Czz\u201D).\n2.\tLonger substrings are harder to find as they require the substring to occur at least three times in the original string.\n3.\tTo solve this efficiently, we can iterate through substring lengths and count their occurrences using a map, ensuring we track only special substrings.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tIterate through all substring lengths:\n\t\u2022\tStart with length len = 1 and increment up to the string\u2019s length.\n\t\u2022\tFor each length, generate all substrings of that length.\n2.\tCheck if the substring is special:\n\t\u2022\tUse the helper function isSpecial to verify if the substring consists of identical characters.\n3.\tCount occurrences of substrings:\n\t\u2022\tUse a HashMap to count the occurrences of each special substring.\n4.\tUpdate the maximum length:\n\t\u2022\tIf a special substring occurs at least three times, update the maxLength with the current substring length.\n5.\tReturn result:\n\t\u2022\tIf no valid substring is found, return -1.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe overall time complexity is O(n^3):\n1.\tOuter loop: For each possible substring length len from 1 to n, we perform the following:\n\t\u2022\tGenerate substrings: This takes O(n - len + 1) approx O(n) for each len.\n\t\u2022\tCheck if special: The isSpecial function takes O(len) for each substring.\n\t\u2022\tHashMap operations: Adding or updating a key in the map takes O(1).\nThus, the work done for each len is O(n) x O(len) = O(n . len). Summing this over all lengths 1 <= len <= n, we get:\n\nTotal work = sum_{len=1}^n O(n . len) = O(n^3)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n^2) in the worst case:\n1.\tHashMap storage: In the worst case, we store all substrings of a given length. There are O(n^2) substrings in total.\n\n# Code\n```java []\nclass Solution {\n public int maximumLength(String s) {\n int n = s.length();\n int maxLength = -1;\n\n for (int len = 1; len <= n; len++) {\n Map<String, Integer> substringCount = new HashMap<>();\n\n for (int i = 0; i <= n - len; i++) {\n String substring = s.substring(i, i + len);\n\n if (isSpecial(substring)) {\n substringCount.put(substring, substringCount.getOrDefault(substring, 0) + 1);\n if (substringCount.get(substring) >= 3) {\n maxLength = Math.max(maxLength, len);\n }\n }\n }\n }\n return maxLength;\n }\n\n private boolean isSpecial(String str) {\n char firstChar = str.charAt(0);\n for (char c : str.toCharArray()) {\n if (c != firstChar) {\n return false;\n }\n }\n return true;\n }\n}\n```
1
0
['Java']
1
find-longest-special-substring-that-occurs-thrice-i
🚀 C++ Solution 🔥Beats 100%🔥Clean Code with Intuition & Approach
c-solution-beats-100-clean-code-with-int-3bmq
null
fakhrulsojib
NORMAL
2024-12-10T04:37:48.966299+00:00
2024-12-10T04:40:31.454054+00:00
6
false
# Intuition \nThe key observation is that the answer depends on the **three longest segments** of each character. If the sizes of these segments are `x`, `y`, and `z` (with `x <= y <= z`), the result must satisfy: `answer >= min(x, y, z)`\n\n# Approach \n1. For each character, collect the sizes of its consecutive segments into an array. \n2. Sort this array to identify the three longest segments. \n3. For the three longest segments `x`, `y`, and `z` (where `x <= y <= z`): \n - The answer can be `x`, as two `x`-sized segments can always be taken from `y` and `z`. \n - For the answer to be `y`, `z` must have at least one extra character, enabling two `y`-sized segments to be formed from `z`. \n - The answer cannot be `z`, but it can be `z - 2`, as `z` can provide three segments of size `z - 2` within itself. \n\n# Complexity \n- **Time complexity:** $$O(n * log n)$$\n\n- **Space complexity:** $$O(n)$$\n\n\n# Code\n```cpp []\nint fastIO = []{ ios_base::sync_with_stdio(false); cin.tie(NULL); return 0; }();\nclass Solution {\npublic:\n int maximumLength(string s) {\n int ans = -1;\n int n = s.size();\n\n vector<int> count[26];\n\n for (int i = 1, now = 1; i < n; i++) {\n if (s[i] == s[i - 1]) {\n now++;\n } else {\n count[s[i - 1] - \'a\'].push_back(now);\n now = 1;\n }\n\n if (i == n - 1) {\n count[s[i] - \'a\'].push_back(now);\n }\n }\n\n for (int i = 0; i < 26; i++) {\n int m = count[i].size();\n \n if (m >= 2) {\n sort(count[i].begin(), count[i].end());\n } else if (m == 0) {\n continue;\n }\n\n int mx = -1;\n\n for (int j = max(0, m - 3); j < m; j++) {\n if ((j + 2 < m) || (j + 1 < m && count[i][j + 1] > count[i][j])) {\n mx = count[i][j];\n } else if (j + 1 < m) {\n mx = max(mx, count[i][j] - 1);\n } else {\n mx = max(mx, count[i][j] - 2);\n }\n }\n\n ans = max(mx, ans);\n }\n\n if (ans == 0) {\n return -1;\n }\n\n return ans;\n }\n};\n```
1
0
['Greedy', 'Counting', 'C++']
0
find-longest-special-substring-that-occurs-thrice-i
simple approach without using any complex algorithm like binarysearch ✅📈
simple-approach-without-using-any-comple-1qim
null
arikaran__r
NORMAL
2024-12-10T04:16:26.071053+00:00
2024-12-10T04:16:26.071053+00:00
5
false
# Approach\nThe goal of this code is to find the maximum length of a substring in the input string s where\n\n* The substring consists of repeated characters.\n* The substring must appear more than twice in s\n\nIf no such substring exists, it checks if there is any character that appears more than twice in s. If found, it returns 1. Otherwise, it returns -1\n\n**Initialize a Dictionary to Track Substring Counts:**\n\n* A dictionary (dic) is used to store substrings of consecutive repeating characters as keys and their frequencies as values.\n\n**1) Generate All Substrings of Repeating Characters**\n**2 ) Track the Frequency of Individual Characters**\n**3 ) Find the Maximum Length of Repeated Substrings Return Results Based on Conditions:**\n\n* If a valid substring with j > 2 is found, return its length (final).\n* If no such substring exists but a character appears more than twice (y > 2), return 1.\n* If neither condition is satisfied, return -1.\n\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N)\n# Code\n``` python []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n \n dic = defaultdict(int)\n\n for i in range(len(s)): # Generating All Substrings of Repeating Characters\n \n cur = s[i]\n temp = s[i]\n for j in range(i+1, len(s)): \n if cur == s[j]: \n temp += s[j]\n dic[temp] += 1\n else: break\n \n hash_set = defaultdict(int)\n for val in s: # Tracking the Frequency of Individual Characters\n hash_set[val] += 1\n\n final = 0\n for i,j in dic.items(): #Finding the Maximum Length of Repeated Substrings\n\n if j>2 : \n final = max(final, len(i))\n if final > 0 : return final\n for x,y in hash_set.items(): \n if y>2:\n return 1 \n return -1\n# if you like my solution please upvote \n```\n``` C++ []\n\nclass Solution {\npublic:\n int maximumLength(string s) {\n unordered_map<string, int> dic;\n\n // First loop to generate substrings\n for (int i = 0; i < s.length(); i++) {\n string cur(1, s[i]);\n string temp = cur;\n for (int j = i + 1; j < s.length(); j++) {\n if (s[j] == cur[0]) {\n temp += s[j];\n dic[temp]++;\n } else {\n break;\n }\n }\n }\n\n unordered_map<char, int> hash_set;\n for (char c : s) {\n hash_set[c]++;\n }\n\n int finalResult = 0;\n for (auto &pair : dic) {\n if (pair.second > 2) {\n finalResult = max(finalResult, (int)pair.first.length());\n }\n }\n\n if (finalResult > 0) {\n return finalResult;\n }\n\n for (auto &pair : hash_set) {\n if (pair.second > 2) {\n return 1;\n }\n }\n\n return -1;\n }\n};\n```\n```java []\nclass Solution {\n public int maximumLength(String s) {\n HashMap<String, Integer> dic = new HashMap<>();\n\n // First loop to generate substrings\n for (int i = 0; i < s.length(); i++) {\n String cur = String.valueOf(s.charAt(i));\n String temp = cur;\n for (int j = i + 1; j < s.length(); j++) {\n if (s.charAt(j) == cur.charAt(0)) {\n temp += s.charAt(j);\n dic.put(temp, dic.getOrDefault(temp, 0) + 1);\n } else {\n break;\n }\n }\n }\n\n HashMap<Character, Integer> hashSet = new HashMap<>();\n for (char c : s.toCharArray()) {\n hashSet.put(c, hashSet.getOrDefault(c, 0) + 1);\n }\n\n int finalResult = 0;\n for (String key : dic.keySet()) {\n if (dic.get(key) > 2) {\n finalResult = Math.max(finalResult, key.length());\n }\n }\n\n if (finalResult > 0) {\n return finalResult;\n }\n\n for (char key : hashSet.keySet()) {\n if (hashSet.get(key) > 2) {\n return 1;\n }\n }\n\n return -1;\n }\n}\n```
1
0
['Hash Table', 'Sliding Window', 'Counting', 'C++', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
simple approach without using any complex algorithm like binarysearch ✅📈
simple-approach-without-using-any-comple-tabg
null
arikaran__r
NORMAL
2024-12-10T03:57:17.478157+00:00
2024-12-10T03:57:17.478157+00:00
9
false
# Approach\nThe goal of this code is to find the maximum length of a substring in the input string s where\n\n* The substring consists of repeated characters.\n* The substring must appear more than twice in s\n\nIf no such substring exists, it checks if there is any character that appears more than twice in s. If found, it returns 1. Otherwise, it returns -1\n\n**Initialize a Dictionary to Track Substring Counts:**\n\n* A dictionary (dic) is used to store substrings of consecutive repeating characters as keys and their frequencies as values.\n\n**1 ) Generate All Substrings of Repeating Characters**\n**2 ) Track the Frequency of Individual Characters**\n**3 ) Find the Maximum Length of Repeated Substrings**\n**Return Results Based on Conditions:**\n\n* If a valid substring with j > 2 is found, return its length (final).\n* If no such substring exists but a character appears more than twice (y > 2), return 1.\n* If neither condition is satisfied, return -1.\n\n\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N)\n# Code\n```python3 []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n \n dic = defaultdict(int)\n\n for i in range(len(s)): # Generating All Substrings of Repeating Characters\n \n cur = s[i]\n temp = s[i]\n for j in range(i+1, len(s)): \n if cur == s[j]: \n temp += s[j]\n dic[temp] += 1\n else: break\n \n hash_set = defaultdict(int)\n for val in s: # Tracking the Frequency of Individual Characters\n hash_set[val] += 1\n\n final = 0\n for i,j in dic.items(): #Finding the Maximum Length of Repeated Substrings\n\n if j>2 : \n final = max(final, len(i))\n if final > 0 : return final\n for x,y in hash_set.items(): \n if y>2:\n return 1 \n return -1\n# if you like my solution please upvote \n```\n``` C++ []\n\nclass Solution {\npublic:\n int maximumLength(string s) {\n unordered_map<string, int> dic;\n\n // First loop to generate substrings\n for (int i = 0; i < s.length(); i++) {\n string cur(1, s[i]);\n string temp = cur;\n for (int j = i + 1; j < s.length(); j++) {\n if (s[j] == cur[0]) {\n temp += s[j];\n dic[temp]++;\n } else {\n break;\n }\n }\n }\n\n unordered_map<char, int> hash_set;\n for (char c : s) {\n hash_set[c]++;\n }\n\n int finalResult = 0;\n for (auto &pair : dic) {\n if (pair.second > 2) {\n finalResult = max(finalResult, (int)pair.first.length());\n }\n }\n\n if (finalResult > 0) {\n return finalResult;\n }\n\n for (auto &pair : hash_set) {\n if (pair.second > 2) {\n return 1;\n }\n }\n\n return -1;\n }\n};\n```\n``` java []\nclass Solution {\n public int maximumLength(String s) {\n HashMap<String, Integer> dic = new HashMap<>();\n\n // First loop to generate substrings\n for (int i = 0; i < s.length(); i++) {\n String cur = String.valueOf(s.charAt(i));\n String temp = cur;\n for (int j = i + 1; j < s.length(); j++) {\n if (s.charAt(j) == cur.charAt(0)) {\n temp += s.charAt(j);\n dic.put(temp, dic.getOrDefault(temp, 0) + 1);\n } else {\n break;\n }\n }\n }\n\n HashMap<Character, Integer> hashSet = new HashMap<>();\n for (char c : s.toCharArray()) {\n hashSet.put(c, hashSet.getOrDefault(c, 0) + 1);\n }\n\n int finalResult = 0;\n for (String key : dic.keySet()) {\n if (dic.get(key) > 2) {\n finalResult = Math.max(finalResult, key.length());\n }\n }\n\n if (finalResult > 0) {\n return finalResult;\n }\n\n for (char key : hashSet.keySet()) {\n if (hashSet.get(key) > 2) {\n return 1;\n }\n }\n\n return -1;\n }\n} \n```
1
0
['Hash Table', 'Sliding Window', 'Counting', 'C++', 'Java', 'Python3']
0
find-longest-special-substring-that-occurs-thrice-i
✅✅Beats 100%🔥C++🔥Python|| 🚀🚀Super Simple and Efficient Solution🚀🚀||🔥Python🔥C++✅✅
beats-100cpython-super-simple-and-effici-5tkd
null
shobhit_yadav
NORMAL
2024-12-10T03:56:40.222525+00:00
2024-12-10T03:56:40.222525+00:00
49
false
# Complexity\n- Time complexity:$$O(26n)=O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(26n)=O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n public:\n int maximumLength(string s) {\n const int n = s.length();\n int ans = -1;\n int runningLen = 0;\n char prevLetter = \'@\';\n vector<vector<int>> counts(26, vector<int>(n + 1));\n for (const char c : s)\n if (c == prevLetter) {\n ++counts[c - \'a\'][++runningLen];\n } else {\n runningLen = 1;\n ++counts[c - \'a\'][runningLen];\n prevLetter = c;\n }\n for (const vector<int>& count : counts){\n ans = max(ans, getMaxFreq(count, n));\n }\n return ans;\n }\n\n private:\n int getMaxFreq(const vector<int>& count, int maxFreq) {\n int times = 0;\n for (int freq = maxFreq; freq >= 1; --freq) {\n times += count[freq];\n if (times >= 3)\n return freq;\n }\n return -1;\n }\n};\n```\n```python []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n n = len(s)\n runningLen = 0\n prevLetter = \'@\'\n counts = [[0] * (n + 1) for _ in range(26)]\n for c in s:\n if c == prevLetter:\n runningLen += 1\n counts[string.ascii_lowercase.index(c)][runningLen] += 1\n else:\n runningLen = 1\n counts[string.ascii_lowercase.index(c)][runningLen] += 1\n prevLetter = c\n\n def getMaxFreq(count: list[int]) -> int:\n times = 0\n for freq in range(n, 0, -1):\n times += count[freq]\n if times >= 3:\n return freq\n return -1\n\n return max(getMaxFreq(count) for count in counts)\n```
1
0
['C++', 'Python3']
1
find-longest-special-substring-that-occurs-thrice-i
Simple O(n) approach | Kotlin
simple-on-approach-kotlin-by-sanskarpati-nhh0
NoteHere i used temp as string but you can use stringbuilder. (Strings in Kotlin are immutable, so every time you modify a string (e.g., by appending characters
sanskarpatidar
NORMAL
2024-12-10T03:49:11.646439+00:00
2024-12-14T05:02:36.594695+00:00
9
false
# Note\n Here i used temp as string but you can use stringbuilder.\n(Strings in Kotlin are immutable, so every time you modify a string (e.g., by appending characters), a new string object is created. This can lead to unnecessary memory allocation and copying.)\n+= Concatenation --> O(n)\n.append() --> O(1)\n# Complexity\n- Time complexity:O(n)\n\n\n- Space complexity:O(n^2)\ncan use pair(char, int) for map key instead of string to keep its space complexity of 26 * n instead of n * n\n\n# Code\n```kotlin []\nclass Solution {\n fun maximumLength(s: String): Int {\n val mp = mutableMapOf<String, Int>()\n val n = s.length\n var start = 0\n var result = -1\n \n while (start < n) {\n var end = start\n while (end < n && s[start] == s[end]) {\n end++\n }\n // map update\n var temp = ""\n for (i in 0 until (end - start)) {\n temp += s[start]\n mp[temp] = mp.getOrDefault(temp, 0) + (end - start - i)\n if (mp[temp]!! >= 3) result = maxOf(result, i + 1)\n }\n start = end\n }\n \n return result\n }\n}\n\n```
1
0
['Hash Table', 'String', 'Counting', 'Kotlin']
0
find-longest-special-substring-that-occurs-thrice-i
Easy Solution in C++
easy-solution-in-c-by-dhanu07-92b9
null
Dhanu07
NORMAL
2024-12-10T02:52:57.869348+00:00
2024-12-10T02:52:57.869348+00:00
16
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 int maximumLength(string s) {\n unordered_map<string,int>mp;\n\n for(int i = 0 ; i < s.length(); i++){\n string temp = "";\n temp += s[i];\n mp[temp]++;\n for(int j = i+1 ; j < s.length() ; j++){\n if(s[i] == s[j]){\n temp += s[j];\n mp[temp]++;\n }\n else{\n break;\n }\n \n \n }\n }\n\n int size = INT_MIN;\n for(auto it : mp){\n if(it.second >= 3 ){\n int val = it.first.size();\n size = max(val,size);\n }\n }\n\n return size == INT_MIN ? -1 : size;\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Rust binary search solution
rust-binary-search-solution-by-sunjesse-nuvh
null
sunjesse
NORMAL
2024-12-10T02:37:04.670648+00:00
2024-12-10T02:37:04.670648+00:00
2
false
# Code\n```rust []\nimpl Solution {\n fn val(x: usize, s: &Vec<u8>, n: &usize) -> bool {\n let mut cnt: Vec<usize> = vec![0; 26];\n let mut p: usize = 0;\n for i in 0..*n {\n while s[p] != s[i] { p += 1; }\n if (i - p + 1 >= x) { cnt[(s[i] - 97) as usize] += 1; }\n if (cnt[(s[i] - 97) as usize] > 2) { return true; }\n }\n false\n }\n\n pub fn maximum_length(s: String) -> i32 {\n let s: Vec<u8> = s.chars().map(|x| x as u8).collect();\n let n = s.len();\n let mut l: usize = 1;\n let mut r: usize = n;\n if !Self::val(l, &s, &n) { return -1; }\n while l + 1 < r {\n let m: usize = (l+r)/2;\n if Self::val(m, &s, &n) { l = m; }\n else { r = m; }\n }\n l as i32\n }\n}\n```
1
0
['Rust']
1
find-longest-special-substring-that-occurs-thrice-i
Simple O(nlog(n)) solution, with explanaion
simple-ologn-solution-with-explanaion-by-wzvt
IntuitionFinding the longest special substring can be challenging. It is much simpler to check if a special substring of any given length appears 3 times. If a
Conrad_123
NORMAL
2024-12-10T02:16:39.548269+00:00
2024-12-16T04:51:16.900460+00:00
7
false
# Intuition\nFinding the longest special substring can be challenging. It is much simpler to check if a special substring of any given length appears 3 times. If a special substring of a given length appears 3 times, then that is the longest special substring or a larger substring exists. Therefore we can preform a binary search to solve this problem. \n\n# Binary Search\n\nTo check if a special substring of a given occurs 3 times, we keep track of how many consecutive characters we\'ve seen and which character we are counting. If the current count is greater than the length we are searching for, then we have found a unique special substring of the current character and we therefore increment a counter for that character. If any characters counter reaches 3, we know a special substring of that given length occurs 3 times, and we return true. Otherwise we return false. \n\n\n\n# Complexity\n- Time complexity:\n$$O(n\\log(n))$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n bool Is_Valid(std::string& str, int target){\n\n int count = 0;\n std::vector<int> seen(26, 0);\n\n char last_valid = \'.\';\n for(int i = 0; i < str.size(); i++){\n\n if(str[i] == last_valid){\n count++;\n }else{\n count = 1;\n last_valid = str[i];\n }\n\n if(count >= target && ++seen[str[i]-\'a\'] == 3){\n return true;\n }\n }\n\n return false;\n }\n\n int maximumLength(std::string s) {\n\n int low = 0;\n int high = s.size()-1;\n\n while(low < high){\n\n int mid = (low + high)/2;\n\n if(Is_Valid(s, mid)){\n low = mid+1;\n }else{\n high = mid;\n }\n }\n\n return low-1;\n }\n};\n```
1
0
['C++']
1
find-longest-special-substring-that-occurs-thrice-i
Simple Binary Search 100% Beats
simple-binary-search-100-beats-by-optimi-dxbg
null
Optimizor
NORMAL
2024-12-10T02:15:44.658787+00:00
2024-12-10T02:15:44.658787+00:00
17
false
# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n int n = s.size();\n int l = 1, r = n;\n\n if (!helper(s, n, l)) return -1;\n\n while (l + 1 < r) {\n int mid = (l + r) / 2;\n if (helper(s, n, mid)) l = mid;\n else r = mid;\n }\n\n return l;\n }\n\nprivate:\n bool helper(const string& s, int n, int x) {\n vector<int> cnt(26, 0);\n int p = 0;\n\n for (int i = 0; i < n; i++) {\n while (s[p] != s[i]) p++;\n if (i - p + 1 >= x) cnt[s[i] - \'a\']++;\n if (cnt[s[i] - \'a\'] > 2) return true;\n }\n\n return false;\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Easy Explanation!!
easy-explanation-by-shailyintech-817d
null
ShailyInTech
NORMAL
2024-12-10T02:02:33.922106+00:00
2024-12-10T02:02:33.922106+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. -->\nBinary Search for the Maximum Length:\n\nUse binary search to find the longest length of a "special substring" that occurs at least three times. This narrows down the problem space from 1 to \uD835\uDC5B.\n\nSliding Window to Extract Substrings:\n\nFor each length during the binary search, use a sliding window to extract all substrings of that length.\nCheck if the substring is "special" (contains only one unique character).\nCount the occurrences of each substring using a dictionary.\n\nValidation:\n\nIf any special substring appears at least three times, the length is valid.\nAdjust the binary search range based on whether the current length is valid or not.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n2\u22C5logn)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```python3 []\nclass Solution:\n def maximumLength(self, s: str) -> int:\n n = len(s)\n\n # Helper function to check if a substring of a given length can appear at least three times\n def can_form(length):\n substring_count = {}\n for i in range(n - length + 1):\n substring = s[i:i + length]\n if len(set(substring)) == 1: # Check if it\'s special\n substring_count[substring] = substring_count.get(substring, 0) + 1\n if substring_count[substring] >= 3:\n return True\n return False\n\n # Binary search for the maximum valid length\n left, right = 1, n\n result = -1\n while left <= right:\n mid = (left + right) // 2\n if can_form(mid):\n result = mid # Update result to the current valid length\n left = mid + 1 # Try for a longer length\n else:\n right = mid - 1 # Try for a shorter length\n\n return result\n\n```
1
0
['Binary Search', 'Sliding Window', 'Python3']
0
find-longest-special-substring-that-occurs-thrice-i
O(nlogn) solution
onlogn-solution-by-yec0807-f755
null
yenc0807
NORMAL
2024-12-10T01:34:39.237717+00:00
2024-12-10T01:34:39.237717+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nsince you only need to consider the same character, you can simplify it into 26 arrays with amounts of substrings\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ngo through the string once and generate the array\ngo through the array once to find the max array by function max\nreturn\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n vector<int> arr[26];\n const short n=s.size();\n short c,i;\n for(i=0;i<n;i++){\n c=1;\n while(i+1<n & s[i+1]==s[i]){i++;c++;}\n arr[s[i]-\'a\'].push_back(c);\n }\n int ans=-1;\n for(auto& i:arr){\n sort(i.begin(),i.end(),greater<int>());\n c=i.size();\n if(c>2) ans=max(ans,i[2]);\n if(c>1) ans=max(ans,min(i[0]-1,i[1]));\n if(c>0) ans=max(ans,i[0]-2);\n }\n return ans<=0? -1:ans;\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
C++ Truly O(n) optimal solution
c-truly-on-optimal-solution-by-ningck-mnvo
null
Ningck
NORMAL
2024-12-10T00:55:25.591871+00:00
2024-12-10T00:55:25.591871+00:00
13
false
With the constraints being low, O(n) vs O(n^2) does not shine as much through the runtime but for bigger constraints this is much better.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumLength(string s) {\n map<pair<char, int>, int> specialStrToCount;\n for (int l=0; l<s.length(); ++l) {\n for (int r=l; r<s.length() && s[l]==s[r]; ++r) {\n ++specialStrToCount[{s[l], r-l+1}];\n }\n }\n\n int ans = -1;\n for (auto p: specialStrToCount) {\n if (p.second >= 3) ans = std::max(ans, p.first.second);\n }\n\n return ans;\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
by using substr function and using map
by-using-substr-function-and-using-map-b-fsxy
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
2004sherry
NORMAL
2024-04-10T15:13:36.412465+00:00
2024-04-10T15:13:36.412504+00:00
24
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// class Solution {\n// public:\n// bool isspecial(string s)\n// {\n// unordered_map<int,int>mp;\n// for(int i=0;i<s.size();i++)\n// {\n// mp[s[i]]++;\n// }\n// if(mp.size()==1)\n// {\n// return true;\n// }\n// return false;\n// }\n// int maximumLength(string s) {\n// unordered_map<string,int>mp;\n// int count=0;\n// int n=s.size();\n// for(int i=0;i<s.size();i++)\n// {\n// string temp=s.substr(i,n);\n// if(isspecial(temp)){\n// mp[temp]++;\n// }\n// }\n// int maxi=-1;\n// // for(int i=0;i<s.size();i++)\n// // {\n// // string t = s.substr(i,n);\n// // if(mp.find(t)!=mp.end())\n// // {\n// // count++;\n// // }\n// // if(count>=3)\n// // {\n// // maxi= max(maxi,t.size());\n// // }\n// // \n// // }\n// int maxLength = -1;\n// for (auto& entry : mp) {\n// if (entry.second >= 3) {\n// maxLength = max(maxLength, (int)entry.first.size());\n// }\n// }\n// return maxLength;\n \n// }\n// };\n#include <iostream>\n#include <string>\n#include <unordered_map>\nusing namespace std;\n\nclass Solution {\npublic:\n bool isSpecial(string s) {\n unordered_map<char, int> mp;\n for (char c : s) {\n mp[c]++;\n }\n return mp.size() == 1;\n }\n\n int maximumLength(string s) {\n unordered_map<string, int> mp;\n int n = s.size();\n for (int i = 0; i < n; i++) {\n for (int len = 1; i + len <= n; len++) {\n string temp = s.substr(i, len);\n if (isSpecial(temp)) {\n mp[temp]++;\n }\n }\n }\n \n int maxLength = -1;\n for (auto& entry : mp) {\n if (entry.second >= 3) {\n maxLength = max(maxLength, (int)entry.first.size());\n }\n }\n \n return maxLength;\n }\n};\n\n\n\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Java O(N) simple sliding window like approach
java-on-simple-sliding-window-like-appro-ggcg
Intuition\nSliding window\n\n# Approach\nLet N be the largest substring for a given character. Let K be all substrings of size 1 to N. Then the number of subst
warland
NORMAL
2024-03-06T18:51:22.590204+00:00
2024-03-08T13:34:54.793279+00:00
13
false
# Intuition\nSliding window\n\n# Approach\nLet N be the largest substring for a given character. Let K be all substrings of size 1 to N. Then the number of substrings that can be formed for a substring of size N with K size is: N - K + 1.\n\n# Complexity\n- Time complexity:\n$$O(N)$$\n\n- Space complexity:\n$$O(N)$$\n\n# Code\n```\nclass Solution {\n public int maximumLength(String s) {\n // maps a character and a character\'s substring to a number of occurences.\n int[][] counts = new int[26][s.length() + 1];\n int n = s.length(), max = 0;\n for (int i = 0; i < n; i++) {\n int j = i;\n char c = s.charAt(i);\n while (j < n - 1 && c == s.charAt(j + 1)) {\n j++;\n }\n int windowSize = j - i + 1;\n // count window for len\n for (int a = 1; a <= windowSize; a++) {\n // number of substrings of len A for a string s(i, j + 1)\n int numOfSubstrings = windowSize - a + 1;\n int count = counts[c - \'a\'][a] + numOfSubstrings;\n counts[c - \'a\'][a] = count;\n if (count >= 3) {\n max = Math.max(max, a);\n }\n }\n i = j;\n }\n\n return max != 0 ? max : -1;\n }\n}\n```
1
0
['Java']
0
find-longest-special-substring-that-occurs-thrice-i
easy to understand ,beginners level code ,brute force
easy-to-understand-beginners-level-code-z92vl
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1.using substring() ins
vigneshbangaru69
NORMAL
2024-02-27T18:24:15.610981+00:00
2024-02-27T18:24:15.611041+00:00
29
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.using substring() insert the strings into the hashmap and count the frequencys(in other words it is the length of the substring) of different lengths\n2.if the length of the substring or frequency is greater than 3 then we check the size of the substring whether it is a single character or a multicharacter \n3.then return the size of the substring if it is true other wise false(-1)\n# Complexity\n- Time complexity:O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\n\nclass Solution {\n public int maximumLength(String s) {\n HashMap<String, Integer> map = new HashMap<>();\n for (int i = 0; i < s.length(); i++) {\n for (int j = i + 1; j <= s.length(); j++) { \n String str = s.substring(i, j);\n if (map.containsKey(str)) {\n map.put(str, map.get(str) + 1);\n } else {\n map.put(str, 1);\n }\n }\n }\n int len = 0;\n for (Map.Entry<String, Integer> e : map.entrySet()) {\n String str = e.getKey();\n int val = e.getValue();\n if (val >= 3) {\n HashSet<Character> set = new HashSet<>();\n for (int j = 0; j < str.length(); j++) {\n set.add(str.charAt(j));\n }\n if (set.size() == 1) { // Corrected condition\n len = Math.max(len, str.length());\n }\n }\n }\n return (len == 0) ? -1 : len;\n }\n}\n\n```\n![upvote please.webp](https://assets.leetcode.com/users/images/c4af312b-9a2c-47fe-bcfe-25652498a53d_1709058226.5963867.webp)\n
1
0
['Hash Table', 'String', 'Counting', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
sliding window, and hashmap
sliding-window-and-hashmap-by-wxs2204-ri2h
Intuition\n Describe your first thoughts on how to solve this problem. \nUse a map to count the occurance of each special substring\n\n# Approach\n Describe you
wxs2204
NORMAL
2024-02-15T04:42:06.807686+00:00
2024-02-15T04:42:06.807715+00:00
75
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse a map to count the occurance of each special substring\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. find a interval with identical char c, with length n\n2. special substring will can be c, cc, ccc, ... n c(s)\n3. with co-responding counts: n, n-1, n-2, ... 1\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maximumLength(String s) {\n Map<String, Integer> map = new HashMap<>();\n int left = 0;\n int length = -1;\n for (int right = 1; right <= s.length(); right++) {\n if (right == s.length() || s.charAt(right) != s.charAt(left)) {\n int n = right - left;\n for (int i = 1; i <= n; i++){\n String cur = i + "" + s.charAt(left);\n map.put(cur, map.getOrDefault(cur, 0) + (n-i+1));\n if (map.get(cur) >= 3) {\n // System.out.println(cur + "," + 3);\n length = Math.max(length, i);\n };\n }\n left = right;\n }\n }\n return length;\n }\n}\n```
1
0
['Hash Table', 'Sliding Window', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
Easy C++ Solution
easy-c-solution-by-anshuljhamb16-uidm
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
anshuljhamb16
NORMAL
2024-01-08T18:29:09.373921+00:00
2024-01-08T18:29:09.374030+00:00
45
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumLength(string s) {\n unordered_map<string, int> m1;\n\n for (int i = 0; i < s.length(); i++) {\n string substring = "";\n substring += s[i];\n m1[substring]++;\n for (int j = i + 1; j < s.length(); j++) {\n substring += s[j];\n if (s[j]==s[i]){\n m1[substring]++;\n }\n else{\n break;\n }\n\n }\n }\n\n int res = -1;\n int maxlength = 0;\n\n for (auto itr : m1) {\n if (itr.second >= 3) {\n string temp = itr.first;\n if (temp.length() > maxlength) {\n res = temp.length();\n maxlength = temp.length();\n }\n }\n }\n\n return res;\n }\n};\n\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Only math | No binary search, no brute-force | 3 ms - faster than 99.73% solutions
simple-python3-solutions-40-ms-faster-th-wxkq
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# Co
tigprog
NORMAL
2024-01-03T18:56:59.095907+00:00
2024-12-10T10:03:37.576143+00:00
261
false
# 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``` python3 []\n# base solution\n\nfrom itertools import groupby\n\nclass Solution:\n def maximumLength(self, s: str) -> int:\n result = -1\n data = Counter()\n for char, it in groupby(s):\n length = sum(1 for _ in it)\n data[(char, length)] += 1\n if length > 1:\n data[(char, length - 1)] += 2\n if length > 2:\n result = max(result, length - 2)\n \n for (_, length), cnt in data.items():\n if cnt >= 3:\n result = max(result, length)\n return result\n```\n``` python3 []\n# solution step-by-step\n\nimport heapq\nfrom itertools import groupby\n\nclass Solution:\n def maximumLength(self, s: str) -> int:\n data = defaultdict(list)\n for char, it in groupby(s):\n length = sum(1 for _ in it)\n data[char].append(length)\n \n def calc(group):\n best = group[0]\n if len(group) >= 3 and group[2] == best:\n return best\n if len(group) >= 2 and group[1] >= best - 1:\n return best - 1\n return best - 2\n \n result = max(\n calc(\n list(heapq.nlargest(3, group))\n )\n for group in data.values()\n )\n return result if result != 0 else -1\n\n```
1
0
['Hash Table', 'Math', 'Python3']
1
find-longest-special-substring-that-occurs-thrice-i
Python3 | Intuitive.
python3-intuitive-by-yutaokkotsu-7504
Intuition\n Describe your first thoughts on how to solve this problem. \n\n- Use two pointers that scans a substring within string, s.\n- Record the substring,
yutaokkotsu
NORMAL
2024-01-02T00:21:27.122155+00:00
2024-01-02T02:32:49.554517+00:00
15
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n- Use two pointers that scans a substring within string, `s`.\n- Record the substring, and its frequency, inside a hashmap\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n<ins>Three-steps</ins>\n\n(1) Use a hashmap/dictionary (here called `memo`) to keep track of substrings that are encountered.\n(2) Scan (loop) through the string, `s`. In a while-loop, if the proceeding (next) element is equal to the current element (*i.e.* repeating), it means that the substring is **\'special\'**; record the frequency (*i.e.* count) of said substring into `memo`.\n(3) Finally, analyze the `memo` to find the longest substring that also has a frequency that is greater than 3.\n\n# Code\n```\nclass Solution:\n def maximumLength(self, s: str) -> int:\n memo = {}\n r = 0\n\n for l in range(len(s)):\n r = l\n while r + 1 <= len(s) and s[l] == s[r]:\n memo[s[l:r + 1]] = memo.setdefault(s[l:r + 1], 0) + 1\n r += 1\n\n # sub-approach 1\n max_substring = 0\n \n for k, int_v in memo.items():\n if len(k) > max_substring and int_v >= 3:\n max_substring = max(max_substring, len(k))\n\n return max_substring if max_substring else -1\n\n # OR ##################\n # sub-approach 2\n #\n # memo_lst = sorted(memo.items(), key=lambda x: len(x[0]), reverse=True) \n # \n # for k, int_v in memo_lst:\n # if int_v >= 3:\n # return len(k)\n #\n # return -1\n\n```\n\n# Complexity\n\n**sub-approach 1**, see below\n- Time complexity:\n\n&emsp; &emsp; &emsp; O(n<sup>2</sup>) \n\n- Space complexity:\n\n&emsp; &emsp; &emsp; O(n<sup>2</sup>)\n\nor **sub-approach 2**, see below\n- Time complexity:\n\n&emsp; &emsp; &emsp; O(n<sup>2</sup> * log(m))\n\n- Space complexity:\n\n&emsp; &emsp; &emsp; O(n<sup>2</sup> + m) \n\n# How it works\n\n\n## Example:\n\n### Part 1:\n\ns = "aaaaa"\n\nUse left `l`, and right, `r` pointers:\n\n```\n""" Diagram\nr = 0 # declare a right pointer, called \'r\', to 0.\n \u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510 \ns:str = | a || a || a || a || a |\n \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\nr = 0\n"""\n```\n\nThe left pointer, `l` increments in a for-loop. Increments from `0` -> `len(s)`.\n\n```\n""" Diagram\n \u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510 \ns:str = | a || a || a || a || a |\n \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\nr = 0\nl = 0 ---> 4 \n"""\n\nfor l in range(len(s)):\n ...\n...\n```\n\nInside the for-loop, have a while-loop that increments `r`, as long as:\n- `r` is smaller than the `len(s)` (to avoid `List Index Out of Range` error.)\n- The value of s at indices `l` and `r` are the same; `s[l] == s[r]` (to ensure we only look at repeating substrings)\n\n```\n""" Diagram\n \u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510 \ns:str = | a || a || a || a || a |\n \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\nr = 0 -> 1 -> 2 -> 3 -> 4\nl = 0 ---> 4 \n"""\n\nfor l in range(len(s)):\n while r + 1 <= len(s) and s[l] == s[r]:\n r += 1\n ...\n...\n\n```\nAnd inside this while loop, update the hashmap, `memo`, with the frequency of the substring that is encountered. \n\n```\n""" Diagram\n \u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510\u250C\u2500\u2500\u2500\u2510 \ns:str = | a || a || a || a || a |\n \u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\u2514\u2500\u2500\u2500\u2518\nr = 0 -> 1 -> 2 -> 3 -> 4\nl = 0 ---> 4 \n"""\n\nfor l in range(len(s)):\n while r + 1 <= len(s) and s[l] == s[r]:\n memo[s[l:r + 1]] = memo.setdefault(s[l:r + 1], 0) + 1\n r += 1\n...\n```\nAs a reminder, this question is asking to return:\n> "the length of the longest special substring of `s` which occurs at least thrice, or `-1` if no special substring occurs at least thrice."\n\nThe hashmap, called `memo`, gives an indication of which substring occurs three times or more. \n\n```\n# memo:\n{\n \'a\': 4, # <- this substring occurs three times or more\n \'aa\': 3, # <- this substring occurs three times or more\n \'aaa\': 2, \n \'aaaa\': 1\n}\n```\nIn the above case, the ***longest special substring that occurs three or more times*** is `"aa"`. (This is apparent because the length of `"aa"` is larger than the length of `"a"`, even though the frequency of `"a"` -> `4` is greater than the frequency of `"a"` -> `3`)\n\nIn order to get the longest substring there are two sub-approaches. \n\n### Part 2: Sub-approach 1\n\nDeclare a variable called `max-substring` that will store the length of the longest substring. \n\nfor-loop through the generated `memo` from above. In this case, iterate over `memo.items()`.\n\n```\n...\nmax_substring = 0\n\nfor k, int_v in memo.items():\n ...\n...\n```\n\nWhile iterating over `memo.items()`, if the substring is greater than the current value of `max_substring` AND the frequency of said substring is greater than 3, apply Python3\'s `max()` function to re-record the longest substring:\n```\n...\nmax_substring = 0\n\nfor k, int_v in memo.items():\n if len(k) > max_substring and int_v >= 3:\n max_substring = max(max_substring, len(k))\n\nreturn max_substring if max_substring else -1\n```\n\nFinally, return the `max_substring` if `max_substring` has value that is `not 0`/`truthy`; otherwise just return `-1` to indicate that nothing was found.\n\n### Part 2: Sub-approach 2\n\nThe hashmap, `memo`, can be ordered in the following way:\n\n```\nmemo_lst = sorted(memo.items(), key=lambda x: len(x[0]), reverse=True) \n```\nThe above code provides a list that is sorted by the length of the keys in reverse order. \n\n```\n# memo_lst: List[Tuple(substring:str, frequency:int)]\n [(\'aaaaa\', 1), (\'aaaa\', 2), (\'aaa\', 3), (\'aa\', 4), (\'a\', 5)]\n```\nNow, just loop through this list again, and return the first item where the frequency is greater than or equal to 3. If there is no substring that meets these conditions, return -1. \n\n```\n... \nmemo_lst = sorted(memo.items(), key=lambda x: len(x[0]), reverse=True) \n\nfor k, int_v in memo_lst:\n if int_v >= 3:\n return len(k)\n\nreturn -1\n```\n\n\n
1
0
['Array', 'Hash Table', 'Python3']
0
find-longest-special-substring-that-occurs-thrice-i
C++ || Very Easy Approach
c-very-easy-approach-by-mrigank_2003-wih9
\n\n# Code\n\nclass Solution {\npublic:\n int maximumLength(string s) {\n map<string, int>mp;\n for(int i=0; i<s.size(); i++){\n cha
mrigank_2003
NORMAL
2023-12-31T17:36:03.823337+00:00
2023-12-31T17:36:03.823367+00:00
54
false
\n\n# Code\n```\nclass Solution {\npublic:\n int maximumLength(string s) {\n map<string, int>mp;\n for(int i=0; i<s.size(); i++){\n char a=s[i];\n int j=i;\n mp[s.substr(i, 1)]++;\n j++;\n while(j<s.size() && s[j]==a){\n mp[s.substr(i, j-i+1)]++;\n j++;\n }\n j--;\n i=j;\n }\n int ans=0, cnt=0;\n for(auto it: mp){\n string s1=it.first;\n // cout<<s1<<endl;\n int cnt1=0;\n for(int i=0; i<s.size()-s1.size()+1; i++){\n // cout<<s.substr(i, s1.size())<<" "<<endl;\n if(s.substr(i, s1.size())==s1)cnt1++;\n }\n // cout<<cnt1<<" "<<s1.size()<<" "<<ans<<" "<<(cnt1>=3)<<" "<<(s1.size()>ans)<<endl;\n if(cnt1>=3 && s1.size()>ans){\n // cout<<" here"<<endl;\n ans=s1.size();\n }\n }\n if(ans==0)return -1;\n return ans;\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Simple O(N) Solution Using Map | Intuition Explained | C++
simple-on-solution-using-map-intuition-e-fj39
Intuition\n\n- If same chars length == k , then we have : \n - 1 strings of length = k-0 \n - 2 strings of length = k-1 \n - 3 strings of length = k-2 \n
Jay_1410
NORMAL
2023-12-31T13:25:13.397713+00:00
2023-12-31T13:25:13.397741+00:00
38
false
# Intuition\n\n- If same chars length == k , then we have : \n - 1 strings of length = k-0 \n - 2 strings of length = k-1 \n - 3 strings of length = k-2 \n - We dont care about strings of length = k-3 , k-4 , . . . etc .\nas the we already got a special string of length = k-2 .\n\n# Code\n```\nclass Solution {\npublic:\n int maximumLength(string s){\n int n = s.size() , maxi = -1;\n map<pair<char,int>,int> mp;\n for(int i=0,j=0;i<n;i=j){\n int len = 0 ;\n while(j < n && s[i] == s[j]) j++ , len++;\n if(len-0 > 0 && (mp[{s[i],len-0}]+=1) >= 3) maxi = max(maxi,len-0);\n if(len-1 > 0 && (mp[{s[i],len-1}]+=2) >= 3) maxi = max(maxi,len-1);\n if(len-2 > 0 && (mp[{s[i],len-2}]+=3) >= 3) maxi = max(maxi,len-2);\n }\n return maxi;\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
cpp easy solution using three vector TC- O(N) SC-O(1)
cpp-easy-solution-using-three-vector-tc-8jfv9
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
dr110801
NORMAL
2023-12-31T10:43:13.130026+00:00
2023-12-31T10:43:13.130058+00:00
13
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumLength(string s) {\n vector<int>fir(26,0);\n vector<int>sec(26,0);\n vector<int>thi(26,0);\n\n int cnt=1;\n char ch=s[0];\n\n for(int i=1; i<=s.size(); i++){\n if( i==s.size() or s[i]!=ch){\n if(fir[ch-\'a\']==0){\n fir[ch-\'a\']=cnt;\n }\n else {\n if(cnt>fir[ch-\'a\']){\n thi[ch-\'a\']=sec[ch-\'a\'];\n sec[ch-\'a\']=fir[ch-\'a\'];\n fir[ch-\'a\']=cnt;\n }\n else if(cnt>sec[ch-\'a\']){\n thi[ch-\'a\']=sec[ch-\'a\'];\n sec[ch-\'a\']=cnt;\n }\n else{\n thi[ch-\'a\']=max(cnt,thi[ch-\'a\']);\n }\n }\n if(i!=s.size()){\n cnt=1;\n ch=s[i];\n }\n }\n else{\n cnt++;\n }\n }\n int ans=-1;\n for(int i=0; i<26 ; i++){\n if(fir[i]==sec[i] and sec[i]==thi[i] and fir[i]>0){\n ans=max(ans,fir[i]);\n }\n else if(fir[i]==sec[i] and fir[i]>=2){\n ans=max(ans,fir[i]-1);\n }\n else if(abs(fir[i]-sec[i])==1 and sec[i]>=1){\n ans=max(ans,sec[i]);\n }\n if(fir[i]>=3){\n ans=max(ans, fir[i]-2);\n }\n }\n return ans;\n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Use O(26 * 3) array and O(n) time - 81 ms
use-o26-3-array-and-on-time-81-ms-by-efo-tb4r
Approach\nSave top 3 counts in decreasing order per each letter, now we can get min from three ababac (1), min from first shared and second aaba (1), or first s
eforce
NORMAL
2023-12-31T07:06:42.695503+00:00
2023-12-31T07:08:15.533265+00:00
29
false
# Approach\nSave top 3 counts in decreasing order per each letter, now we can get min from three `ababac` (1), min from first shared and second `aaba` (1), or first shared accross three `aaaa` (2).\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$ // 26 * 3\n\n# Code\n```\n/**\n * @param {string} s\n * @return {number}\n */\nvar maximumLength = function(s) {\n const aCode = "a".charCodeAt();\n const counts = Array.from({ length: 26}, () => new Array(3).fill(0));\n let prev;\n let count = 0;\n\n const save = () => {\n const index = prev.charCodeAt() - aCode;\n if (counts[index][0] < count) {\n counts[index][2] = counts[index][1];\n counts[index][1] = counts[index][0];\n counts[index][0] = count;\n } else if (counts[index][1] < count) {\n counts[index][2] = counts[index][1];\n counts[index][1] = count;\n } else if (counts[index][2] < count) {\n counts[index][2] = count;\n }\n };\n\n for (let i = 0; i <= s.length; ++i) {\n if (prev === s[i]) {\n ++count;\n } else {\n if (count) save();\n prev = s[i];\n count = 1;\n }\n }\n\n let result = -1;\n\n for (let i = 0; i < 26; ++i) {\n count = Math.min(counts[i][0], counts[i][1], counts[i][2]);\n if (count) result = Math.max(result, count);\n count = Math.min(counts[i][0] - 1, counts[i][1]);\n if (count > 0) result = Math.max(result, count);\n count = counts[i][0] - 2;\n if (count > 0) result = Math.max(result, count);\n }\n\n return result;\n};\n```
1
0
['JavaScript']
0
find-longest-special-substring-that-occurs-thrice-i
[JAVA] Beats 100% simple approach using Set.
java-beats-100-simple-approach-using-set-wb3s
\n\n\n# Approach \uD83D\uDCA1\n Describe your approach to solving the problem. \nDivide String into sub-parts and check the possibility of each String that is p
Codersoon
NORMAL
2023-12-31T05:11:08.183755+00:00
2023-12-31T05:14:06.801550+00:00
51
false
![image.png](https://assets.leetcode.com/users/images/22428c16-0fbb-48b1-b058-301c9253ceda_1703999403.3413873.png)\n\n\n# Approach \uD83D\uDCA1\n<!-- Describe your approach to solving the problem. -->\nDivide String into sub-parts and check the possibility of each String that is present in input sub-string 3 time. check for each and you will get the answer :)\n\n# Complexity\n- Time complexity: O(N^2).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maximumLength(String s) {\n //Base case\n if(s.length() <= 2)return 0;\n\n Set<String> set = new HashSet<>();\n int maxlength = -1;\n for(int i=0; i<s.length(); i++){\n for(int j=i+1; j<s.length(); j++){\n String charSub = s.substring(i,j);\n if(isSameChars(charSub)){\n set.add(charSub);\n }\n }\n }\n\n for(String setStr : set){\n if(isThreetimes(s, setStr)){\n maxlength = Math.max(maxlength, setStr.length());\n }\n }\n return maxlength;\n }\n\n private boolean isSameChars(String allSame){\n char c = allSame.charAt(0);\n for(int i=1; i<allSame.length(); i++){\n if(c != allSame.charAt(i))return false;\n }\n return true;\n }\n\n private boolean isThreetimes(String s, String setSub){\n int count = 0;\n for(int i=0; i<=s.length()-setSub.length(); i++){\n boolean same = true;\n for(int j = 0; j<setSub.length(); j++){\n if(s.charAt(i+j) != setSub.charAt(j)){\n same = false;\n break;\n }\n }\n if(same)count++;\n }\n return count>=3;\n }\n}\n\n//TC : O(N^2);\n//SC : O(N);\n```\nHappy Leetcoding...... ^^
1
0
['Java']
2
find-longest-special-substring-that-occurs-thrice-i
🧽 Java Clean & Simple | Sliding Window O(n)
java-clean-simple-sliding-window-on-by-p-e72c
Approach\nUsing Sliding Window to slide over it to get the continuous lenght, save it to the map (A 2D array int[][] map = new int[26][s.length()];)\n\nlast, ch
palmas
NORMAL
2023-12-31T04:48:08.199713+00:00
2024-07-28T04:25:39.067878+00:00
121
false
# Approach\nUsing Sliding Window to slide over it to get the continuous lenght, save it to the map (A 2D array ```int[][] map = new int[26][s.length()];```)\n\nlast, check if it have appear three time and compare the length to other which have appear three time.\n\n\n\n# Optimization\nAs example of "aaaa", when looping through it, it would be:\n"a": 4\n"aa": 3\n"aaa: 2\n"aaaa": 1\n\nwhich mean with a length of continuous n (4), each sub length (1,2,3,4) would appear (n - sub) time, so we can jump to the next different without looping them again.\n(the last line```i = j; //jump to first different```)\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\n public int maximumLength(String s) {\n char[] arr = s.toCharArray();\n int[][] map = new int[26][s.length()];\n\n int max = -1;\n\n int i = 0;\n while (i < arr.length) {\n int j = i;\n\n while (j < arr.length && arr[j] == arr[i])\n j++;\n\n int cont = j - i;\n for (int k = 0; k < cont; k++) {\n map[arr[i] - \'a\'][k] += cont - k;\n if (map[arr[i] - \'a\'][k] > 2)\n max = Math.max(max, k + 1);\n }\n\n i = j;\n }\n return max;\n }\n}\n```
1
0
['Java']
1
find-longest-special-substring-that-occurs-thrice-i
Java || Beats 100% of the solutions ✅ ✅ ✅
java-beats-100-of-the-solutions-by-ritab-d0re
\n\n# Code\n\nclass Solution {\n public int maximumLength(String s) {\n HashMap<String,Integer>map=new HashMap<>();\n int n=s.length();\n
Ritabrata_1080
NORMAL
2023-12-31T04:38:31.817278+00:00
2023-12-31T04:38:31.817297+00:00
30
false
\n\n# Code\n```\nclass Solution {\n public int maximumLength(String s) {\n HashMap<String,Integer>map=new HashMap<>();\n int n=s.length();\n for(int i=0;i<n;i++){\n String str="";\n for(int j=i;j<n;j++){\n str+=s.charAt(j);\n if(special(str)){\n if(map.containsKey(str)) map.put(str,map.get(str)+1);\n else map.put(str,1);\n }\n }\n }\n int max=-1;\n for(String s1:map.keySet()){\n if(map.get(s1)>2) max=Math.max(max,s1.length());\n }\n return max;\n }\n \n public boolean special(String str){\n for(int i=0;i<str.length()-1;i++){\n if(str.charAt(i)!=str.charAt(i+1)) return false;\n }\n return true;\n }\n}\n```
1
0
['Hash Table', 'Java']
1
find-longest-special-substring-that-occurs-thrice-i
Clear clean details Explanation : find-longest-special-substring-that-occurs-thrice-I and II
clear-clean-details-explanation-find-lon-w3ac
\n\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n\n# Code\n\npublic class Solution {\n public static int maximumLength(String input) {\n // Map to
Dheerajkumar9631r
NORMAL
2023-12-31T04:06:54.367338+00:00
2023-12-31T04:08:26.830838+00:00
16
false
\n\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n\n# Code\n```\npublic class Solution {\n public static int maximumLength(String input) {\n // Map to store counts of special substrings\n Map<String, Integer> specialSubstringCountMap = new HashMap<>();\n\n // Length of the input string\n int length = input.length();\n\n // Iterate through all possible substrings\n for (int start = 0; start < length; start++) {\n for (int end = start + 1; end <= length; end++) {\n // Extract the current substring\n String currentSubstring = input.substring(start, end);\n\n // Check if the substring is special\n boolean isSpecial = true;\n for (int i = 0; i < currentSubstring.length() - 1; i++) {\n if (currentSubstring.charAt(i) != currentSubstring.charAt(i + 1)) {\n isSpecial = false;\n break;\n }\n }\n\n // If the substring is special, update the count in the map\n if (isSpecial) {\n specialSubstringCountMap.put(currentSubstring,\n specialSubstringCountMap.getOrDefault(currentSubstring, 0) + 1);\n }\n }\n }\n\n // Find the maximum length of special substrings occurring at least thrice\n int maxLength = -1;\n for (Map.Entry<String, Integer> entry : specialSubstringCountMap.entrySet()) {\n if (entry.getValue() >= 3) {\n maxLength = Math.max(maxLength, entry.getKey().length());\n }\n }\n\n return maxLength;\n }}\n```
1
0
['Java']
1
find-longest-special-substring-that-occurs-thrice-i
sliding window solution c++
sliding-window-solution-c-by-yashgarala2-wx3r
Intuition\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n^2)\n Add your space complexity here, e.g.
yashgarala29
NORMAL
2023-12-31T04:02:40.352844+00:00
2023-12-31T04:02:40.352888+00:00
36
false
# Intuition\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool countWindo(string &s,int c){\n /*\n this method will count char no of occurrence in string \n we are not storing string we are just storing char so we reduce space complexity \n */\n map<char,int> count;\n map<char,int> arr;\n for(int i=0;i<c;i++)\n {\n arr[s[i]]++;\n } \n if(arr[s[0]]==c){\n count[s[0]]++;\n }\n int t=0;\n int n=s.length();\n for(int j=c;j<n;j++){\n arr[s[t++]]--;\n arr[s[j]]++;\n if(arr[s[j]]==c){\n ++count[s[j]];\n if(count[s[j]]>=3){\n return true;\n }\n }\n }\n return false; \n }\n int maximumLength(string s) {\n int n=s.length();\n for(int i=n-2;i>=1;i--){\n \n if(countWindo(s,i)){\n return i;\n }\n }\n return -1; \n \n }\n};\n```
1
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Easy Python Solution
easy-python-solution-by-_suraj__007-gst8
Code\n\nclass Solution:\n def maximumLength(self, s: str) -> int:\n if len(set(s))==len(s):\n return -1\n for i in range(len(s)-3,-1
_suraj__007
NORMAL
2023-12-31T04:01:18.321763+00:00
2023-12-31T04:01:18.321797+00:00
185
false
# Code\n```\nclass Solution:\n def maximumLength(self, s: str) -> int:\n if len(set(s))==len(s):\n return -1\n for i in range(len(s)-3,-1,-1):\n d = {}\n count = 0\n for j in range(i,len(s)):\n if len(set(s[count:j+1]))==1:\n if s[count:j+1] not in d:\n d[s[count:j+1]]=1\n else:\n d[s[count:j+1]]+=1\n if d[s[count:j+1]]==3:\n return len(s[count:j+1])\n count+=1\n return -1\n \n \n```
1
0
['Python3']
0
find-longest-special-substring-that-occurs-thrice-i
Java
java-by-soumya_699-7729
IntuitionApproachComplexity Time complexity: Space complexity: Code
Soumya_699
NORMAL
2025-04-09T07:01:34.582782+00:00
2025-04-09T07:01:34.582782+00:00
0
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maximumLength(String s) { Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j <= s.length(); j++) { String y = s.substring(i, j); if (y.chars().distinct().count() == 1) { map.put(y, map.getOrDefault(y, 0) + 1); } } } int max = 0; for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getValue() >= 3) { if (entry.getKey().length() > max) { max = entry.getKey().length(); } } } if (max == 0) { return -1; } return max; } } ```
0
0
['Java']
0
find-longest-special-substring-that-occurs-thrice-i
Java
java-by-soumya_699-c7m3
IntuitionApproachComplexity Time complexity: Space complexity: Code
Soumya_699
NORMAL
2025-04-09T07:01:29.946604+00:00
2025-04-09T07:01:29.946604+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maximumLength(String s) { Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j <= s.length(); j++) { String y = s.substring(i, j); if (y.chars().distinct().count() == 1) { map.put(y, map.getOrDefault(y, 0) + 1); } } } int max = 0; for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getValue() >= 3) { if (entry.getKey().length() > max) { max = entry.getKey().length(); } } } if (max == 0) { return -1; } return max; } } ```
0
0
['Java']
0
find-longest-special-substring-that-occurs-thrice-i
Longest Repeated Character Substring Occurring Thrice
longest-repeated-character-substring-occ-3283
IntuitionInitial thought was to identify all substrings in the input string that consist of a single repeated character (e.g., "aaa" or "bb"), since these are t
t0ny1601
NORMAL
2025-04-05T09:10:14.063878+00:00
2025-04-05T09:10:14.063878+00:00
1
false
# Intuition Initial thought was to identify all substrings in the input string that consist of a single repeated character (e.g., "aaa" or "bb"), since these are the "special substrings" defined by the problem. The goal is to find the longest such substring that appears at least three times. A key observation is that within a run of identical characters (e.g., "aaaa"), shorter substrings (like "aa" or "aaa") can appear multiple times, and we need to count these occurrences across all runs of the same character in the string. This led me to think about breaking the string into runs of consecutive characters and then analyzing the possible substring lengths within those runs to see which length appears at least thrice. # Approach To solve this problem efficiently, I used the following approach: 1. Parse the String into Runs: Iterate through the string and group consecutive identical characters into "runs." For each run, calculate its length (e.g., "aaa" has length 3). Store these lengths in a Map<Character, List<Integer>>, where the key is the character and the value is a list of run lengths for that character. For example, for "aaabaaa", the map would be 'a' -> [3, 3], 'b' -> [1]. 2. Count Substring Occurrences: For each character in the map, process its list of run lengths. For each possible substring length k (starting from 1 up to the maximum possible length), calculate how many times a substring of length k appears across all runs of that character. For a run of length len, the number of substrings of length k is max(0, len - k + 1). For example, in a run "aaaa" (length 4), there are 3 substrings of length 2 ("aa" at positions 0-1, 1-2, 2-3). Sum this count across all runs of the same character. 3. Find the Maximum Valid Length: For each k, if the total count of occurrences is at least 3, update the maximum length found so far. If the count drops below 3 for a given k, we can stop checking larger values of k for that character, as the count only decreases as k increases. Track the overall maximum k across all characters. 4. Handle Edge Cases: If the string length is less than 3, return -1 since no substring can occur thrice. If no substring length has at least 3 occurrences, return -1. # Complexity - Time complexity: $$O(n^2)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maximumLength(String s) { if (s.length() < 3) return -1; // Map to store run lengths for each character Map<Character, List<Integer>> map = new HashMap<>(); // Step 1: Collect run lengths int n = s.length(); for (int i = 0; i < n; ) { char ch = s.charAt(i); int start = i; while (i < n && s.charAt(i) == ch) i++; int length = i - start; map.computeIfAbsent(ch, k -> new ArrayList<>()).add(length); } int maxLen = -1; // Step 2: Analyze each character for (List<Integer> lengths : map.values()) { // For each possible substring length, count occurrences for (int k = 1; k <= n; k++) { int count = 0; for (int len : lengths) { // Number of substrings of length k in a run of length len count += Math.max(0, len - k + 1); } if (count >= 3) { maxLen = Math.max(maxLen, k); } else { break; // No need to check larger k if count < 3 } } } return maxLen; } } ```
0
0
['String', 'Java']
0
find-longest-special-substring-that-occurs-thrice-i
7 ms Beats 72.70%
7-ms-beats-7270-by-red_viper-xrer
Code
red_viper
NORMAL
2025-03-28T10:47:43.776385+00:00
2025-03-28T10:47:43.776385+00:00
1
false
# Code ```cpp [] class Solution { public: int maximumLength(string s) { unordered_map <string , int> map; int len = s.length(); for(int i =0 ; i < len ; i ++ ){ string str =""; for ( int j = i ; j < len ; j ++ ){ if( !str.empty() && str.back() != s[j]) break; str += s[j]; map[ str ] ++; } } int Max = INT_MIN; string result = ""; for ( const auto & [temp , ct ] : map){ int size = temp .size(); if( Max < size && ct >= 3 ){ Max = size; } } return Max == INT_MIN ? -1 : Max; } }; ```
0
0
['C++']
0
find-longest-special-substring-that-occurs-thrice-i
Easy C++ solution using sliding window and hash map
easy-c-solution-using-sliding-window-and-pxuu
Code
imran2018wahid
NORMAL
2025-03-27T11:25:16.379254+00:00
2025-03-27T11:25:16.379254+00:00
1
false
# Code ```cpp [] class Solution { public: int maximumLength(string s) { int ans = 0, j = 0; string current = ""; unordered_map<string, int> m; for (int i=0;i<s.length();i++) { current += s[i]; if (s[i] != s[j]) { j = i; current = ""; current += s[i]; } m[current]++; if (m[current] >= 3 && ans < current.length()) { ans = current.length(); } ans = max(ans, (i-j-1)); } for (auto it : m) { if (it.second == 2 && m.find(it.first + it.first.back()) != m.end()) { ans = max(ans, (int)it.first.length()); } } return ans==0?-1:ans; } }; ```
0
0
['Sliding Window', 'C++']
0