question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
remove-nth-node-from-end-of-list
Easy ,Beginner Friendly & Dry Run || Simple loops || Time O(N) Space O(1) || Gits ✅✅✅👈👈
easy-beginner-friendly-dry-run-simple-lo-ea7q
\n\n# Intuition \uD83D\uDC48\n\nIn the given question, you are provided with the head of a linked list and a number n. You are required to remove the nth node f
GiteshSK_12
NORMAL
2024-02-07T12:30:04.651212+00:00
2024-02-07T12:30:04.651244+00:00
1,324
false
![Screenshot 2024-02-07 164819.png](https://assets.leetcode.com/users/images/0b582f2d-9b4c-4f0d-aace-e0ec05ca4b49_1707308564.5210462.png)\n\n# Intuition \uD83D\uDC48\n\nIn the given question, you are provided with the head of a linked list and a number n. You are required to remove the nth node from the end of the list.\n\n# Approach \uD83D\uDC48\n\nTo solve this question, first, we need to determine the length of the linked list. After obtaining the length, we subtract n from it, which gives us the position of the nth node from the start that we need to remove from the linked list.\n\n# Code Explanation \uD83D\uDC48\n\n* **Edge Case Handling**: The method first checks if the input `head` is `null` or if the list contains only one node (`head.next == null`). In either case, the method returns `null`, as removing a node from such a list would result in an empty list.\n \n* **Dummy Head Initialization**: A dummy node with a value of `0` is created and its `next` pointer is set to point to the `head` of the list. This dummy node acts as a placeholder to simplify edge cases, especially when the node to be removed is the head of the list.\n \n* **Counting Nodes**: The method iterates through the entire list starting from `head`, using a `while` loop to count the total number of nodes in the list. This count is stored in the variable `count`.\n \n* **Adjusting Count for Removal**: The variable `count` is then decremented by `n`. This adjustment translates the task from "remove the nth node from the end" to "find the (count\u2212n)th node from the beginning".\n \n* **Finding the Predecessor Node**: The method initializes a pointer `prev` to the dummy node and then advances it `count` times through the list. After this loop, `prev` points to the node immediately before the node that needs to be removed.\n \n* **Removing the Node**: The node to be removed is `prev.next`. To remove it, the method sets `prev.next` to `prev.next.next`, effectively bypassing the node to be removed and linking `prev` directly to the node after the one to be removed. This operation does not deallocate the removed node, but it effectively removes it from the list as seen by traversing the list from the dummy head.\n \n* **Returning the New Head**: Finally, the method returns `dummy.next`, which is the new head of the list. If the original head of the list was removed, `dummy.next` now points to the second node, which is the new head. If any other node was removed, the structure of the list is updated accordingly, with the original head still in place.\n\n# Complexity \uD83D\uDC48\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code \uD83D\uDC48\n```C []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\nstruct ListNode* removeNthFromEnd(struct ListNode* head, int n) {\n if(head == NULL || head->next == NULL)return NULL;\n\n struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));\n dummy -> next = head;\n int count = 0;\n\n struct ListNode* iterate = head;\n while(iterate != NULL){\n count++;\n iterate = iterate->next;\n } \n count-=n;\n struct ListNode* prev = dummy; \n for (int i = 0; i < count; i++) {\n prev = prev->next;\n }\n prev->next = prev->next->next;\n return dummy->next;\n}\n```\n```C++ []\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 ListNode* removeNthFromEnd(ListNode* head, int n) {\n if(head == NULL || head->next == NULL)return NULL;\n\n ListNode* dummy = new ListNode(0);\n dummy->next = head;\n int count = 0;\n\n ListNode* iterate = head;\n while(iterate != NULL){\n count++;\n iterate = iterate->next;\n } \n count-=n;\n ListNode* prev = dummy; \n for (int i = 0; i < count; i++) {\n prev = prev->next;\n }\n prev->next = prev->next->next;\n return dummy->next;\n }\n};\n```\n```Java []\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 ListNode removeNthFromEnd(ListNode head, int n) {\n if(head == null || head.next == null)return null;\n\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n int count = 0;\n\n ListNode iterate = head;\n while(iterate != null){\n count++;\n iterate = iterate.next;\n } \n count-=n;\n ListNode prev = dummy; \n for (int i = 0; i < count; i++) {\n prev = prev.next;\n }\n prev.next = prev.next.next;\n return dummy.next;\n }\n}\n```\n```javascript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} n\n * @return {ListNode}\n */\nvar removeNthFromEnd = function(head, n) {\n if(head == null || head.next == null)return null;\n\n dummy = new ListNode(0);\n dummy.next = head;\n let count = 0;\n\n iterate = head;\n while(iterate != null){\n count++;\n iterate = iterate.next;\n } \n count-=n;\n prev = dummy; \n for (let i = 0; i < count; i++) {\n prev = prev.next;\n }\n prev.next = prev.next.next;\n return dummy.next;\n};\n```\n```C# []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public int val;\n * public ListNode next;\n * public ListNode(int val=0, ListNode next=null) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\npublic class Solution {\n public ListNode RemoveNthFromEnd(ListNode head, int n) {\n if(head == null || head.next == null)return null;\n\n ListNode dummy = new ListNode(0);\n dummy.next = head;\n int count = 0;\n\n ListNode iterate = head;\n while(iterate != null){\n count++;\n iterate = iterate.next;\n } \n count-=n;\n ListNode prev = dummy; \n for (int i = 0; i < count; i++) {\n prev = prev.next;\n }\n prev.next = prev.next.next;\n return dummy.next;\n }\n}\n```\n```python []\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n """\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n """\n if head == None or head.next == None: return None\n\n dummy = ListNode(0)\n dummy.next = head\n count = 0\n\n iterate = head\n while iterate != None:\n count+=1\n iterate = iterate.next \n\n count-=n\n prev = dummy\n for i in range(0 , count):\n prev = prev.next\n\n prev.next = prev.next.next\n return dummy.next\n```\n```ruby []\n# Definition for singly-linked list.\n# class ListNode\n# attr_accessor :val, :next\n# def initialize(val = 0, _next = nil)\n# @val = val\n# @next = _next\n# end\n# end\n# @param {ListNode} head\n# @param {Integer} n\n# @return {ListNode}\ndef remove_nth_from_end(head, n)\n if head == nil or head.next == nil \n return nil\n end\n dummy = ListNode.new(0)\n dummy.next = head\n count = 0\n\n iterate = head\n while iterate != nil\n count+=1\n iterate = iterate.next \n end\n count-=n\n prev = dummy\n for a in 1..count do\n prev = prev.next\n end\n\n prev.next = prev.next.next\n return dummy.next\nendus aacha \n```\n\n# Dry Run \uD83D\uDC48\n\n1. **Initialization**:\n \n * The list is `[1,2,3,4,5]`.\n * `n = 2`, meaning we want to remove the 2nd node from the end of the list, which is `4`.\n2. **Dummy Node**:\n \n * A dummy node is created and its `next` is set to point to the head of the list. Now, the list looks like `[dummy,1,2,3,4,5]`.\n3. **Counting Nodes**:\n \n * The method iterates through the list to count the nodes. `count` becomes `5` because there are 5 nodes in the list.\n4. **Adjusting Count for Removal**:\n \n * The method calculates the position to stop before the node to be removed: `count = count - n`, which is `5 - 2 = 3`. This means we need to find the 3rd node from the beginning, which is `3`, to get to its predecessor.\n5. **Finding the Predecessor Node**:\n \n * Starting from the dummy node, the method advances `prev` 3 times. After these iterations, `prev` points to the node `3`.\n6. **Removing the Node**:\n \n * `prev.next` points to `4`, and `prev.next.next` points to `5`. The method sets `prev.next` to `prev.next.next`, which makes `prev.next` point to `5`. Now, the list looks like `[dummy,1,2,3,5]`, effectively removing the `4`.\n7. **Returning the New Head**:\n \n * Finally, the method returns `dummy.next`, which is the head of the new list `[1,2,3,5]`.\n\n# Here\'s a more detailed breakdown of the key steps: \uD83D\uDC48\n\n* **Before Removal**:\n \n * List: `Dummy -> 1 -> 2 -> 3 -> 4 -> 5`\n* **After Counting (`count = 3` after adjustment)**:\n \n * `prev` starts at `Dummy` and moves to `3` after 3 iterations.\n* **Node Removal**:\n \n * Before: `Dummy -> 1 -> 2 -> 3 -> 4 -> 5`\n * After: `Dummy -> 1 -> 2 -> 3 ------> 5`\n* **Result**:\n \n * The final list returned is `[1,2,3,5]`, with the node containing `4` removed.\n\n# Hey Guys if you like the explanation and solution the upvote me.\u2764\uFE0F\u2764\uFE0F\u2764\uFE0F\n
7
0
['Linked List', 'Two Pointers', 'C', 'Python', 'C++', 'Java', 'Python3', 'Ruby', 'JavaScript', 'C#']
1
remove-nth-node-from-end-of-list
[Python] - Two Pointer - Clean & Simple - O(n) Solution
python-two-pointer-clean-simple-on-solut-9jv1
\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
yash_visavadia
NORMAL
2023-02-17T18:51:06.843886+00:00
2023-02-17T18:54:00.993802+00:00
3,945
false
\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 removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n dummy = ListNode()\n dummy.next = head\n\n pnt1, pnt2 = dummy, head\n for _ in range(n):\n pnt2 = pnt2.next\n\n while pnt2:\n pnt1, pnt2 = pnt1.next, pnt2.next\n \n pnt1.next = pnt1.next.next\n return dummy.next\n\n```\n\n## Easy To Understand Solution :\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 removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n trav = head\n size = 0\n while True:\n size += 1\n trav = trav.next\n if trav == None:\n break\n \n if size == 1:\n return None\n \n if size == n:\n return head.next\n \n \n trav = head\n while size != n + 1:# or you can write size - n - 1 != 0 :\n trav = trav.next\n n+=1\n \n trav.next = trav.next.next\n return head\n```
7
0
['Linked List', 'Two Pointers', 'Python3']
1
remove-nth-node-from-end-of-list
Javascript very very easy to understand solution with video explanation!
javascript-very-very-easy-to-understand-4iydu
Here is video for explain if it is helpful please subscribe! :\n\n\n\nhttps://youtu.be/yvYtR-KPD6c\n\n# Code\n\n/**\n * Definition for singly-linked list.\n * f
rlawnsqja850
NORMAL
2023-01-17T01:51:41.312388+00:00
2023-01-17T01:51:41.312415+00:00
2,355
false
Here is video for explain if it is helpful please subscribe! :\n\n\n\nhttps://youtu.be/yvYtR-KPD6c\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} n\n * @return {ListNode}\n */\nvar removeNthFromEnd = function(head, n) {\n let arr = []\n let res = new ListNode()\n let copy = res;\n while(head){\n arr.push(head.val)\n head = head.next;\n }\n for(let i =0; i<arr.length;i++){\n if(arr.length-i == n) continue;\n copy.next = new ListNode(arr[i])\n copy = copy.next;\n }\n return res.next;\n};\n```
7
0
['JavaScript']
0
remove-nth-node-from-end-of-list
[0ms][1LINER][100%][Fastest Solution Explained] O(n)time complexity O(n)space complexity
0ms1liner100fastest-solution-explained-o-sk0w
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\nTake care brother, pe
darian-catalin-cucer
NORMAL
2022-06-08T17:14:19.112293+00:00
2022-06-08T17:14:19.112328+00:00
1,678
false
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, ***please upvote*** this post.)\n***Take care brother, peace, love!***\n\n```\n```\n\nThe best result for the code below is ***0ms / 38.2MB*** (beats 92.04% / 24.00%).\n* *** Kotlin ***\n\n```\n\n/**\n * Example:\n * var li = ListNode(5)\n * var v = li.`val`\n * Definition for singly-linked list.\n * class ListNode(var `val`: Int) {\n * var next: ListNode? = null\n * }\n */\nclass Solution {\n fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {\n if (head == null) return null\n \n var nodeCount = 0\n var current = head\n \n while (current != null) {\n nodeCount++\n current = current.next\n }\n \n if (nodeCount == n) return head.next\n \n var prev: ListNode? = null\n current = head\n val dummy = ListNode(-1)\n dummy.next = current\n \n var step = nodeCount - n\n while (step-- > 0) {\n prev = current\n current = current?.next\n }\n \n prev?.next = current?.next\n \n return dummy.next\n }\n}\n\n```\n\n```\n```\n\n```\n```\n\n***"Open your eyes. Expect us." - \uD835\uDCD0\uD835\uDCF7\uD835\uDCF8\uD835\uDCF7\uD835\uDD02\uD835\uDCF6\uD835\uDCF8\uD835\uDCFE\uD835\uDCFC***
7
2
['C', 'PHP', 'C++', 'Java', 'Kotlin', 'JavaScript']
3
remove-nth-node-from-end-of-list
✔C++ Two Pointer || Easy to Understand || Time O(n) || Space O(1)
c-two-pointer-easy-to-understand-time-on-g6gb
\nPlease Upvote if it helps...!\n\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *slow = head;\n L
iqlipse_abhi
NORMAL
2022-01-09T10:06:03.254311+00:00
2022-01-17T11:12:02.135855+00:00
458
false
![image](https://assets.leetcode.com/users/images/aa9908c4-58aa-4d16-a850-5885515a9064_1642417916.7980297.jpeg)\n**Please Upvote if it helps...!**\n```\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode *slow = head;\n ListNode *fast = head;\n int count = n;\n while(count > 0)\n {\n fast = fast->next;\n count--;\n } \n if(fast == NULL)\n {\n return head->next; // edge case handled\n } \n while(fast->next!=NULL)\n {\n slow=slow->next; \n fast=fast->next;\n }\n slow->next = slow->next->next;\n return head;\n }\n};\n```
7
1
['Two Pointers', 'C']
1
remove-nth-node-from-end-of-list
Java Solution using Two Pointer and in One Pass
java-solution-using-two-pointer-and-in-o-kum6
Idea:- For solving this question in one pass we can use two pointer approach. In this approach we make two pointer and maintain a gap of size n-1 between these
rohit_malangi
NORMAL
2021-09-13T03:00:45.365897+00:00
2021-09-13T03:03:16.705983+00:00
848
false
Idea:- For solving this question in one pass we can use two pointer approach. In this approach we make two pointer and maintain a gap of size n-1 between these two pointers. \nWhen first pointer is at the end of the list we sure that second pointer at n+1 position from end . Now we need only remove nth element with the help of second pointer.\nThe Only edge case is when (n==size of list).\n```\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode p1=head,p2=head;\n while(p1!=null&&p1.next!=null){\n if(n<=0){\n p2=p2.next;\n }\n p1=p1.next;\n --n;\n }\n if(n>0){ // The only edge case removed with this condition\n head=head.next;\n }else{\n p2.next=p2.next.next;\n }\n return head;\n }\n}\n// If you like the code and concept than Please UpVote me :)
7
0
['Two Pointers', 'Java']
0
remove-nth-node-from-end-of-list
0ms, 2.3mb - Readable code
0ms-23mb-readable-code-by-fracasula-r523
\nfunc removeNthFromEnd(head *ListNode, n int) *ListNode {\n\tdummy := &ListNode{Next: head}\n\t// the 2nd pointer will advance only after \n\t// we processed t
fracasula
NORMAL
2021-08-29T08:38:23.375942+00:00
2021-08-29T08:38:23.375972+00:00
453
false
```\nfunc removeNthFromEnd(head *ListNode, n int) *ListNode {\n\tdummy := &ListNode{Next: head}\n\t// the 2nd pointer will advance only after \n\t// we processed the first n nodes\n\tfirst, second := dummy, dummy\n\n\tvar count int\n\tfor first.Next != nil {\n\t\tfirst = first.Next\n\t\t\n\t\tcount++\n\t\tif count > n {\n\t\t\tsecond = second.Next\n\t\t}\n\t}\n\n\tsecond.Next = second.Next.Next\n\n\treturn dummy.Next\n}\n```
7
0
['Go']
2
remove-nth-node-from-end-of-list
simple one pass solution in java | explained | 0ms faster than 100%
simple-one-pass-solution-in-java-explain-mu5h
```\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n // Create two nodes pointing to head;\n var first = head;\n
MrAlpha786
NORMAL
2021-08-01T15:21:23.387389+00:00
2021-08-01T15:21:23.387445+00:00
545
false
```\nclass Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n // Create two nodes pointing to head;\n var first = head;\n var second = head;\n \n // make second node n nodes ahead of first node;\n for (int i =0; i <n; i++)\n second = second.next;\n \n // If second node is null, that mean n == list.size-1;\n // that means we have to remove the head of the list;\n if (second == null)\n return first.next;\n \n // if second node is not null, lets move both first and second nodes\n // until second.next == null;\n // remember after this, first node will n+1 nodes from the end;\n while(second.next != null) {\n first = first.next;\n second = second.next;\n }\n \n // we can easily skip nth node and make first.next point to n.next;\n first.next = first.next.next;\n \n return head;\n }\n}
7
0
['Java']
1
remove-nth-node-from-end-of-list
Clean c solution
clean-c-solution-by-tim37021-n5wn
c\nstruct ListNode* removeNthFromEnd(struct ListNode* head, int n){\n struct ListNode *p=head, *q=head;\n\t// delay by n nodes.\n for(int i=0; i<n; i++) {
tim37021
NORMAL
2020-11-04T06:59:18.717583+00:00
2020-11-04T06:59:18.717654+00:00
622
false
```c\nstruct ListNode* removeNthFromEnd(struct ListNode* head, int n){\n struct ListNode *p=head, *q=head;\n\t// delay by n nodes.\n for(int i=0; i<n; i++) {\n p = p->next;\n }\n if(!p) {\n //remove head\n return head->next;\n }\n\t// pass through\n while(p->next) {\n p = p->next;\n q = q->next;\n }\n q->next = q->next->next;\n return head;\n}\n```\n\nAlthough there are two loop, but it is still a one pass solution.
7
0
[]
2
remove-nth-node-from-end-of-list
Two Pointers: farer than 99.67% memory less than 99.98%
two-pointers-farer-than-9967-memory-less-1597
\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n fast = head\n while n > 0:\n fast = fast.next\
dqdwsdlws
NORMAL
2020-10-28T05:18:55.516007+00:00
2020-10-28T11:00:46.979140+00:00
708
false
```\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n fast = head\n while n > 0:\n fast = fast.next\n n -= 1\n if not fast: return head.next\n slow = head\n while fast.next:\n fast = fast.next\n slow = slow.next\n slow.next = slow.next.next\n return head\n```
7
0
['Python', 'Python3']
2
remove-nth-node-from-end-of-list
Unsafe rust single pass solution
unsafe-rust-single-pass-solution-by-lkrb-2kpm
The fastest solution is to use two pointers, one in front and the other n step back. When the front pointer hits the end of the list, the tail pointer points at
lkrb
NORMAL
2019-05-08T17:58:46.450092+00:00
2019-05-08T17:58:46.450156+00:00
492
false
The fastest solution is to use two pointers, one in front and the other n step back. When the front pointer hits the end of the list, the tail pointer points at the node to remove. So the front pointer can be immutable while the tail one must be mutable. \n\nHowever, we cannot have both an immutable and a mutable reference to the same object in safe rust --- I spent quite some time fighting with the borrow checker and realised this is impossible (correct me if I\'m wrong) --- so the safe rust solution requires two passes: one for the length of list, the other for removing the node.\n\nHere is a solution with unsafe rust which should be the most performant.\n```\nimpl Solution {\n pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {\n unsafe {\n let mut head = head;\n let mut front: *mut Option<Box<ListNode>> = &mut head;\n let mut tail: *mut Option<Box<ListNode>> = &mut head;\n for _ in 0..n {\n front = &mut (*front).as_mut().unwrap().next;\n }\n if (*front).is_none() {\n return head.take().unwrap().next;\n }\n loop {\n front = &mut (*front).as_mut().unwrap().next;\n if (*front).is_none() {\n break;\n }\n tail = &mut (*tail).as_mut().unwrap().next;\n }\n (*tail).as_mut().unwrap().next = (*tail).as_mut().unwrap().next.as_mut().unwrap().next.take();\n head\n }\n }\n}\n```
7
0
[]
0
remove-nth-node-from-end-of-list
Python One Pass
python-one-pass-by-wangqiuc-x31r
Suppose the length of linked list is L, the distance between the node to delete and the tail is |node-tail| = N. Then |node-head| = L-N. So we can use two point
wangqiuc
NORMAL
2019-03-02T21:08:17.176246+00:00
2019-03-02T21:08:17.176296+00:00
951
false
Suppose the length of linked list is L, the distance between the node to delete and the tail is **|node-tail| = N**. Then **|node-head| = L-N**. So we can use two pointers here to get that **L-N**.\n\nPointer **a** first walks N units and there are L-N units left that **a** can walk. Then we have **b** start walking from the head and **a** keep walking simultaneously. \nAfter **L-N** rounds, **a** will reach the tail and **b** has walked L-N from the head, with a distance N away from the tail. So when **a** reaches the tail, we know the node that **b** is pointing at is what to delete.\n\nIn case the head node is what to delete, we can create a dummy head whose next node is the **head**. Then we have both a and b point at the dummy and eventually return **dummy.next**.\n```\ndef removeNthFromEnd(head, n):\n\ta = b = dummy = ListNode(0)\n\tdummy.next = head\n\tfor _ in range(n): \n\t\ta = a.next\n\twhile a.next: \n\t\ta, b = a.next, b.next\n\tb.next = b.next.next\n\treturn dummy.next\n```\nIt\'s a one pass O(n) time O(1) space solution.
7
0
[]
3
remove-nth-node-from-end-of-list
Rust 0 ms solution
rust-0-ms-solution-by-aleihanami-opwm
rust\nimpl Solution {\n pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {\n let mut dummy_head = Some(Box::ne
aleihanami
NORMAL
2019-01-17T15:50:54.753577+00:00
2019-01-17T15:50:54.753643+00:00
702
false
```rust\nimpl Solution {\n pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {\n let mut dummy_head = Some(Box::new(ListNode {\n val: 0, next: head,\n }));\n let mut len = 0;\n {\n let mut p = dummy_head.as_ref();\n while p.unwrap().next.is_some() {\n len += 1;\n p = p.unwrap().next.as_ref();\n }\n }\n let idx = len - n;\n {\n let mut p = dummy_head.as_mut();\n for _ in 0..(idx) {\n p = p.unwrap().next.as_mut();\n }\n let next = p.as_mut().unwrap().next.as_mut().unwrap().next.take();\n p.as_mut().unwrap().next = next;\n }\n dummy_head.unwrap().next\n }\n}\n```\nAfter hours figting with borrow checker, I think the "One Pass" algorithm cannot be written in Rust without `unsafe`. \nBut actually the two pass solution is just as fast as one pass solution (times of moving pointer should be same), so just take it.
7
0
[]
1
longest-substring-of-all-vowels-in-order
Best C++ Solution
best-c-solution-by-6cdh-utju
The basic idea is \'a\' < \'e\' < \'i\' < \'o\' < \'u\'. So this problem is to find the length of the longest non-decreasing substring that has five different c
6cdh
NORMAL
2021-04-25T04:25:45.735335+00:00
2021-04-25T04:25:45.735409+00:00
6,671
false
The basic idea is `\'a\' < \'e\' < \'i\' < \'o\' < \'u\'`. So this problem is to find the length of the longest non-decreasing substring that has five different chars.\n\n```c++\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n const auto n = word.size();\n\n int cnt = 1;\n int len = 1;\n int max_len = 0;\n for (int i = 1; i != n; ++i) {\n if (word[i - 1] == word[i]) {\n ++len;\n } else if (word[i - 1] < word[i]) {\n ++len;\n ++cnt;\n } else {\n cnt = 1;\n len = 1;\n }\n \n if (cnt == 5) {\n max_len = max(max_len, len);\n }\n }\n return max_len;\n }\n};\n```
217
1
['C']
21
longest-substring-of-all-vowels-in-order
[Java/Python 3] Sliding window codes, w/ brief explanation and analysis.
javapython-3-sliding-window-codes-w-brie-ledd
Loop through input string and maintain a sliding window to fit in beautiful substrings;\n2. Use a Set seen to check the number of distinct vowels in the sliding
rock
NORMAL
2021-04-25T04:12:34.337466+00:00
2021-04-25T18:22:01.277011+00:00
4,927
false
1. Loop through input string and maintain a sliding window to fit in beautiful substrings;\n2. Use a Set `seen` to check the number of distinct vowels in the sliding window;\n3. Whenever adjacent letters is not in alpahbetic order, start a new window and new Set;\n4. For each iteration of the loop, add the correponding char and check the size of the Set `seen`; If the size reaches `5`, update the longest length;\n5. Return the longest length after the termination of the loop.\n\n```java\n public int longestBeautifulSubstring(String word) {\n int longest = 0;\n Set<Character> seen = new HashSet<>();\n for (int lo = -1, hi = 0; hi < word.length(); ++hi) {\n if (hi > 0 && word.charAt(hi - 1) > word.charAt(hi)) {\n seen = new HashSet<>();\n lo = hi - 1;\n }\n seen.add(word.charAt(hi));\n if (seen.size() == 5) {\n longest = Math.max(longest, hi - lo);\n }\n }\n return longest;\n }\n```\nCredit to **@MtDeity**, who improve the following Python 3 code. \n```python\n def longestBeautifulSubstring(self, word: str) -> int:\n seen = set()\n lo, longest = -1, 0\n for hi, c in enumerate(word):\n if hi > 0 and c < word[hi - 1]:\n seen = set()\n lo = hi - 1 \n seen.add(c) \n if len(seen) == 5:\n longest = max(longest, hi - lo)\n return longest\n```\n\n**Analysis:**\n\nThere are at most `5` characters in Set `seen`, which cost space `O(1)`. Therefore, \nTime: `O(n)`, space: `O(1)`
58
0
[]
8
longest-substring-of-all-vowels-in-order
Java Simple
java-simple-by-vikrant_pc-00x8
\npublic int longestBeautifulSubstring(String word) {\n\tint result = 0, currentLength = 0, vowelCount = 0;\n\tfor(int i=0;i<word.length();i++) {\n\t\tif(i!=0 &
vikrant_pc
NORMAL
2021-04-25T04:01:40.241758+00:00
2021-04-30T04:45:08.238400+00:00
2,273
false
```\npublic int longestBeautifulSubstring(String word) {\n\tint result = 0, currentLength = 0, vowelCount = 0;\n\tfor(int i=0;i<word.length();i++) {\n\t\tif(i!=0 && word.charAt(i) < word.charAt(i-1)) {\n\t\t\tvowelCount = 0;\n\t\t\tcurrentLength = 0;\n\t\t}\n\t\tcurrentLength++;\n\t\tif(i==0 || word.charAt(i) != word.charAt(i-1)) vowelCount++;\n\t\tif(vowelCount == 5) result = Math.max(result, currentLength);\n\t}\n\treturn result;\n}\n```
36
3
[]
6
longest-substring-of-all-vowels-in-order
JAVA READABLE CODE || Constant Space
java-readable-code-constant-space-by-him-eip2
Idea:\n Given word only contains vowels(given in question) and we just have to find out the longest substring that contains all vowels in sorted order of ascii
himanshuchhikara
NORMAL
2021-04-25T10:13:17.836288+00:00
2021-04-30T12:44:01.065666+00:00
1,791
false
**Idea:**\n Given word only contains vowels(given in question) and we just have to find out the longest substring that contains all vowels in sorted order of ascii value. i.e \'a\'<\'e\'<\'i\'<\'o\'<\'u\' .\n So if a substring have 5 unique character and following ascii order we can update our answer by its length.\n**CODE:**\n```\n public int longestBeautifulSubstring(String word) {\n int cnt=1;\n int len=1;\n int max_length=0;\n \n int n=word.length();\n \n for(int i=1;i<n;i++){\n if(word.charAt(i)==word.charAt(i-1)){\n len++;\n }else if(word.charAt(i-1)<word.charAt(i)){\n cnt++;\n len++;\n }else{\n len=1;\n cnt=1;\n }\n \n if(cnt==5){\n max_length=Math.max(max_length,len);\n }\n }\n return max_length;\n }\n```\t\n\n**Complexity:**\n`Time:O(n) and Space:O(1)`\n
28
1
['Java']
4
longest-substring-of-all-vowels-in-order
C++ O(n)
c-on-by-votrubac-4evh
cpp\nint longestBeautifulSubstring(string w) {\n int res = 0;\n for (int i = 0, j = 0; i < w.size(); ++i) {\n if (w[i] == \'a\') {\n int
votrubac
NORMAL
2021-04-25T04:20:45.906032+00:00
2021-04-25T06:58:20.087431+00:00
2,387
false
```cpp\nint longestBeautifulSubstring(string w) {\n int res = 0;\n for (int i = 0, j = 0; i < w.size(); ++i) {\n if (w[i] == \'a\') {\n int cnt = 0;\n for (j = i + 1; j < w.size() && w[j - 1] <= w[j]; ++j)\n cnt += w[j - 1] < w[j];\n if (cnt == 4)\n res = max(res, j - i);\n i = j - 1;\n }\n }\n return res;\n}\n```
27
2
[]
3
longest-substring-of-all-vowels-in-order
Just 7 lines of code || Easiest Solution
just-7-lines-of-code-easiest-solution-by-5xb4
Approach\n Describe your approach to solving the problem. \nTwo Pointer Approach: \n\n count variable is looking for the all vowels in current substring window.
ha_vi_ag-
NORMAL
2023-02-06T06:47:41.444219+00:00
2023-02-06T06:47:41.444246+00:00
1,054
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n**Two Pointer Approach**: \n\n* **count** variable is looking for the all vowels in current substring window.\n* The idea behind **count** variable is, it counts all the **"<"** operations. if it equals 5 it implies we got all the vowels.\n* if sorted sequence breaks we reset our first pointer **"p"** as well as **count** variable i.e. we reset our current window.\n\n\n# Complexity\n- Time complexity: **O(n)**\n\n- Space complexity: **O(1)**\n\n# Code\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int ans = 0, p = 0, count = 1;\n \n for(int i = 1; i < word.length(); i++) {\n\n if(word[i-1] < word[i]) count++;\n \n else if(word[i-1] > word[i])\n p = i, count = 1;\n \n if(count == 5) ans = max(ans,i-p+1);\n }\n\n return ans;\n }\n};\n```
18
0
['Sliding Window', 'C++']
1
longest-substring-of-all-vowels-in-order
[Python3] greedy
python3-greedy-by-ye15-auyj
\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = "aeiou"\n ans = 0\n cnt = prev = -1 \n fo
ye15
NORMAL
2021-04-25T04:01:33.584725+00:00
2021-04-25T16:04:49.642098+00:00
1,734
false
\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = "aeiou"\n ans = 0\n cnt = prev = -1 \n for i, x in enumerate(word): \n curr = vowels.index(x)\n if cnt >= 0: # in the middle of counting \n if 0 <= curr - prev <= 1: \n cnt += 1\n if x == "u": ans = max(ans, cnt)\n elif x == "a": cnt = 1\n else: cnt = -1 \n elif x == "a": cnt = 1\n prev = curr \n return ans \n```\n\nAlternative implementations\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n ans = 0\n cnt = unique = 1\n for i in range(1, len(word)): \n if word[i-1] <= word[i]: \n cnt += 1\n if word[i-1] < word[i]: unique += 1\n else: cnt = unique = 1\n if unique == 5: ans = max(ans, cnt)\n return ans \n```\n\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n ans = ii = 0\n unique = 1\n for i in range(1, len(word)): \n if word[i-1] > word[i]: \n ii = i \n unique = 1\n elif word[i-1] < word[i]: unique += 1\n if unique == 5: ans = max(ans, i-ii+1)\n return ans \n```
11
0
['Python3']
2
longest-substring-of-all-vowels-in-order
C++ Solution using Stack
c-solution-using-stack-by-krishnam1998gk-o3fd
Below is the solution using stack. I will explain each and every step of my logic\n1. It is obvious that if the length of the string is smaller than 5 the answe
krishnam1998gkp
NORMAL
2021-04-25T04:42:24.027698+00:00
2021-04-25T04:42:24.027730+00:00
566
false
Below is the solution using stack. I will explain each and every step of my logic\n1. It is obvious that if the length of the string is smaller than **5** the answer is **0**.\n2. Initialising all the variables and stack of characters\n```\n\tstack<char> st;\n\tint i=0,j=0,count=0,ans=INT_MIN,f=0;\n```\n3.We run a while loop until `i<word.size();`\n4.Now we know that the first letter of the substring has to be \'a\'.So, we check if stack is empty and `word[i]==\'a\'` then push it into the stack otherwise we just move ahead.The first line inside the block of the loop shows this.\n```\nif(st.empty()&&word[i]!=\'a\')i++;\n```\n5.Now if `word[i]==\'a\'` and stack is empty or `st.top()==\'a\'` we push `word[i]` in the stack and increase the count by 1.\n6.We have to keep in mind that if `word[i]==\'a\'` then `st.top()==\'a\'||st.empty()`.\n If this is not the case then we pop out each and every element from the stack and repeat the process again.\n7.Simarily for `word[i]==\'e\'` `st.top()==\'a\'||st.top==\'e\'` and `word[i]==\'i\'` `st.top()==\'e\'||st.top()==\'i\'`and so on.\n8. When we reach `word[i]==\'u\'`. `if(st.top()==\'o\'||st.top()==\'u\')` we increase the count by 1 and `ans = max(ans,count)`.Also one has to keep in mind that substring should contain atleast one occurrence of each and every vowel in the substring .To check if this we use a flag variable `f` whose initial value is zero.When it reaches the above mentioned if block we make `f=1`.\n9. Out of the block of loop we check `if(f==0)`.If it is true then the answer is zero as there is no occurrence of u in the substring.Else the answer becomes answer.\nThe entire code is given below:\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n if(word.size()<5)return 0;\n stack<char> st;\n int i=0,j=0,count=0,ans=INT_MIN,f=0;//here f is the flag variable\n while(i<word.size()){\n if(st.empty()&&word[i]!=\'a\')i++;//checks if the first letter of the substring is \'a\'\n else if(word[i]==\'a\'){\n if(st.empty()||st.top()==\'a\'){\n st.push(word[i]);\n count++;\n i++;\n }\n else{\n while(!st.empty()){\n st.pop();\n }\n count=0;\n }\n }\n else if(word[i]==\'e\'){\n if(st.top()==\'a\'||st.top()==\'e\'){\n st.push(word[i]);\n count++;\n ans=max(ans,count);\n i++;\n }\n else{\n while(!st.empty()){\n st.pop();\n }\n count=0;\n }\n }\n else if(word[i]==\'i\'){\n if(st.top()==\'e\'||st.top()==\'i\'){\n st.push(word[i]);\n count++;\n i++;\n }\n else{\n while(!st.empty()){\n st.pop();\n }\n count=0;\n }\n }\n else if(word[i]==\'o\'){\n if(st.top()==\'i\'||st.top()==\'o\'){\n st.push(word[i]);\n count++;\n i++;\n }\n else{\n while(!st.empty()){\n st.pop();\n }\n count=0;\n }\n }\n else if(word[i]==\'u\'){\n if(st.top()==\'o\'||st.top()==\'u\'){\n st.push(word[i]);\n count++;\n ans=max(count,ans);\n i++;\n f=1;//f becomes 1 if this block is reached conforming that there is an occurence of every vowel in the substring\n }\n else{\n while(!st.empty()){\n st.pop();\n }\n count=0;\n }\n }\n }\n if(f==0)return 0;//every vowel doesn\'t appear in the substring so answer is zero\n return ans;//maximum length of the substring\n }\n};\n```\nFeel free to check this out.Ignore the grammatical mistakes. Comment if any doubt.\n
10
1
[]
5
longest-substring-of-all-vowels-in-order
Simple solution || Easy to understand || Explained !!
simple-solution-easy-to-understand-expla-ah03
The idea is simple,we use two pointers to find the length of longest substring.\nInitially i=0,j=1;\n-> whenever we find word[j]<word[j-1], we check whether all
srinivasteja18
NORMAL
2021-04-25T04:27:48.752597+00:00
2021-04-25T04:27:48.752634+00:00
727
false
The idea is simple,we use two pointers to find the length of longest substring.\nInitially i=0,j=1;\n-> whenever we find `word[j]<word[j-1]`, we check whether all chars in `"aeiou`" present in substring `j-i`, we use map to find that.\n-> If ` m.size() ==5` then we update the `maxi` which is longest substring and update the `i = j`.\n-> If `m.size()!=5`, then the substring doesn\'t contain all chars in `"aeiou"`, we just update` i=j.`\nFinally retuen `maxi.`\n\n**DO UPVOTE if you find it helpful !!**\n```\nint longestBeautifulSubstring(string word) {\n int maxi =0;\n int i=0,j=1;\n map<char,int>m;\n m[word[0]]++;\n while(j<word.length()){\n if(word[j] < word[j-1]){\n if(m.size() == 5)\n maxi = max(maxi, j-i);\n i = j;\n m.clear();\n }\n m[word[j]]++;\n j++;\n }\n if(m.size() == 5)\n maxi = max(maxi,j-i);\n return maxi;\n }\n```
10
1
['C']
0
longest-substring-of-all-vowels-in-order
[Python3] 98% Fast Solution
python3-98-fast-solution-by-voidcupboard-b9dk
\nfrom itertools import groupby\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n arr = groupby(word)\n \n a
VoidCupboard
NORMAL
2021-05-28T13:39:38.533622+00:00
2021-05-28T13:39:38.533667+00:00
1,235
false
```\nfrom itertools import groupby\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n arr = groupby(word)\n \n ans = []\n \n count = 0\n \n for i , j in arr:\n ans.append([i , list(j)])\n \n for i in range(len(ans) - 4):\n if(ans[i][0] == \'a\' and ans[i + 1][0] == \'e\' and ans[i + 2][0] == \'i\' and ans[i + 3][0] == \'o\' and ans[i + 4][0] == \'u\'):\n count = max(count , len(ans[i][1]) + len(ans[i + 1][1]) + len(ans[i + 2][1]) + len(ans[i + 3][1]) + len(ans[i + 4][1])) \n \n \n return count\n```
9
0
['Python3']
0
longest-substring-of-all-vowels-in-order
Easy understanding | Brute Force | No extra space | Simple c++
easy-understanding-brute-force-no-extra-51mo9
C++ solution:\n\nclass Solution {\npublic:\n \n int longestBeautifulSubstring(string s) {\n int n=s.size();\n int ans=0;\n for(int i=
millenniumdart09
NORMAL
2021-04-25T04:12:17.964250+00:00
2021-04-25T04:30:47.777746+00:00
552
false
**C++ solution:**\n```\nclass Solution {\npublic:\n \n int longestBeautifulSubstring(string s) {\n int n=s.size();\n int ans=0;\n for(int i=0;i<n;)\n {\n if(s[i]==\'a\')\n {\n int c=1;\n int count=0;\n while(i<n&&s[i]==\'a\')\n {\n count++;\n i++;\n }\n //cout<<"a "<<count<<endl;\n if(i<n&&s[i]==\'e\')\n {\n c++;\n while(i<n&&s[i]==\'e\')\n {\n count++;\n i++;\n }\n // cout<<"e "<<count<<endl;\n if(i<n&&s[i]==\'i\')\n {\n c++;\n //count++;\n while(i<n&&s[i]==\'i\')\n {\n count++;\n i++;\n }\n // cout<<"i "<<count<<endl;\n if(i<n&&s[i]==\'o\')\n {\n c++;\n //count++;\n while(i<n&&s[i]==\'o\')\n {\n count++;i++;\n }\n //cout<<"o "<<count<<endl;\n if(i<n&&s[i]==\'u\')\n {\n c++;\n c=5;\n //count++;\n while(i<n&&s[i]==\'u\')\n {\n count++;\n i++;\n }\n\n }\n //cout<<"u "<<count<<endl;\n\n }\n }\n }\n \n if(c==5)\n {\n ans=max(ans,count);\n }\n \n }\n else\n i++;\n }\n return ans;\n }\n};\n```
7
3
['C']
2
longest-substring-of-all-vowels-in-order
C++ | Easy to understand | Time Complexity - O(N) | Space Complexity - O(1)
c-easy-to-understand-time-complexity-on-cdfum
\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int n = word.length();\n \n int i = 0;\n int ans =
CPP_Bot
NORMAL
2022-08-11T19:06:54.583240+00:00
2022-08-11T19:06:54.583267+00:00
596
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int n = word.length();\n \n int i = 0;\n int ans = 0;\n \n while(i<n){\n int ac = 0;\n int ec = 0;\n int ic = 0;\n int oc = 0;\n int uc = 0;\n \n while(i<n && word[i]==\'a\'){\n ac++;\n i++;\n }\n \n while(i<n && word[i]==\'e\'){\n ec++;\n i++;\n }\n \n while(i<n && word[i]==\'i\'){\n ic++;\n i++;\n }\n \n while(i<n && word[i]==\'o\'){\n oc++;\n i++;\n }\n \n while(i<n && word[i]==\'u\'){\n uc++;\n i++;\n }\n \n if(ac>0 && ec>0 && ic>0 && oc>0 && uc>0){\n ans = max(ans, ac+ec+ic+oc+uc);\n }\n }\n \n return ans;\n }\n};\n```
6
0
[]
2
longest-substring-of-all-vowels-in-order
Straightforward Python3 O(n) stack solution with explanations
straightforward-python3-on-stack-solutio-1ebq
\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n d = {}\n d[\'a\'] = {\'a\', \'e\'}\n d[\'e\'] = {\'e\', \'i
tkuo-tkuo
NORMAL
2021-04-25T07:07:34.230066+00:00
2021-04-28T13:35:48.432726+00:00
848
false
```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n d = {}\n d[\'a\'] = {\'a\', \'e\'}\n d[\'e\'] = {\'e\', \'i\'}\n d[\'i\'] = {\'i\', \'o\'}\n d[\'o\'] = {\'o\', \'u\'}\n d[\'u\'] = {\'u\'}\n\t\t\n res, stack = 0, []\n for c in word: \n # If stack is empty, the first char must be \'a\'\n if len(stack) == 0:\n if c == \'a\':\n stack.append(c)\n continue \n \n # If stack is NOT empty,\n # input char should be the same or subsequent to the last char in stack\n # e.g., last char in stack is \'a\', next char should be \'a\' or \'e\'\n # e.g., last char in stack is \'e\', next char should be \'e\' or \'i\'\n # ...\n # e.g., last char in stack is \'u\', next char should be \'u\'\n if c in d[stack[-1]]:\n stack.append(c)\n # If the last char in stack is eventually \'u\', \n # then we have one beautiful substring as candidate, \n # where we record and update max length of beautiful substring (res)\n if c == \'u\':\n res = max(res, len(stack))\n else:\n stack = [] if c != \'a\' else [\'a\']\n \n return res\n```
6
0
['Stack', 'Python3']
2
longest-substring-of-all-vowels-in-order
Java O(n) solution, simple to understand
java-on-solution-simple-to-understand-by-t0we
public int longestBeautifulSubstring(String word) {\n \n int max = 0;\n int count = 1, i = 0, j = 1;\n \n while(j < word.leng
ankit03jangra
NORMAL
2021-05-24T17:35:26.808268+00:00
2021-05-24T17:35:26.808307+00:00
400
false
public int longestBeautifulSubstring(String word) {\n \n int max = 0;\n int count = 1, i = 0, j = 1;\n \n while(j < word.length()){\n \n if(word.charAt(j) < word.charAt(j-1)){\n i = j; \n count = 1;\n }\n \n else if(word.charAt(j) != word.charAt(j-1))\n count++;\n \n if(count==5)\n max = Math.max(max, j-i+1); \n \n j++;\n }\n return max;\n }\n\t\n\tPlease upvote if you find it simple to understand
5
0
['Sliding Window', 'Java']
1
longest-substring-of-all-vowels-in-order
[JAVA] [O(n)]
java-on-by-trevor-akshay-gtlv
```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int max = 0;\n for(int i = 1;i<word.length();i++){\n int temp
trevor-akshay
NORMAL
2021-04-29T15:32:27.829798+00:00
2021-04-29T15:32:27.829828+00:00
533
false
```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int max = 0;\n for(int i = 1;i<word.length();i++){\n int temp = 1;\n Set<Character> verify = new HashSet<>();\n verify.add(word.charAt(i-1));\n while(i < word.length() && word.charAt(i) >= word.charAt(i-1)){\n temp++;\n verify.add(word.charAt(i));\n i++;\n }\n max = verify.size() == 5 ? Math.max(max,temp) : max ;\n }\n\n return max;\n }\n}
5
0
['Java']
0
longest-substring-of-all-vowels-in-order
[Java] Straight Forward Intuitive Solution -explained
java-straight-forward-intuitive-solution-oh59
\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int result = 0; \n int start = 0;\n int n = word.length();\n
vinsinin
NORMAL
2021-04-25T04:24:05.613195+00:00
2021-04-25T19:13:45.920648+00:00
539
false
```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int result = 0; \n int start = 0;\n int n = word.length();\n String vowels = "aeiou";\n int v = vowels.length();\n \n if (n < v) return 0; //if the word length is less than that of the actual vowel length return 0\n \n while (start < n){ //run loop until the start pointer reaches end\n int end = start; // end is the start to begin with\n int k = 0; //pointer to track vowel\n\t\t\t//loop until if end is less than the word length and the character at end is equal to \n\t\t\t// the character at k in vowel\n while (end < n && k < vowels.length() && word.charAt(end) == vowels.charAt(k)){\n while(end < n && word.charAt(end) == vowels.charAt(k)) end++; //to handle repetition after matching\n k++;\n }\n\t\t\t// record the max length each time\n if (k == v) result = Math.max(result, end - start);\n start = end; //start is moved to the current end pointer\n // increment start to next position of \'a\'\n\t\t\twhile (start < n && word.charAt(start) != \'a\') start++;\n }\n return result;\n }\n}\n```
5
0
['Java']
1
longest-substring-of-all-vowels-in-order
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-1lzf
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n int longestBeautifulSubstring(string s) \n {\n string
shishirRsiam
NORMAL
2024-06-15T06:28:13.410802+00:00
2024-06-15T06:28:13.410830+00:00
440
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string s) \n {\n string need = "aeiou";\n int ans = 0, n = s.size();\n int i = 0, j = 0, cur = 0;\n while(j<n)\n {\n if(s[j] == need[cur])\n {\n while(s[j] == need[cur]) j++;\n cur++;\n if(cur == 5) ans = max(ans, j-i);\n }\n else \n {\n cur = 0;\n while(j < n and s[j] != need[cur]) j++;\n i = j;\n }\n }\n return ans;\n }\n};\n```
4
0
['String', 'Greedy', 'Sliding Window', 'C++']
3
longest-substring-of-all-vowels-in-order
70 ms Runtime Solution - C++
70-ms-runtime-solution-c-by-day_tripper-4jg4
\nclass Solution {\npublic:\n int longestBeautifulSubstring(string w) {\n int res = 0, j = 0;\n for (int i = 0; i < w.size(); ++i) {\n if (w[i] =
Day_Tripper
NORMAL
2022-08-29T17:58:50.938399+00:00
2022-08-29T17:58:50.938461+00:00
512
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string w) {\n int res = 0, j = 0;\n for (int i = 0; i < w.size(); ++i) {\n if (w[i] == \'a\') {\n int cnt = 0;\n for (j = i + 1; j < w.size() && w[j - 1] <= w[j]; ++j)\n cnt += w[j - 1] < w[j];\n if (cnt == 4)\n res = max(res, j - i);\n i = j - 1;\n }\n }\n return res;\n}\n};\n```
4
0
['String']
0
longest-substring-of-all-vowels-in-order
Avoiding Regular Expression (Regex) Worst Case
avoiding-regular-expression-regex-worst-om01e
The "obvious" regular-expression-based solution for this problem (a+e+i+o+u+) will have quadratic performance on a string of all "a"s.\n\nThis is due to the beh
user9084vW
NORMAL
2021-09-15T22:47:38.444733+00:00
2021-09-15T22:47:38.444764+00:00
197
false
The "obvious" regular-expression-based solution for this problem (`a+e+i+o+u+`) will have quadratic performance on a string of all "a"s.\n\nThis is due to the behavior of regular expression matchers. It will start at the first character, attempt to make a match, and scan to the end of the string to discover that no match exists. It will then start at the second character and try again, then the third, etc.\n\nThis behavior can be circumvented by exploiting the fact that most regular expression matchers do not allow overlapping matches. That means if the regex is "loosened" so that strings of "a"s are always considered a match, the matcher won\'t try each character individually.\n\nThe regex to use is `(a+)(e+i+o+u+)?`. You then simply have to filter away all matches that don\'t have the optional second group.(Alternatively, if you\'re clever you can use non-capturing groups and check that the last character is a `u`).\n\nHere is an example in Python:\n\n```\nimport re\n\ndef longestBeautifulSubstring(self, word: str) -> int:\n if len(word) < 5:\n return 0\n\n lengths = [len(a) + len(opt) for (a, opt) in re.findall(r\'(a+)(e+i+o+u+)?\', word) if opt]\n return max(lengths) if lengths else 0\n```
4
0
[]
0
longest-substring-of-all-vowels-in-order
Easy C++ Single Pass Approach
easy-c-single-pass-approach-by-piyushbis-iwy5
We are going to store last vowel occured,number of unique vowels,the global max for string length, and local max for string length.\nAt each iteration we will c
piyushbisht3
NORMAL
2021-07-25T07:06:47.757514+00:00
2021-07-25T07:06:47.757542+00:00
430
false
We are going to store **last vowel occured,number of unique vowels,the global max for string length, and local max for string length.**\nAt each iteration we will check for three cases:\n1. Is incoming vowel equal to the previous vowel stored\n\t* We just increment the local max length of the string. \n\n2. if incoming vowel is greater than the previous vowel stored\n\t* We increment the local max length ,and update the previous vowel index as well as unique vowel index\n\n3. is incoming vowel if smaller than the previous vowel stored\n\t* We reset the local max length,unique vowels index as well as previous vowel index.\n\nAt the end of each iteration we check if number of unique vowels encountered is 5 ,we then update the global max length of the string. \t\n\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n\n int lastVow=-1;\n int uniqueVows=0;\n int maxString=0;\n int currLen=0;\n int n=word.size();\n \n for(int i=0;i<n;i++)\n {\n if(lastVow==word[i]) //if same vowels occur\n {\n currLen++;\n }\n else if(lastVow<word[i]) //check if new Vowel is greater than lastone\n {\n lastVow=word[i];\n uniqueVows++;\n currLen++;\n }\n else //if smaller vowel occur\n {\n currLen=1;\n uniqueVows=1;\n lastVow=word[i];\n }\n if(uniqueVows==5) //if all vowels occur once\n maxString=max(maxString,currLen);\n }\n return maxString;\n \n \n }\n};\n```
4
0
['C']
1
longest-substring-of-all-vowels-in-order
C++ | (Two pointers) | (Simple and elegant)
c-two-pointers-simple-and-elegant-by-gee-oma0
PLz do upvote if you find it helpful!!!!\nMaintain two pointers left and right and a map.\nNow we will move on to the right freely,also put elements into the ma
GeekyBits
NORMAL
2021-05-17T13:02:23.294069+00:00
2022-02-17T08:20:33.560883+00:00
166
false
PLz do upvote if you find it helpful!!!!\nMaintain two pointers left and right and a map.\nNow we will move on to the right freely,also put elements into the map as we move on the way until: we find a vowel which precedes the previous letter in the alphabet.\nIf that happens we will check the map size first,if its 5 we will store it in a temporary result \nthen,we will clear the map(dont forget to do this)\nand after that we will move the left pointer till it reaches the right pointer.\n\nthen the same steps are repeated again.\n\nbe careful to check the map once again after a complete traversal.\n//see the second test case carefully\n\n\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string s) {\n int left=0;\n int right=0;\n int res=0;\n map<char,int> m;\n int n=s.length();\n while(right<n){ \n if(right>0 and ((int)(s[right]-\'a\')<(int)(s[right-1]-\'a\'))){\n if(m.size()==5){ // a probable result has arrived\n res=max(res,right-left);\n }\n \n m.clear();\n while(left!=right){\n left++;\n } \n }\n m[s[right]]++;\n right++;\n }\n if(m.size()==5){ //the last right to left pointer\n res=max(res,right-left);\n }\n return res;\n }\n};\n```\n\nIf you found this useful,plz upvote!!!!\nKEEP CODING!!
4
1
[]
0
longest-substring-of-all-vowels-in-order
A few solutions
a-few-solutions-by-claytonjwong-z1rx
Kotlin\n\nclass Solution {\n fun longestBeautifulSubstring(s: String): Int {\n var best = 0\n var last = \'x\'\n var start = 0\n
claytonjwong
NORMAL
2021-04-25T04:01:55.817092+00:00
2021-04-25T04:52:15.597180+00:00
281
false
*Kotlin*\n```\nclass Solution {\n fun longestBeautifulSubstring(s: String): Int {\n var best = 0\n var last = \'x\'\n var start = 0\n var seen = mutableSetOf<Char>()\n for (i in 0 until s.length) {\n if (s[i] < last) { // \uD83D\uDEAB violation to lexicographically non-decreasing\n seen.clear()\n start = i\n }\n seen.add(s[i]); last = s[i]\n if (seen.size == 5) // \uD83D\uDC40 all 5 vowels\n best = Math.max(best, i - start + 1) // \uD83C\uDFAF +1 for start..i inclusive\n }\n return best\n }\n}\n```\n\n*Javascript*\n```\nlet longestBeautifulSubstring = (s, start = 0, last = \'x\', seen = new Set(), best = 0) => {\n s.split(\'\').forEach((c, i) => {\n if (c < last) // \uD83D\uDEAB violation to lexicographically non-decreasing\n seen.clear(), start = i;\n seen.add(c), last = c;\n if (seen.size == 5) // \uD83D\uDC40 all 5 vowels\n best = Math.max(best, i - start + 1); // \uD83C\uDFAF +1 for start..i inclusive\n });\n return best;\n};\n```\n\n*Python3*\n```\nclass Solution:\n def longestBeautifulSubstring(self, s: str, last = \'x\', start = 0, best = 0) -> int:\n seen = set()\n for i, c in enumerate(s):\n if c < last: # \uD83D\uDEAB violation to lexicographically non-decreasing\n seen.clear()\n start = i\n seen.add(c)\n last = c\n if len(seen) == 5: # \uD83D\uDC40 all vowels\n best = max(best, i - start + 1) # \uD83C\uDFAF +1 for start..i inclusive\n return best\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using Set = unordered_set<char>;\n int longestBeautifulSubstring(string s, int start = 0, char last = \'x\', Set seen = {}, int best = 0) {\n for (auto i{ 0 }; i < s.size(); ++i) {\n if (s[i] < last) // \uD83D\uDEAB violation to lexicographically non-decreasing\n seen.clear(), start = i;\n seen.insert(s[i]), last = s[i];\n if (seen.size() == 5) // \uD83D\uDC40 all vowels\n best = max(best, i - start + 1); // \uD83C\uDFAF +1 for start..i inclusive\n }\n return best;\n }\n};\n```
4
0
[]
1
longest-substring-of-all-vowels-in-order
❇ longest-substring-of-all-vowels-in-order👌 🏆O(N)❤️ Javascript🎯 Memory👀95.45%🕕 ++Explanation✍️
longest-substring-of-all-vowels-in-order-x6d7
\n\nTime Complexity: O(N)\nSpace Complexity: O(1)\n\n\nvar longestBeautifulSubstring = function (word) {\n const pattern = [\'a\', \'e\', \'i\', \'o\', \'u\'
anurag-sindhu
NORMAL
2024-05-18T17:36:16.674693+00:00
2024-05-18T17:37:43.868971+00:00
110
false
![image](https://assets.leetcode.com/users/images/b9ecc654-8dbb-4ae1-b036-808c1a960f31_1716053604.2757008.png)\n\nTime Complexity: O(N)\nSpace Complexity: O(1)\n\n```\nvar longestBeautifulSubstring = function (word) {\n const pattern = [\'a\', \'e\', \'i\', \'o\', \'u\'];\n let patternIndex = 0;\n let output = 0;\n let startPatternIndex = null;\n let index = 0;\n for (index = 0; index < word.length; index++) {\n const element = word[index];\n if (patternIndex === 4 && element === pattern[patternIndex]) {\n if (element === pattern[pattern.length - 1]) {\n const size = index - startPatternIndex + 1;\n output = Math.max(output, size);\n }\n } else if (element === pattern[patternIndex]) {\n if (startPatternIndex === null) {\n startPatternIndex = index;\n }\n patternIndex += 1;\n } else if (word[index] === word[index - 1]) {\n continue;\n } else {\n patternIndex = 0;\n startPatternIndex = null;\n if (element === pattern[patternIndex] || element === pattern[patternIndex - 1]) {\n startPatternIndex = index;\n patternIndex += 1;\n }\n }\n }\n if (startPatternIndex !== null && patternIndex === 4) {\n const size = index - startPatternIndex;\n output = Math.max(output, size);\n }\n return output;\n};\n```
3
0
['JavaScript']
0
longest-substring-of-all-vowels-in-order
C++✅✅ | Faster🚀 than 90%🔥| A TRICK TO HANDLE ORDERING👌| Sliding Window🆗 |
c-faster-than-90-a-trick-to-handle-order-oxmt
\n\n# Code\n\n\nclass Solution {\npublic:\n\n int longestBeautifulSubstring(string w) {\n \n int n = w.size();\n vector<pair<char,int>>vp;\n
mr_kamran
NORMAL
2023-04-01T08:58:26.805460+00:00
2023-04-01T08:58:26.805492+00:00
1,160
false
\n\n# Code\n```\n\nclass Solution {\npublic:\n\n int longestBeautifulSubstring(string w) {\n \n int n = w.size();\n vector<pair<char,int>>vp;\n char curr = w[0];\n int cnt = 0;\n for(int i = 0;i<n;)\n {\n while(w[i]==curr && i < n)\n {\n i++; cnt++;\n }\n vp.push_back({curr,cnt});\n curr = w[i];\n cnt = 0;\n }\n int maxi = 0;\n n = vp.size();\n\n if(n < 5) return 0;\n\n string t;\n string s = "aeiou";\n cnt = 0;\n int i = 0, j = 0;\n\n for(;j<5;++j)\n {\n t.push_back(vp[j].first);\n cnt += vp[j].second;\n }\n\n if(t==s) maxi = max(maxi,cnt);\n \n for(;j<n;++j)\n {\n t.erase(t.begin());\n t.push_back(vp[j].first);\n cnt-= vp[i].second;\n i++;\n cnt+=vp[j].second;\n if(t==s) maxi = max(maxi,cnt); \n }\n \n return maxi;\n }\n};\n\n```
3
0
['C++']
0
longest-substring-of-all-vowels-in-order
C++ easy to understand
c-easy-to-understand-by-batsy01-5ljy
\nclass Solution {\npublic:\n \n int longestBeautifulSubstring(string word) {\n //longest beautiful substring\n //next character should be e
batsy01
NORMAL
2022-01-09T06:18:46.388868+00:00
2022-01-09T06:18:46.388917+00:00
135
false
```\nclass Solution {\npublic:\n \n int longestBeautifulSubstring(string word) {\n //longest beautiful substring\n //next character should be equal of greater than the prevoius one\n //if fails -> start new window\n //each of english vowel must appear at once i.e. mp.size()==5\n //word consist only 5 letters i.e. vowels\n map<char,int> mp;\n int i=1,j=0;\n int ans=0;\n mp[word[0]]++; //entry for first letter in word\n while(i<word.size())\n {\n while(i<word.length() && word[i]>=word[i-1])\n {\n mp[word[i]]++;\n i++;\n }\n \n if(mp.size()==5) ans=max(ans,i-j);\n mp.clear();\n j=i; //start new window as failure occured\n mp[word[j]]++;\n i++;\n }\n return ans;\n }\n};\n```
3
0
[]
0
longest-substring-of-all-vowels-in-order
✅ [C++] (Sliding Window) Solution for 1839. Longest Substring Of All Vowels in Order
c-sliding-window-solution-for-1839-longe-k0qo
null
utcarsh
NORMAL
2021-11-08T03:39:19.055665+00:00
2021-11-08T06:18:16.788785+00:00
424
false
<iframe src="https://leetcode.com/playground/m92efik6/shared" frameBorder="0" width="800" height="400"></iframe>
3
0
['C', 'Sliding Window', 'C++']
0
longest-substring-of-all-vowels-in-order
C++ || without Sliding window || Map
c-without-sliding-window-map-by-priyanka-kdh8
\n\npublic:\n int longestBeautifulSubstring(string s) {\n long long int i,j,m=0;\n for(j=0;j<s.length();j++)\n {\n if(s[j]==\
priyanka1230
NORMAL
2021-08-17T15:34:29.334364+00:00
2021-08-17T15:34:29.334403+00:00
158
false
```\n\n```public:\n int longestBeautifulSubstring(string s) {\n long long int i,j,m=0;\n for(j=0;j<s.length();j++)\n {\n if(s[j]==\'a\')\n {\n i=j;\n map<int,int>mp;\n while(i<s.length()&&s[i]==\'a\')\n {\n mp[0]++;\n i++;\n }\n while(i<s.length()&&s[i]==\'e\')\n {\n mp[1]++;\n i++;\n }\n while(i<s.length()&&s[i]==\'i\')\n {\n mp[2]++;\n i++;\n }\n while(i<s.length()&&s[i]==\'o\')\n {\n mp[3]++;\n i++;\n }\n while(i<s.length()&&s[i]==\'u\')\n {\n mp[4]++;\n i++;\n }\n if(mp.size()==5)\n {\n m=max(i-j,m);\n }\n j=i-1;\n }\n }\n return m;\n }\n};
3
0
[]
0
longest-substring-of-all-vowels-in-order
Java solution
java-solution-by-rkxyiiyk2-1vo3
\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n \n int maxCount = 0, currCount = 1, vowCount = 1;\n \n
rkxyiiyk2
NORMAL
2021-07-23T03:21:13.401373+00:00
2021-07-23T03:23:17.154309+00:00
292
false
```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n \n int maxCount = 0, currCount = 1, vowCount = 1;\n \n for (int i = 1; i < word.length(); i++) {\n char prev = word.charAt(i-1);\n char curr = word.charAt(i);\n if (curr < prev) {\n currCount = 1;\n vowCount = 1;\n } else if (curr > prev) {\n vowCount++;\n currCount++;\n } else {\n currCount++;\n }\n if (vowCount == 5) {\n maxCount = Integer.max(currCount, maxCount); \n }\n }\n return maxCount;\n }\n}\n```
3
0
['Java']
0
longest-substring-of-all-vowels-in-order
Python3 simple solution using two pointer approach
python3-simple-solution-using-two-pointe-bzsl
\nclass Solution:\n def longestBeautifulSubstring(self, s: str) -> int:\n i,j,x = 0,0,0\n while j < len(s):\n if s[j] in [\'a\', \'e
EklavyaJoshi
NORMAL
2021-05-07T17:43:33.318349+00:00
2021-05-07T17:43:33.318394+00:00
247
false
```\nclass Solution:\n def longestBeautifulSubstring(self, s: str) -> int:\n i,j,x = 0,0,0\n while j < len(s):\n if s[j] in [\'a\', \'e\', \'i\', \'o\', \'u\'] and (s[j-1] <= s[j] or j == 0):\n j += 1\n else:\n if len(set(s[i:j])) == 5:\n x = max(x,j-i)\n i = j\n j += 1\n if len(set(s[i:j])) == 5:\n x = max(x,j-i)\n return x\n```\n**If you like this solution, please upvote for this**
3
0
['Two Pointers', 'Python3']
1
longest-substring-of-all-vowels-in-order
Python solution | Lengthy but beginner friendly
python-solution-lengthy-but-beginner-fri-5v3o
\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n mx=0\n ans=0\n res=""\n endcaseans=""\n v="ae
rohansk
NORMAL
2021-04-25T10:09:41.274513+00:00
2021-05-15T05:29:50.036360+00:00
86
false
```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n mx=0\n ans=0\n res=""\n endcaseans=""\n v="aeiou"\n for i in range(0,len(word)-1):\n if word[i]<=word[i+1]:\n res+=word[i]\n else:\n res+=word[i]\n endcaseans+=res\n if "".join(sorted(set(res))) == v:\n ans=len(res)\n if ans>mx:\n mx=ans\n res=""\n endcase=word[len(endcaseans):]\n if "".join(sorted(set(endcase))) == v:\n if len(endcase)>mx:\n mx=len(endcase)\n return mx\n```
3
1
[]
0
longest-substring-of-all-vowels-in-order
Sliding window with multiple conditions java
sliding-window-with-multiple-conditions-l88mf
Sliding window with multiple conditions, if you can optimize thise code, please add the comment.\n\nclass Solution {\n public int longestBeautifulSubstring(S
karthik1239
NORMAL
2021-04-25T04:37:00.281347+00:00
2021-04-25T04:42:30.631472+00:00
229
false
Sliding window with multiple conditions, if you can optimize thise code, please add the comment.\n```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int max = 0;\n int start = 0;\n int end = 0;\n int len = word.length();\n char[] vowels = {\'a\', \'e\', \'i\', \'o\', \'u\'};\n int charIndex = 0;\n while(end < len) {\n //If previous character is u and current character is not u, we have got the required string from start to previous index.\n if(charIndex == 4 && word.charAt(end) != vowels[charIndex]) {\n max = Math.max(max, end - start);\n charIndex = 0;\n start = end;\n continue;\n }\n\t\t\t//Skip duplicate vowel character\n if(word.charAt(end) == vowels[charIndex]) {\n end++;\n continue;\n } \n\t\t\t//Found the next required vowel.\n if(word.charAt(end) == vowels[charIndex + 1]) {\n charIndex++;\n end++;\n continue;\n }\n\t\t\t//Not the vowel string that we want. So reset.\n if(word.charAt(end) != vowels[charIndex + 1]) {\n charIndex = 0;\n while(end < len && word.charAt(end) != vowels[charIndex])\n end++;\n start = end;\n }\n }\n if(charIndex == 4) {\n max = Math.max(max, end - start);\n }\n return max;\n }\n}\n```
3
0
[]
0
longest-substring-of-all-vowels-in-order
C++ slinding window solution very easy
c-slinding-window-solution-very-easy-by-ruae4
\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int ans=0;\n for (int i=0;i<word.size();)\n {\n
rkrrathorerohit10
NORMAL
2021-04-25T04:04:45.617835+00:00
2021-04-25T04:32:51.053238+00:00
195
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int ans=0;\n for (int i=0;i<word.size();)\n {\n int j=i;\n\t\t\t// we have flag variables for each vowel so that we can know that we have got each vowel in order.\n bool flaga=false,flage=false,flagi=false,flago=false,flagu=false;\n while (j<word.size()&&word[j]==\'a\')\n {\n flaga=true;\n j++;\n }\n\t\t\t// if we don\'t get vowel \'a\' hence we can simply cotinue to next position, as there id no use of trying for other vowels\n\t\t\t// this same is happening for each vowel using flag variables\n if (!flaga){\n i=j+1;\n continue;\n }\n while (flaga&&j<word.size()&&word[j]==\'e\')\n {\n flage=true;\n j++;\n }\n while (flage&&j<word.size()&&word[j]==\'i\')\n {\n flagi=true;\n j++;\n }\n while (flagi&&j<word.size()&&word[j]==\'o\')\n {\n flago=true;\n j++;\n }\n while (flago&&j<word.size()&&word[j]==\'u\')\n {\n flagu=true;\n j++;\n }\n\t\t\t// if we got all vowels then update the answer else simply move to further index.\n if (flaga&&flage&&flagi&&flago&&flagu)\n {\n ans=max(ans,j-i);\n }\n i=j;\n }\n return ans;\n }\n};\n```\nkindly ask if any doubt there.\n
3
1
[]
0
longest-substring-of-all-vowels-in-order
C++ solution easy [ reduce to longest increasing substring ]
c-solution-easy-reduce-to-longest-increa-vsf9
intuition\n\nthis problem can be reduced down to longest increasing substring [ which was not obvious at first atleast for me ]bcz i was trying sliding window m
zerojude
NORMAL
2021-04-25T04:01:17.548003+00:00
2021-04-25T04:19:09.213760+00:00
318
false
**intuition**\n\nthis problem can be reduced down to longest increasing substring `[ which was not obvious at first atleast for me ] `bcz i was trying sliding window most of time with char string getting wrong ans on edge cases\n\n\n**implementation**\n\nin the first part of code i changed the string to numbers that way it will be easier for me write less messy code \n\n i changed \n\n a -- > 0 \n e -- > 1 \n i -- > 2 \n o -- > 3 \n u -- > 4 \n\n so the string like this " aaeiaeiou " -- > becoms " 001201234 "\n\n so the question converts to finding the longest increasnig substring which includes the all the no [ 0 , 1 , 2 , 3 , 4 ] , and it must be sorted \n\n to handle count of different no i have used `cnt`\n\n to maintain the sorted form we use code like **longest increasing substring** \n\n\n\n\n ```\n\n int longestBeautifulSubstring(string A ) {\n \n \n if( A.size() < 5 )return 0 ; \n \n for( auto &x : A ) // imprtant step to convert the problem to known problem \n {\n if( x == \'a\' ) x = \'0\'; \n if( x == \'e\' ) x = \'1\'; \n if( x == \'i\' ) x = \'2\'; \n if( x == \'o\' ) x = \'3\'; \n if( x == \'u\' ) x = \'4\'; \n }\n \n // after this we only deal with numbers so our code bit clearer now \n\n int mx = 0 ; \n \n vector< int > t( 10 , 0 ); \n int cnt = 0 ; \n int i = 0 ; \n int j ;\n \n \n \n for( j = 0 ; j < A.size() ; j++ )\n {\n if( j > 0 && A[j] >= A[j-1] ) // increasing contraint [ no strict ]\n {\n if( t[A[j]-\'0\']++ == 0 )cnt++; \n \n if( cnt == 5 ) // we found increasing substring that contain all 5 no\'s \n {\n mx = max( mx , j-i+1 ); \n }\n }\n else \n {\n i = j ; // starting indext should be from this j now \n \n for( int i = 0 ; i < 5 ; i++ )t[i] = 0 ; \n cnt = 0 ; \n t[A[j]-\'0\'] = 1 ;\n if( A[j] == \'0\' )cnt = 1 ; // if this char is \'a\' then cnt = 1 ; \n }\n }\n \n return mx ; // return the longest increasiong substring that all 5 no in it \n \n }\n\n\n ```
3
3
['Sliding Window']
0
longest-substring-of-all-vowels-in-order
Longest Beautiful Substring | C++ Solution | Two Pointer + Greedy | O(N) Time
longest-beautiful-substring-c-solution-t-pzz2
IntuitionWe’re asked to find the length of the longest "beautiful" substring—a substring that: Contains all 5 vowels: 'a', 'e', 'i', 'o', 'u' Appears in lexi
Praveenkumaryadav
NORMAL
2025-04-06T17:31:13.821935+00:00
2025-04-06T17:36:49.032421+00:00
23
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We’re asked to find the length of the longest "beautiful" substring—a substring that: - Contains all 5 vowels: 'a', 'e', 'i', 'o', 'u' - Appears in lexicographical order (i.e., 'a' before 'e', 'e' before 'i', etc.) Instead of checking all substrings (which would be slow), we scan the string once using a greedy + two pointer approach and track progress through the vowel stages. # Approach <!-- Describe your approach to solving the problem. --> Initialize: - vowelStage = 1: Tracks how many vowels we've encountered in correct order - left = 0: Start of the current valid substring - maxLength = 0: Stores the length of the longest beautiful substring Traverse the string from index 1 to end: - If the current character is smaller than the previous (order break): - Reset vowelStage = 1, and left = i to restart tracking a new possible substring - If the current character is greater than the previous: - Move to the next vowel stage (vowelStage++) - If vowelStage == 5 (all vowels in order found): - Update maxLength with the length of the current window Return maxLength at the end # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(N) Single pass through the string of length N - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) No extra space used other than a few variables # Code ``` C++ [] class Solution { public: int longestBeautifulSubstring(string word) { int maxLength = 0, left = 0, vowelStage = 1; for(int i=1; i<word.size(); i++) { if(word[i] < word[i-1]) { vowelStage = 1; left = i; } else if(word[i-1] < word[i]) { vowelStage++; } if(vowelStage == 5) { maxLength = max(maxLength, i - left + 1); } } return maxLength; } }; ``` ```java [] class Solution { public int longestBeautifulSubstring(String word) { int maxLength = 0, vowelStage = 1, left = 0; for(int i=1; i<word.length(); i++) { if(word.charAt(i-1) > word.charAt(i)) { vowelStage = 1; left = i; } else if(word.charAt(i-1) < word.charAt(i)) { vowelStage++; } if(vowelStage == 5) { maxLength = Math.max(maxLength, i-left+1); } } return maxLength; } } ``` <strong>👍 If this helped, an upvote would be appreciated! <br> ![upvote (1080 x 1080 px) (400 x 400 px) (400 x 400 px).jpg](https://assets.leetcode.com/users/images/32dee7ff-2eb7-483e-b6a7-e68763a42781_1743960958.610285.jpeg)
2
0
['String', 'Sliding Window', 'C++', 'Java']
0
longest-substring-of-all-vowels-in-order
🔥EASY JAVA SOLUTION🔥|| READABLE SOLUTION___
easy-java-solution-readable-solution___-irmnh
Intuition\n Describe your first thoughts on how to solve this problem. \nThe vowels are \'a\',\'e\',\'i\',\'o\',\'u\' So they are in order then only the word be
Baibhab07
NORMAL
2024-07-17T03:39:55.024294+00:00
2024-07-17T03:39:55.024326+00:00
96
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe vowels are `\'a\',\'e\',\'i\',\'o\',\'u\'` So they are in order then only the word become beautiful... which means every word have 5 vowels.\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a variable`count`which check for all the vowel present or not, a variable `l` for counting the length of the substring.\n2. Initialize another variable `max_len` with zero.\n3. Iterate through the words length starting from the index 1.\n - Check if the character at `i` is equal to `i-1` if yes then increase the count of the `l` by 1.\n - else if the character at `i-1` is less than `i` then increase the `count` and length `l` by 1.\n - else set `count` and `l` to 1.\n - if the `count` is equal to 5 then set the `max_len` to maximun of `l` and `max_len`.\n4. Return the value of the `max_len`.\n\n---\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ - We traverse throught the length of the word only once\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$ - As no extra space is used to store character \n\n---\n\n\n# Code\n```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int count = 1;\n int l = 1;\n int max_len = 0;\n\n for (int i = 1; i < word.length(); i++) {\n if (word.charAt(i) == word.charAt(i - 1)) {\n l++;\n } else if (word.charAt(i - 1) < word.charAt(i)) {\n count++;\n l++;\n } else {\n l = 1;\n count = 1;\n }\n if (count == 5) {\n max_len = Math.max(max_len, l);\n }\n }\n\n return max_len;\n }\n}\n```\n# *UPVOTE PLEASE...\uD83D\uDE0A* \n# For the easy explaination......\n![avatar.jpeg](https://assets.leetcode.com/users/images/c3390970-fddd-4f78-b53a-92fea7e72b5c_1721186715.05799.jpeg)\n
2
0
['Java']
0
longest-substring-of-all-vowels-in-order
not a easy python solution, hahaha...
not-a-easy-python-solution-hahaha-by-see-8um6
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
seenumadhavan
NORMAL
2024-01-28T13:07:59.545630+00:00
2024-01-28T13:07:59.545675+00:00
307
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) : max size of seen and stack can only be size of 5\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestBeautifulSubstring(self, s: str) -> int:\n stack = [\'u\',\'o\',\'i\',\'e\',\'a\']\n seen = []\n maxi = 0\n r = 0\n c = 0\n while r < len(s):\n char = s[r]\n if not stack:\n if s[r] == "u":\n c += 1\n else:\n maxi = max(maxi, c)\n c = 0\n stack = [\'u\',\'o\',\'i\',\'e\',\'a\']\n seen.clear()\n if s[r] == stack[-1] or (seen and seen[-1] == s[r]):\n if s[r] == stack[-1]:\n seen.append(stack.pop(-1))\n c += 1\n elif s[r] == stack[-1] or (seen and seen[-1] == s[r]):\n if s[r] == stack[-1]:\n seen.append(stack.pop(-1))\n c += 1\n else:\n if not stack:\n maxi = max(maxi, c)\n c = 0\n stack = [\'u\',\'o\',\'i\',\'e\',\'a\']\n seen.clear()\n if s[r] == stack[-1] or (seen and seen[-1] == s[r]):\n if s[r] == stack[-1]:\n seen.append(stack.pop(-1))\n c += 1\n r += 1\n if not stack:\n maxi = max(maxi, c)\n return maxi\n```
2
0
['Python3']
0
longest-substring-of-all-vowels-in-order
✅💯Very Easy | Simple Solution
very-easy-simple-solution-by-dipesh_12-y36h
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
dipesh_12
NORMAL
2023-05-06T05:56:12.489499+00:00
2023-05-06T05:56:12.489531+00:00
631
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 longestBeautifulSubstring(String word) {\n int len=1;\n int count=1;\n int maxLen=0;\n for(int i=1;i<word.length();i++){\n if(word.charAt(i-1)<=word.charAt(i)){\n if(word.charAt(i-1)!=word.charAt(i)){\n count++;\n }\n len++;\n if(count==5){\n maxLen=Math.max(maxLen,len);\n }\n }\n else{\n len=1;\n count=1;\n }\n }\n\n return maxLen;\n }\n}\n```
2
0
['Java']
1
longest-substring-of-all-vowels-in-order
Java || String Manipulation(Sliding window variation) ✅
java-string-manipulationsliding-window-v-yumf
\nclass Solution {\n public boolean isDistinct(char a, char b){\n return a!=b;\n }\n public int longestBeautifulSubstring(String word) {\n
Ritabrata_1080
NORMAL
2022-10-23T18:30:01.121398+00:00
2022-10-23T18:30:01.121444+00:00
836
false
```\nclass Solution {\n public boolean isDistinct(char a, char b){\n return a!=b;\n }\n public int longestBeautifulSubstring(String word) {\n int maxLen = 0, n = word.length(), count = 1, wordLength = 1;\n for(int i = 1;i<n;i++){\n if(word.charAt(i-1) <= word.charAt(i)){\n if(isDistinct(word.charAt(i-1), word.charAt(i))){\n count++;\n }\n wordLength++;\n if(count == 5){\n maxLen = Math.max(maxLen, wordLength);\n }\n }\n else{\n count = 1;\n wordLength = 1;\n }\n }\n return maxLen;\n }\n}\n```
2
0
['String', 'Sliding Window', 'Java']
0
longest-substring-of-all-vowels-in-order
✅Easy Java solution||Without Window Sliding||Beginner Friendly🔥
easy-java-solutionwithout-window-sliding-ii3b
If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries
deepVashisth
NORMAL
2022-09-08T20:04:27.989695+00:00
2022-09-08T20:04:27.989739+00:00
403
false
**If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.**\n```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n char[] vowels = {\'a\',\'e\',\'i\',\'o\',\'u\'};\n int count = 0;\n int max = 0;\n int j = 0;\n for(int i = 0 ; i < word.length() ; i ++){\n if(word.charAt(i) == vowels[j]){\n count++;\n }\n else if(j < vowels.length-1 && count > 0 &&word.charAt(i) == vowels[j+1]){\n j++;\n count++;\n }\n else if(word.charAt(i) != vowels[j]){\n if(j == vowels.length-1){\n max = Math.max(max,count);\n }\n j = 0;\n count = 0;\n if(word.charAt(i) == vowels[j]){\n count++;\n }\n }\n }\n if(j == vowels.length-1){\n max = Math.max(max,count);\n }\n return max;\n }\n}\n```\n**Happy Coding**
2
0
['Java']
0
longest-substring-of-all-vowels-in-order
Most Simple and Easy || Sliding Window || Intuitive || 2 approaches
most-simple-and-easy-sliding-window-intu-zbw2
Most Intutive:\nGiven word only contains vowels(given in question) and we just have to find out the longest substring that contains all vowels in sorted order o
souravpal4
NORMAL
2022-08-30T07:29:55.634800+00:00
2022-09-02T04:05:53.843811+00:00
75
false
**Most Intutive:**\nGiven word only contains vowels(given in question) and we just have to find out the longest substring that contains all vowels in sorted order of ascii value. i.e `\'a\'<\'e\'<\'i\'<\'o\'<\'u\' .`\nSo if a substring have 5 unique character and following ascii order we can update our answer by its length.\n\n```\nclass Solution {\n public int longestBeautifulSubstring1(String word) {\n int cnt=1;\n int len=1;\n int max_length=0;\n \n int n=word.length();\n \n for(int i=1;i<n;i++){\n if(word.charAt(i)==word.charAt(i-1)){\n len++;\n }else if(word.charAt(i-1)<word.charAt(i)){\n cnt++;\n len++;\n }else{\n len=1;\n cnt=1;\n }\n \n if(cnt==5){\n max_length=Math.max(max_length,len);\n }\n }\n return max_length;\n }```\n\t\n\t\n //Sliding Window\n\t\n\t\n``` public int longestBeautifulSubstring(String word) {\n int start = 0;\n int res = 0;\n Map<Character, Integer> charCount = new HashMap();\n char ch = word.charAt(0);\n charCount.put(ch, 1);\n\n for(int end = 1; end < word.length(); end++)\n {\n if (word.charAt(end-1) > word.charAt(end))\n { \n charCount.clear();\n start = end;\n }\n ch = word.charAt(end);\n charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);\n\n if(charCount.size() == 5)\n res=Math.max(res, end - start + 1);\n }\n return res;\n }\n}\n```
2
0
['Sliding Window', 'Java']
0
longest-substring-of-all-vowels-in-order
easy sliding window concept || using hashmaps in cpp
easy-sliding-window-concept-using-hashma-cnfh
class Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n vectorA(26,0);\n int j=0 ,i=0;\n int n=word.size();\n
agarwalayush007
NORMAL
2022-08-27T14:05:33.209795+00:00
2022-08-27T14:05:33.209836+00:00
224
false
class Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n vector<int>A(26,0);\n int j=0 ,i=0;\n int n=word.size();\n \n int count =0,ans=0;\n while(i<n)\n {\n if(i>0 and i!=j and word[i]<word[i-1])\n {\n for(int i=0;i<26;i++)\n A[i]=0; \n \n j=i;\n count=0;\n \n }\n if(A[word[i]-\'a\']==0)count++;\n A[word[i]-\'a\']++;\n \n if(count==5)ans=max(ans,i-j+1);\n \n i++;\n \n \n }\n return ans;\n }\n};
2
0
['C', 'Sliding Window']
0
longest-substring-of-all-vowels-in-order
concise solution (faster than 100% typescript submissions)
concise-solution-faster-than-100-typescr-5i8f
Runtime: 99 ms, faster than 100.00% of TypeScript online submissions \n\nfunction longestBeautifulSubstring_2(word: string): number {\n let maxCount = 0\n
cachiengion314
NORMAL
2022-04-22T07:51:10.884953+00:00
2022-04-22T07:52:20.862968+00:00
287
false
Runtime: 99 ms, faster than 100.00% of TypeScript online submissions \n```\nfunction longestBeautifulSubstring_2(word: string): number {\n let maxCount = 0\n let l = 0, r = 1\n let vowelCount = 1\n\n while (r < word.length) {\n let key_char = word[r]\n if (key_char < word[r - 1]) {\n vowelCount = 1\n l = r\n } else if (key_char > word[r - 1]) {\n vowelCount++\n }\n if (vowelCount === 5) {\n maxCount = Math.max(maxCount, r - l + 1)\n }\n r++\n }\n return maxCount\n}\n```
2
0
['TypeScript', 'JavaScript']
0
longest-substring-of-all-vowels-in-order
JAVA||Sliding window||O(n)||Clear solution
javasliding-windowonclear-solution-by-ch-t5jn
Please upvote if you find it useful! Or leave comments or suggestions below!\nI will try my best to answer them! Thank you!!\n\nclass Solution {\n public int
Changxu_Ren
NORMAL
2022-01-23T22:56:34.289964+00:00
2022-01-23T22:56:34.290018+00:00
149
false
Please upvote if you find it useful! Or leave comments or suggestions below!\nI will try my best to answer them! Thank you!!\n```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n // the last \'u\' is the sentinel value\n char[] vowels = new char[]{\'a\', \'e\', \'i\', \'o\', \'u\', \'u\'};\n int left = 0, right = 0, vIdx = 0, maxLen = 0;\n \n while (left < word.length()) {\n char leftChar = word.charAt(left);\n \n if (leftChar == \'a\') {\n right = left;\n \n while (right < word.length()) {\n char rightChar = word.charAt(right);\n char nextVowel = vowels[vIdx + 1];\n \n if (rightChar != vowels[vIdx]) {\n if (rightChar != nextVowel) {\n break;\n } else {\n vIdx++;\n }\n }\n right++;\n }\n \n if (vIdx == 4) maxLen = Math.max(maxLen, right - left);\n left = right - 1;\n }\n \n vIdx = 0;\n left++;\n }\n \n return maxLen;\n }\n}\n\n```
2
0
[]
0
longest-substring-of-all-vowels-in-order
C++ | O(n) Simple Solution
c-on-simple-solution-by-getting_on_track-nzj9
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n vector vowels{\'a\',\'e\',\'i\',\'o\',\'u\'};\n int result = 0;
getting_on_track
NORMAL
2021-12-21T05:05:27.065374+00:00
2021-12-21T05:06:43.641095+00:00
105
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n vector<char> vowels{\'a\',\'e\',\'i\',\'o\',\'u\'};\n int result = 0;\n int currPos = 0;\n int runningLength = 0;\n \n for(int i=0;i<word.size();i++)\n {\n if(word[i]==\'a\')\n {\n runningLength = (currPos==1 ? runningLength : 0 ) + 1;\n currPos = 1;\n }\n else if (currPos<5 && word[i] == vowels[currPos])\n {\n currPos++;\n runningLength++;\n }\n else if(currPos>0 && word[i]==vowels[currPos-1])\n {\n runningLength++;\n }\n else\n {\n runningLength = 0;\n currPos = 0;\n }\n \n if(currPos==5)\n {\n result = max(result, runningLength);\n }\n \n }\n \n return result;\n \n }\n};
2
0
[]
0
longest-substring-of-all-vowels-in-order
[Python3] Simple single pass
python3-simple-single-pass-by-danwusbu-l2kl
Explanation:\ng holds the unique vowels seen so far, in order.\ncount holds the size of the current substring.\nm holds the max size, and is what we return at t
danwuSBU
NORMAL
2021-07-16T23:02:40.264155+00:00
2021-11-06T01:33:59.843736+00:00
272
false
**Explanation:**\n`g` holds the unique vowels seen so far, in order.\n`count` holds the size of the current substring.\n`m` holds the max size, and is what we return at the end.\n\nWe do one pass through `word`, and if we encounter a vowel, we do one of two things:\n1. If `g` isn\'t empty and `g[-1]` is greater than the new vowel, then we do a reset - we set `count` back to 0 and empty out `g`.\n2. If `g` is blank or `g[-1]` is smaller than the new vowel, then we simply append the new vowel to `g`.\n\nWe do this every iteration, as well:\n1. `count += 1` obviously.\n2. We check if `g == \'aeiou\'`. If this is true, then we have a valid substring of size `count`. We compare it with `m`, naturally.\n\nAt the end, we spit out `m`, which is our correct answer.\n\n**Code:**\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n g = \'\'\n count = m = 0\n for x in word:\n if g and x < g[-1]:\n count = 0\n g = \'\'\n if not g or x > g[-1]:\n g += x\n count += 1\n if g == \'aeiou\':\n m = max(m, count)\n return m\n```
2
0
['Python']
1
longest-substring-of-all-vowels-in-order
[Java] Clean O(1)-space Solution
java-clean-o1-space-solution-by-xieyun95-zdt3
\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int res = 0;\n \n int len = 1; // length of current non-d
xieyun95
NORMAL
2021-05-26T03:31:35.730514+00:00
2021-05-26T03:31:35.730547+00:00
168
false
```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int res = 0;\n \n int len = 1; // length of current non-decreasing substring\n int count = 1; // number of unique char in current non-decreasing substring\n \n for (int i = 1; i < word.length(); i++) {\n char c1 = word.charAt(i);\n char c2 = word.charAt(i-1);\n \n if (c1 < c2) {\n len = 1;\n count = 1;\n } else if (c1 == c2) {\n len++;\n if (count == 5) res = Math.max(res, len);\n } else {\n len++;\n count++;\n if (count == 5) res = Math.max(res, len);\n }\n }\n return res;\n }\n}\n```
2
0
['Java']
0
longest-substring-of-all-vowels-in-order
[Python] fast and simple
python-fast-and-simple-by-cruim-r1bi
\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n begin = None\n best = 0\n a_detected = False\n for i
cruim
NORMAL
2021-05-21T13:31:01.149055+00:00
2021-05-21T13:31:01.149088+00:00
360
false
```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n begin = None\n best = 0\n a_detected = False\n for index, value in enumerate(word):\n if not a_detected and value == \'a\':\n begin = index\n a_detected = True\n elif a_detected and value < word[index-1]:\n if len(set(word[begin:index])) == 5:\n best = max(best, len(word[begin:index]))\n if value == \'a\':\n begin = index\n else:\n begin = None\n a_detected = False\n best = max(best, len(word[begin:])) if a_detected and len(set(word[begin:])) == 5 else best\n return best\n```
2
0
['Python', 'Python3']
0
longest-substring-of-all-vowels-in-order
Simple c++solution 97% faster
simple-csolution-97-faster-by-ankushjkku-8uan
\tclass Solution {\n\tpublic:\n\t\tint longestBeautifulSubstring(string word) {\n\t\t\tint a=0,e=0,I=0,o=0,u=0; // variables are used to store the frequency se
ankushjkkumar
NORMAL
2021-05-02T15:20:55.026786+00:00
2021-05-02T15:20:55.026827+00:00
155
false
\tclass Solution {\n\tpublic:\n\t\tint longestBeautifulSubstring(string word) {\n\t\t\tint a=0,e=0,I=0,o=0,u=0; // variables are used to store the frequency sequencly\n\t\t\tint n=word.size();\n\t\t\tint maxi=0;\n\t\t\tfor(int i=0;i<word.size();i++)\n\t\t\t{\n\t\t\t\tif(word[i]==\'a\')\n\t\t\t\t{\n\t\t\t\t\t\twhile(i<n)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(word[i]==\'a\')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ta++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tif( a>0 && word[i]==\'e\' )\n\t\t\t\t\t{\n\t\t\t\t\t\twhile(i<n)\n\t\t\t\t\t {\n\t\t\t\t\t\t\tif(word[i]==\'e\')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\te++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif(a>0 && e>0 && word[i]==\'i\')\n\t\t\t\t\t{\n\t\t\t\t\t\t while(i<n)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(word[i]==\'i\')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tI++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(a>0 && e>0 && I>0 && word[i]==\'o\')\n\t\t\t\t\t{\n\t\t\t\t\t\t while(i<n)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(word[i]==\'o\')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\to++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(a>0 && e>0 && I>0 && o>0 && word[i]==\'u\')\n\t\t\t\t\t{\n\t\t\t\t\t\t while(i<n)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(word[i]==\'u\')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tu++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif(a>0 && e>0 && I>0 && o>0 && u>0)\n\t\t\t\t\t\tmaxi=max(a+e+I+o+u,maxi);\n\n\t\t\t\t\ta=0;\n\t\t\t\t\te=0;\n\t\t\t\t\tI=0;\n\t\t\t\t\to=0;\n\t\t\t\t\tu=0;\n\t\t\t\t\ti=i-1;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn maxi;\n\t\t}\n\t};
2
0
[]
0
longest-substring-of-all-vowels-in-order
Easy C++ Solution O(n) Time and O(1) space
easy-c-solution-on-time-and-o1-space-by-xyrsr
We know a<e<i<o<u . So, here we just need to find the length of longest non-decreasing substring with 5 different characters.\n\nclass Solution {\npublic:\n
akb30
NORMAL
2021-04-25T10:23:06.454079+00:00
2021-04-25T10:23:06.454106+00:00
90
false
We know a<e<i<o<u . So, here we just need to find the length of longest non-decreasing substring with 5 different characters.\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int j=0;\n int res=0;\n unordered_map<char,int> mp;\n for(int i=0;i<word.size();i++)\n {\n if(i>0 && word[i-1]>word[i])\n {\n mp.clear();\n j=i;\n }\n mp[word[i]]++;\n if(mp.size()==5)\n res=max(res,i-j+1);\n }\n return res;\n }\n};\n```
2
0
[]
0
longest-substring-of-all-vowels-in-order
C++ | Sliding window | with Set | Simple | with comments
c-sliding-window-with-set-simple-with-co-o39k
\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n \n set<char> checker; //set to store all vowels\n \n
Vlad_III
NORMAL
2021-04-25T04:51:46.362030+00:00
2021-04-25T04:52:33.713326+00:00
93
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n \n set<char> checker; //set to store all vowels\n \n int start = 0; \n int end =0;\n int curr =0; \n int ans =0 ; // final answer\n \n while(curr<word.size()){\n \n \n if(checker.empty()){ //if set is empty \n \n char st = word[curr]; //check is beginning letter is a or not\n \n if(st!=\'a\'){\n curr++;\n \n }else{\n \n checker.insert(\'a\');\n start = curr;\n end = curr;\n curr++;\n \n }\n \n } else{\n \n\n if(word[curr] - word[end]>=0 and (curr== (end+1) or curr==end)){ //if letter are in inc order insert them \n \n \n checker.insert(word[curr]);\n \n \n curr++;\n end++;\n \n }else{\n \n if(checker.size()==5){ //if we have all vowels then size will be 5\n \n ans = max(ans,end-start+1);\n checker.clear(); // clear the set\n start = curr;\n end = curr;\n \n }else{ // not found all vowels discard set , start afresh\n checker.clear();\n start = curr;\n end = curr;\n \n }\n \n }\n \n \n }\n \n }\n\n if(checker.size()==5){ //out side the loop case\n \n ans = max(ans,end-start+1);\n checker.clear();\n \n }\n\n \n return ans;\n \n }\n};```
2
0
['Sliding Window']
0
longest-substring-of-all-vowels-in-order
[Python] - Bruteforce O(n) - Simple easy to follow solution
python-bruteforce-on-simple-easy-to-foll-g7j8
Intuition --> \nKeep track of the previous character and it has to be in sequence so the else condition follows accordingly. \n\nTime Complexity:- O(n)\n\n\ncla
ankits0052
NORMAL
2021-04-25T04:26:55.760059+00:00
2021-04-25T04:28:19.440103+00:00
230
false
Intuition --> \nKeep track of the previous character and it has to be in sequence so the else condition follows accordingly. \n\nTime Complexity:- O(n)\n\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n s=0\n prev=\'a\'\n l=[]\n for char in word:\n if char == \'a\' and prev == \'a\':\n prev=char\n s+=1\n elif char == \'e\' and (prev == \'a\' or prev==\'e\'):\n prev=char\n s+=1\n elif char == \'i\' and (prev ==\'e\' or prev==\'i\'):\n prev=char\n s+=1\n elif char == \'o\' and (prev == \'i\' or prev==\'o\'):\n prev=char\n s+=1\n elif char==\'u\' and (prev ==\'o\' or prev==\'u\'):\n prev=char\n s+=1\n if s>=5:\n l.append(s)\n else:\n if char !=\'a\':\n s=0\n prev=\'a\'\n else:\n s=1\n prev=char\n \n if not l:\n return 0\n else:\n return max(l)\n```
2
1
['Python', 'Python3']
0
longest-substring-of-all-vowels-in-order
C++ | Solution code | O(n) | 696. Count Binary String
c-solution-code-on-696-count-binary-stri-947m
Concept used here is similar to the solution for the problem 696. Count Binary Substring\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(stri
ExtraSecond
NORMAL
2021-04-25T04:03:42.675925+00:00
2021-04-25T04:06:15.511454+00:00
213
false
Concept used here is similar to the solution for the problem [696. Count Binary Substring](https://leetcode.com/problems/count-binary-substrings/)\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n vector<pair<char,int>> count;\n \n for(int i = 0 ; i < word.size() ; ) {\n int haha = 0;\n int j = i;\n char temp = word[j];\n while(j < word.size() && word[j] == temp) {\n j++;\n }\n count.push_back(make_pair(temp, j-i));\n\n i = j;\n }\n \n int answer = 0;\n\n \n for(int index = 0 ; index < count.size() ; index++) {\n int a = index;\n int e = index+1;\n int i = index+2;\n int o = index+3;\n int u = index+4;\n\n if(a < count.size() && count[a].first == \'a\' && e < count.size() && count[e].first == \'e\' && i < count.size() && count[i].first == \'i\' && o < count.size() && count[o].first == \'o\' && u < count.size() && count[u].first == \'u\') {\n\n answer = max(\n answer, count[a].second + count[e].second + count[i].second + count[o].second + count[u].second\n );\n }\n \n \n }\n \n return answer;\n \n }\n};
2
0
[]
1
longest-substring-of-all-vowels-in-order
The Quest for the Longest Beautiful Substring: A Vowel Odyssey 🎶🔍 (BEATS 100%)
the-quest-for-the-longest-beautiful-subs-mrc5
Intuition 🧠💡Alright, let's tackle this problem step by step! Imagine you're on a quest to find the most melodious substring in a string of vowels. The melody mu
Karnsaty
NORMAL
2025-04-11T07:57:42.226413+00:00
2025-04-11T07:57:42.226413+00:00
3
false
# Intuition 🧠💡 Alright, let's tackle this problem step by step! Imagine you're on a quest to find the most melodious substring in a string of vowels. The melody must follow the order 'a', 'e', 'i', 'o', 'u'—like a musical scale going up 🎧. And not just any scale, but one that includes all five vowels in order! So, our goal is to find the longest substring where the vowels appear in this exact increasing order, and all five must be present. Think of it like finding the longest "aeiou" sequence in a jumbled string of letters. # Approach 🚀🔍 Here's how we can approach this melodious problem: ****Initialize Trackers:**** We'll keep track of: **count:** How many distinct vowels in order we've seen so far in the current substring. **left:** The starting index of our current potential melodious substring. **ans:** The length of the longest valid substring we've found. **Slide Through the String: We'll slide a window from the second character to the end:** If the current character is less than the previous one, it breaks our sequence. Time to reset! 🚨 Set count back to 1 (starting fresh with the current character). Move left to the current position. If the current character is greater than the previous one, it's the next vowel in our sequence! 🎉 Increment count. If it's the same, we just continue (no change to count). **Check for Full Melody:** Whenever count hits 5, it means we've got all five vowels in order! � Calculate the length of this substring (right - left + 1). Update ans if this is the longest we've found. **Return the Result:** After sliding through the entire string, ans will hold the length of the longest melodious substring. If none, it'll be 0. # Complexity 📊 **Time Complexity: O(n)** – We're sliding through the string once, so it's linear time. Efficient! ⚡ **Space Complexity: O(1)** – We're using a constant amount of extra space. No extra memory hogging here! 🐜 # Code ```cpp [] class Solution { public: int longestBeautifulSubstring(string word) { int count=1,ans=0,left=0; for(int right=1;right<word.size();++right){ if(word[right]<word[right-1]){ count=1; left=right; } else if(word[right]>word[right-1]){ count++; } if(count==5){ ans=max(ans,right-left+1); } } return ans; } }; ``` # Upvote for the Vowel Hunter! 🎯🔥 **Hey fellow coders! 👋** If you enjoyed this **musical journey through vowels** and found the solution helpful, don’t forget to smash that **upvote button!** ⬆️✨ Your support keeps the **coding symphony alive**—let’s make **beautiful substrings** trend! 🎶💻 # Happy Coding! 🚀😃
1
0
['String', 'Sliding Window', 'C++']
0
longest-substring-of-all-vowels-in-order
C++ | Easy to Understand | Sliding Window
c-easy-to-understand-sliding-window-by-g-8ltb
Intuition start traversing the string for every a that you encounter find the max valid window starting from this position Approach we initialize two pointers:
ghozt777
NORMAL
2025-03-17T20:35:43.320318+00:00
2025-03-17T20:36:01.288971+00:00
84
false
# Intuition - start traversing the string - for every `a` that you encounter find the max valid window starting from this position # Approach - we initialize two pointers: `start` and `end` - if the current character is `a` then start expanding the window till it becomes invalid -> if we exceed the length or we break the sequence of vowels - next we check if we have seen all the vowels in the current window, if so this window is valid and we can update our answer - finally we skip to last position where the window became invalid as we dont need to process the previous substring since it is already invalid # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```cpp [] class Solution { public: int longestBeautifulSubstring(string word) { int start = 0 , res = 0 ; string vw = "aeiou" ; for(int i = 0 ; i < word.size() ; i++){ if(word[i] == 'a'){ int j = i + 1 ; unordered_set<char> s ; s.insert(word[i]) ; while( j < word.length() && ( // the current char can either be equal to the previous char // or 1 + previous char w.r.t its position in the sequence aka vw word[j] == word[j-1] || vw.find(word[j]) == vw.find(word[j-1]) + 1 ) ) s.insert(word[j++]) ; j = j - 1 ; if(s.size() == 5) res = max(res,j-i+1) ; i = j ; } } return res ; } }; ```
1
0
['String', 'Sliding Window', 'C++']
0
longest-substring-of-all-vowels-in-order
Easy Solution using Recursion
easy-solution-using-recursion-by-paidise-nzdx
IntuitionThe problem requires finding the longest substring that contains all five vowels ('a', 'e', 'i', 'o', 'u') in order. The approach involves checking eac
PaidisettySuraj
NORMAL
2025-03-12T08:28:34.125603+00:00
2025-03-12T08:28:34.125603+00:00
45
false
# Intuition The problem requires finding the longest substring that contains all five vowels ('a', 'e', 'i', 'o', 'u') in order. The approach involves checking each potential starting point of such a substring and verifying if it meets the criteria. # Approach Initialization: Define the sequence of vowels and a helper function check to validate the substring. Helper Function: The check function recursively verifies if the substring starting at a given index contains all vowels in order. Main Function: Traverse the string to find all starting points where the substring could potentially be beautiful (i.e., starting with 'a'). For each starting point, use the check function to determine the length of the valid beautiful substring. Keep track of the maximum length found. # Complexity - Time complexity: The main loop runs in O(n) time, where n is the length of the input string. The check function also runs in O(n) time in the worst case. - Space complexity: O(1) # Code ```cpp [] class Solution { public: string sequence = "aeiou"; int check(string &word, int j, int k) { if ((j >= word.size() && k>=5) || k >= 5) return j; char c = sequence[k]; if (word[j] != c) return 0; while (j < word.size() && word[j] == c) j++; return check(word, j, k + 1); } int longestBeautifulSubstring(string word) { int n = word.size(), ans = 0; if (n < 5) return 0; vector<int>Afreq; if(word[0]=='a')Afreq.push_back(0); for(int i=1;i<=n-4;i++){ if(word[i]=='a') { if(word[i-1]=='a')continue; else Afreq.push_back(i); } } for (int i = 0; i < Afreq.size(); i++) { int j = check(word, Afreq[i], 0); ans = max(ans, j - Afreq[i]); } return ans; } }; // Aposition // aeeeiiiioooauuuaeiou ```
1
0
['Two Pointers', 'Recursion', 'Sliding Window', 'C++']
0
longest-substring-of-all-vowels-in-order
My Solution, Beats 96+%
my-solution-beats-96-by-simolekc-q178
Code
simolekc
NORMAL
2025-03-10T18:51:22.669216+00:00
2025-03-10T18:51:22.669216+00:00
83
false
# Code ```javascript [] /** * @param {string} word * @return {number} */ var longestBeautifulSubstring = function (word) { let n = word.length; let pntPattern = 0; const pattern = "aeiou"; let longestBeautiful = 0; let left = 0; let right = 0; while (right < n) { if (pattern[pntPattern] === word[right]) { while (pattern[pntPattern] === word[right]) { if (pntPattern === 4) { longestBeautiful = Math.max(longestBeautiful, right - left + 1); } right++; } pntPattern++; } else { while (right < n && "a" !== word[right]) { right++; } left = right; pntPattern = 0; } } return longestBeautiful; }; ```
1
0
['Sliding Window', 'JavaScript']
0
longest-substring-of-all-vowels-in-order
Easiest c++ solution solve by counting
easiest-c-solution-solve-by-counting-by-c0hsi
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(1) Code
albert0909
NORMAL
2025-03-10T03:35:08.788443+00:00
2025-03-10T03:35:08.788443+00:00
211
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)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<char> vowel = {'a', 'e', 'i', 'o', 'u'}; int longestBeautifulSubstring(string word) { int idx = 0, ans = 0, cnt = 0, i; for(i = 0;i < word.length();i++){ if(word[i] == 'a') break; } for(i;i < word.length();i++){ if(word[i] == 'u' && (vowel[idx] == 'u' || vowel[idx] == 'o')){ ans = max(cnt + 1, ans); } if(word[i] == vowel[idx]) cnt++; else if(word[i] == vowel[min(4, idx + 1)] && (word[i - 1] == vowel[idx] || word[i - 1] == vowel[min(4, idx + 1)])){ idx++; cnt++; } else{ if(word[i] == 'a') cnt = 1; else cnt = 0; idx = 0; } } return ans; } }; auto init = []() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 'c'; }(); ```
1
0
['String', 'Counting', 'C++']
0
longest-substring-of-all-vowels-in-order
A Greedy Sliding Window Approach
a-greedy-sliding-window-approach-by-rutu-lx69
Intuition\nThe problem requires finding the longest contiguous substring in which all five vowels (a, e, i, o, u) appear at least once in alphabetical order. Th
RutujaGhadage
NORMAL
2024-08-10T20:12:12.854269+00:00
2024-08-10T20:12:12.854295+00:00
287
false
# Intuition\nThe problem requires finding the longest contiguous substring in which all five vowels (a, e, i, o, u) appear at least once in alphabetical order. The key observation is that as soon as the order is violated, we need to reset the tracking of the current valid substring.\n\n# Approach\n1. Initialization:\n\n- Use a list vowels to represent the required order of vowels.\n- Initialize pointers and counters: i for iterating through the string, curr_idx to track the current vowel in the sequence, count to count the length of the current valid substring, and ans to store the maximum length of any valid substring found.\n\n2. Iterating through the string:\n\n- For each character in the string, check if it matches the current vowel in the sequence (vowels[curr_idx]).\n- If it matches, increment the count.\n- If the current character does not match but the previous character matched the current vowel, and the current character matches the next vowel in sequence, move to the next vowel and increment count.\n- If neither condition is met, check if the current substring is a valid "beautiful" substring by verifying that all vowels were seen (curr_idx == len(vowels) - 1). If so, update ans with the maximum length. Then reset the curr_idx and count and restart the process.\n- After the loop, check again if the last valid substring is the longest one.\n\n3. Return the result:\n- Return the maximum length found.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = [\'a\', \'e\', \'i\', \'o\', \'u\']\n i = 0\n curr_idx = 0\n count = 0\n ans = 0\n while i < len(word):\n if word[i] == vowels[curr_idx]:\n count += 1\n elif (i > 0 \n and word[i - 1] == vowels[curr_idx]\n and curr_idx < len(vowels) - 1 \n and word[i] == vowels[curr_idx + 1]):\n curr_idx += 1\n count += 1\n else:\n if curr_idx == len(vowels) - 1:\n ans = max(ans, count)\n curr_idx = 0\n count = 0\n if word[i] == vowels[curr_idx]:\n count += 1\n i += 1\n\n if curr_idx == len(vowels) - 1:\n ans = max(ans, count)\n \n return ans\n\n\n \n \n```
1
0
['String', 'Greedy', 'Sliding Window', 'Python3']
0
longest-substring-of-all-vowels-in-order
Python Intuitive State Machine
python-intuitive-state-machine-by-minecr-7pj4
Intuition\n Describe your first thoughts on how to solve this problem. \nTrack what state we are in when building the current substring. Then update the maximum
minecraftyugi
NORMAL
2024-07-09T05:35:50.453983+00:00
2024-07-09T05:35:50.454026+00:00
18
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTrack what state we are in when building the current substring. Then update the maximum length if our current state matches the conditions for a beautiful substring.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nState 0 is an invalid state (for example, current substring from $$l$$ to $$i$$ is not in alphabetical order)\nState 1 is last character of current susbtring is $$a$$ and current substring is in alphabetical order. Set $$l$$ to this position if it is the first $$a$$ in the current substring\nState 2 is last character of current susbtring is $$e$$ and current substring is in alphabetical order\nState 3 is last character of current susbtring is $$i$$ and current substring is in alphabetical order\nState 4 is last character of current susbtring is $$o$$ and current substring is in alphabetical order\nState 5 is last character of current susbtring is $$u$$ and current substring is in alphabetical order. Update the max length if current substring has largest length\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```\nimport collections\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n n = len(word)\n if n < 5:\n return 0\n\n max_len = 0\n l = 0\n state = 0\n for i, ch in enumerate(word):\n if state != 1 and ch == "a":\n state = 1\n l = i\n elif state == 1 and ch == "a":\n state = 1\n elif (state == 1 or state == 2) and ch == "e":\n state = 2\n elif (state == 2 or state == 3) and ch == "i":\n state = 3\n elif (state == 3 or state == 4) and ch == "o":\n state = 4\n elif (state == 4 or state == 5) and ch == "u":\n state = 5\n max_len = max(max_len, i - l + 1)\n else:\n state = 0\n\n return max_len\n```
1
0
['Python3']
0
longest-substring-of-all-vowels-in-order
When fresher writes the code XD | O(n) beats 95%
when-fresher-writes-the-code-xd-on-beats-rf13
Code\n\nclass Solution {\n public int longestBeautifulSubstring(String s) {\n int maxi = 0;\n int startIdx = 0;\n for(int i = 0 ; i < s.length
suryanshnevercodes
NORMAL
2024-07-05T12:34:12.698830+00:00
2024-07-05T12:34:12.698880+00:00
69
false
# Code\n```\nclass Solution {\n public int longestBeautifulSubstring(String s) {\n int maxi = 0;\n int startIdx = 0;\n for(int i = 0 ; i < s.length() - 1 ; i++) {\n boolean aflg = false;\n boolean eflg = false;\n boolean iflg = false;\n boolean oflg = false;\n boolean uflg = false;\n if(s.charAt(i) == \'a\') {\n startIdx = i;\n aflg = true;\n while(i + 1 < s.length() && s.charAt(i+1) == \'a\') {\n i++;\n }\n if(i + 1 < s.length() && s.charAt(i+1) != \'e\') continue;\n while(i + 1 < s.length() && s.charAt(i+1) == \'e\') {\n eflg = true;\n i++;\n }\n if(i + 1 < s.length() && s.charAt(i+1) != \'i\') continue;\n while(i + 1 < s.length() && s.charAt(i+1) == \'i\') {\n iflg = true;\n i++;\n }\n if(i + 1 < s.length() && s.charAt(i+1) != \'o\') continue;\n while(i + 1 < s.length() && s.charAt(i+1) == \'o\') {\n oflg = true;\n i++;\n }\n if(i + 1 < s.length() && s.charAt(i+1) != \'u\') continue;\n while(i + 1 < s.length() && s.charAt(i+1) == \'u\') {\n uflg = true;\n i++;\n }\n if(aflg && eflg && iflg && oflg && uflg) {\n maxi = Math.max(maxi, i - startIdx + 1);\n }\n }\n }\n return maxi;\n }\n}\n```
1
0
['String', 'Sliding Window', 'Java']
0
longest-substring-of-all-vowels-in-order
🔥VERY SIMPLE LOGIC using only vector🔥🔥. Beginner friendly and easy to understand.
very-simple-logic-using-only-vector-begi-13ye
\n# Complexity\n- Time complexity:\n O(n) \n\n- Space complexity:\n O(1) \n\n# Code\n\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word)
Saksham_Gulati
NORMAL
2024-06-19T14:28:45.530530+00:00
2024-06-19T14:28:45.530558+00:00
206
false
\n# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n $$O(1)$$ \n\n# Code\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int i=0,j=0,n=word.size();\n int mx=0;\n vector<char>v={\'a\',\'e\',\'i\',\'o\',\'u\'};\n while(j<n)\n {\n if(word[j]==\'a\')\n {\n i=j;\n int k=0;\n char c=v[k];\n while(j<n)\n {\n while(j+1<n&&c==word[j+1])\n {\n j++;\n }\n if(k==4) mx=max(mx,j-i+1);\n k++;\n if(k==5)break;\n if(j+1<n&&v[k]!=word[j+1])break; \n c=v[k];\n j++;\n }\n }\n j++;\n }\n return mx;\n }\n};\n```
1
0
['Two Pointers', 'Sliding Window', 'C++']
0
longest-substring-of-all-vowels-in-order
✅✅Easiest Python Solution | O(n) | Simple linear✅✅no stack/greedy/sliding window/two pointers
easiest-python-solution-on-simple-linear-ywse
Approach\nc is the current counter\nm is the max\np is the pointer on the array a, remembering the current char\n\nIncrement c if the current char is the pointe
nicostoehr
NORMAL
2024-05-08T21:48:41.126558+00:00
2024-05-08T21:48:41.126592+00:00
33
false
# Approach\nc is the current counter\nm is the max\np is the pointer on the array a, remembering the current char\n\nIncrement c if the current char is the pointer char.\nIncrement c and p if the current char is the next pointer char.\nOtherwise make c the new m if the pointer is at the end of the array c is bigger than m. Set p to -1 and keep it at that while we do not start a new chain with the first letter "a".\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n\n# Code\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n a = ["a", "e", "i", "o", "u"]\n c, m, p, = 0, 0, 0\n\n for x in word:\n if p >= 0 and x == a[p]: c += 1\n elif -1 < p < 4 and c > 0 and x == a[p+1]:\n c += 1\n p += 1\n else: \n if p == 4 and c > m: m = c\n c = 0\n if x == "a": \n c += 1\n p = 0\n else: p = -1\n return m if p != 4 else max(c,m)\n```
1
0
['Python3']
0
longest-substring-of-all-vowels-in-order
Fast Java Solution
fast-java-solution-by-seif_hamdy-6dg6
Intuition\nI will consider the vowels as stages with their alphabetical order and make sure no stages have been skipped and we have passed by all stages to find
Seif_Hamdy
NORMAL
2024-02-19T08:40:52.115631+00:00
2024-02-19T08:40:52.115655+00:00
44
false
# Intuition\nI will consider the vowels as stages with their alphabetical order and make sure no stages have been skipped and we have passed by all stages to find the complete substring\n# Approach\nApproach is described within the comments\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int maxLength = 0;\n // edge case\n if (word.length() < 5) {\n return maxLength;\n }\n int startLocation = 0;\n int currentStage = 0;\n int vowelStage = 0;\n boolean sequenceStarted = false;\n // main for loop on all characters\n for (int i = 0; i < word.length(); i++) {\n char c = word.charAt(i);\n vowelStage = getStage(c);\n // starting our sequence\n if (!sequenceStarted && vowelStage == 1) {\n currentStage = 1;\n sequenceStarted = true;\n startLocation = i;\n }\n // ending the sequence\n else if (sequenceStarted && vowelStage < currentStage) {\n sequenceStarted = false;\n currentStage = 0;\n // we may restart the sequence if we meet an \'a\'\n if (vowelStage == 1) {\n i--;\n }\n } else if (sequenceStarted && vowelStage >= currentStage) {\n // in middle of sequence\n if (currentStage == 5) {\n // expanding the complete substring\n if (vowelStage == 5) {\n if (((i - startLocation + 1)) > maxLength) {\n maxLength = i - startLocation + 1;\n }\n } else {\n // sequence ended by a stage less than 5\n sequenceStarted = false;\n currentStage = 0;\n // restart sequence possible\n if (vowelStage == 1) {\n i--;\n }\n }\n } else {\n // upgrading stage\n if (vowelStage == (currentStage + 1)) {\n currentStage = vowelStage;\n if (vowelStage == 5) {\n if (((i - startLocation) + 1) > maxLength) {\n maxLength = i - startLocation + 1;\n }\n }\n // found the same stage still present\n } else if (vowelStage == currentStage) {\n continue;\n } else {\n // a stage has been skipped\n sequenceStarted = false;\n currentStage = 0;\n }\n }\n }\n }\n return maxLength;\n }\n\n private int getStage(char c) {\n int stage;\n switch (c) {\n case \'a\':\n stage = 1;\n break;\n case \'e\':\n stage = 2;\n break;\n case \'i\':\n stage = 3;\n break;\n case \'o\':\n stage = 4;\n break;\n case \'u\':\n stage = 5;\n break;\n default:\n stage = 0;\n }\n return stage;\n }\n}\n```
1
0
['String', 'Sliding Window', 'Java']
0
longest-substring-of-all-vowels-in-order
Easy understandable sountion in java with o(N) complexity
easy-understandable-sountion-in-java-wit-4tqs
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
GantlaRahul
NORMAL
2024-02-06T07:39:31.762937+00:00
2024-02-06T07:39:31.762990+00:00
110
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 longestBeautifulSubstring(String word) {\n char[] arr = {\'a\', \'e\', \'i\', \'o\', \'u\'};\n int index = 0;\n int maxLength = 0;\n int len = 0;\n int s = 0;\n int i = 0;\n\n while (i < word.length()) {\n if (arr[index] == word.charAt(i)) {\n len++;\n s = 1;\n i++;\n } else if (index != 4 && arr[index + 1] == word.charAt(i) && s == 1) {\n len++;\n index++;\n i++;\n } else {\n if (index == 4) {\n maxLength = Math.max(maxLength, len);\n }\n s = 0;\n index = 0;\n len = 0;\n if(word.charAt(i)!=\'a\'){\n i++;\n }\n }\n }\n\n if (index == 4) {\n maxLength = Math.max(maxLength, len);\n }\n\n return maxLength;\n }\n}\n\n```
1
0
['Java']
0
longest-substring-of-all-vowels-in-order
simple easy brute force & sliding window
simple-easy-brute-force-sliding-window-b-zcs3
\n# Complexity\n- Time complexity:\n O(n*n) \n\n- Space complexity:\n O(1) \n \n\n\nclass Solution {\n \n\n public int longestBeautifulSubstring(String wo
indrajeetyadav932001
NORMAL
2023-09-07T18:41:22.698340+00:00
2023-09-07T18:42:21.074277+00:00
137
false
\n# Complexity\n- Time complexity:\n $$O(n*n)$$ \n\n- Space complexity:\n $$O(1)$$ \n \n```\n\nclass Solution {\n \n\n public int longestBeautifulSubstring(String word) {\n int j=0,ans=0,n=word.length();\n for(int i=0;i<n;i++){\n if(word.charAt(i)==\'a\'){\n int cnt=0;\n for(j=i+1;j<n && word.charAt(j-1)<=word.charAt(j);j++)\n cnt+=word.charAt(j-1)<word.charAt(j)?1:0;\n \n if(cnt==4) ans=Math.max(ans,j-i);\n i=j-1;\n }\n }\n return ans;\n\n }\n}\n```\n# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n $$O(1)$$ \n\n# Code\n```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int n=word.length(),i=0,j=0,ans=0,cnt=1;\n\n for(j=1;j<n;j++){\n if(word.charAt(j)>word.charAt(j-1)) cnt++;\n if(word.charAt(j)<word.charAt(j-1)){\n cnt=1;\n i=j;\n } \n if(cnt==5) ans=Math.max(ans,j-i+1);\n }\n return ans;\n }\n}\n```\n\n
1
0
['Two Pointers', 'String', 'Sliding Window', 'Java']
0
longest-substring-of-all-vowels-in-order
Sliding Window Template | C++
sliding-window-template-c-by-mayanksingh-cvxy
\n\n# Code\n\nclass Solution {\npublic:\n int longestBeautifulSubstring(string nums) {\n int n=nums.size();\n if (n<5) return 0;\n int c
MayankSinghNegi
NORMAL
2023-05-25T04:39:13.105258+00:00
2023-05-25T04:39:13.105311+00:00
141
false
\n\n# Code\n```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string nums) {\n int n=nums.size();\n if (n<5) return 0;\n int count=1,maxi=0;\n set<char> st;\n st.insert(nums[0]);\n for (int i=1;i<n;i++)\n {\n if (nums[i]>=nums[i-1])\n count++;\n else\n {\n st.clear();\n count=1;\n }\n st.insert(nums[i]);\n if (st.size()==5)\n maxi=max(maxi,count);\n }\n return maxi;\n }\n};\n```
1
0
['C++']
0
longest-substring-of-all-vowels-in-order
Brute Force
brute-force-by-gaurav_sengar-v5uj
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
Gaurav_sengar
NORMAL
2023-03-06T12:50:12.690331+00:00
2023-03-06T12:50:12.690367+00:00
267
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 longestBeautifulSubstring(string s) {\n int n=s.size();\n int i=0;\n int maxi=0;\n if(s.size()<5)\n {\n return 0;\n }\n while(i<n-4)\n {\n if(s[i]==\'a\')\n {\n int j=i+1;\n int cnt=1;\n char prev=\'a\';\n while(j<n){\n if(prev==\'a\')\n {\n if(s[j]==\'a\' or s[j]==\'e\'){\n prev=s[j];\n cnt++;\n j++;\n }\n else{\n break;\n }\n }\n else if(prev==\'e\'){\n if(s[j]==\'e\' or s[j]==\'i\'){\n prev=s[j];\n cnt++;\n j++;\n }\n else{\n break;\n }\n }\n else if(prev==\'i\'){\n if(s[j]==\'i\' or s[j]==\'o\'){\n prev=s[j];\n cnt++;\n j++;\n }\n else{\n break;\n }\n }\n else if(prev==\'o\'){\n if(s[j]==\'o\' or s[j]==\'u\'){\n prev=s[j];\n cnt++;\n j++;\n }\n else{\n break;\n }\n }\n else if(prev==\'u\'){\n if(s[j]==\'u\'){\n prev=s[j];\n cnt++;\n j++;\n }\n else{\n break;\n }\n }\n if(prev==\'u\'){\n maxi=max(maxi,cnt);\n }\n }\n //maxi=max(maxi,cnt);\n i=j;\n }\n else{\n i++;\n }\n }\n return maxi;\n }\n};\n```
1
0
['C++']
0
longest-substring-of-all-vowels-in-order
C++ Best Solution||Easy to Understand
c-best-solutioneasy-to-understand-by-ret-rtwh
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string w) \n {\n int len=1,cnt=1,max_len=0;\n for(int i=1;iw[i-1])\n
return_7
NORMAL
2022-09-07T18:41:37.494515+00:00
2022-09-07T18:41:37.494560+00:00
344
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string w) \n {\n int len=1,cnt=1,max_len=0;\n for(int i=1;i<w.size();i++)\n {\n if(w[i]==w[i-1])\n {\n len++;\n }\n else if(w[i]>w[i-1])\n {\n len++;\n cnt++;\n }\n else\n {\n len=1;\n cnt=1;\n }\n if(cnt==5)\n {\n max_len=max(len,max_len);\n }\n }\n return max_len;\n \n }\n};\n//if you like the solution plz upvote.
1
0
['C']
0
longest-substring-of-all-vowels-in-order
C++ || Stack || Esay to Understand
c-stack-esay-to-understand-by-himanshu18-gkxh
class Solution {\npublic:\n \n \n int longestBeautifulSubstring(string word) {\n \n int n = word.size();\n stack st;\n unordered_
Himanshu1802
NORMAL
2022-07-20T03:15:32.673205+00:00
2022-07-20T03:15:32.673249+00:00
36
false
class Solution {\npublic:\n \n \n int longestBeautifulSubstring(string word) {\n \n int n = word.size();\n stack<char> st;\n unordered_map<char,int> mp;\n int res = 0;\n \n \n for(int i=0; i<n; i++){\n \n char ch = word[i];\n \n if(!st.empty() and st.top() > ch){\n \n mp.clear();\n while(!st.empty()) st.pop();\n \n }\n \n mp[ch]++;\n st.push(ch);\n \n if(mp.size() >= 5){\n \n if(st.size() > res){\n res = st.size();\n }\n }\n \n }\n \n \n return res;\n \n }\n};
1
0
['Stack', 'C', 'C++']
0
longest-substring-of-all-vowels-in-order
Easy to understand Explaination
easy-to-understand-explaination-by-sinha-1zfa
\n\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n char[] arr = word.toCharArray();\n int maxLength = 0;\n \n
sinhaneha455
NORMAL
2022-07-16T16:50:44.131983+00:00
2022-07-16T16:51:50.127039+00:00
78
false
```\n\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n char[] arr = word.toCharArray();\n int maxLength = 0;\n \n for(int i = 1 ; i < word.length() ; i++){\n if(arr[i-1] == \'a\'){ //we know that our valid window will only start from a , throgh this line we can increase the performance because it is not checking each and every substring.\n int currentLength = 1; //because it includes that char which is present at i-1th index.i.e \'a\' = 1(length)\n int uniqueCharacter = 1; //the char present at i-1th index would be first unique character for that substring/window i.e \'a\'\n while( i < word.length() && arr[i-1] <= arr[i]){ //check whether arr[i-1]<= arr[i] to maintain the vowels order.\n uniqueCharacter += arr[i-1] < arr[i] ? 1 : 0; //unique character will only increase when arr[i-1] is strictly smaller than arr[i].\n currentLength += 1; // currentLength would be increase because the window can have multiple same characters but in a maintained order.\n i++; //increase the window size since we need to find out the longest as our ans.\n \n }\n \n if(uniqueCharacter == 5){ //that means in your current window you have all vowels in an order ( a , e, i , o , u)\n maxLength = Math.max(maxLength , currentLength);\n \n }\n }\n }\n \n return maxLength; \n \n }\n}\n```\n\n**If you found this useful then please upvote <3**
1
0
[]
0
longest-substring-of-all-vowels-in-order
Nice Question with alot of Brainstorming required || CPP || Moderate || Sliding window
nice-question-with-alot-of-brainstorming-2mpg
\nclass Solution {\npublic:\n int cnt=0;\n bool help(char a,char b){\n if(a==b) return true;\n else if(a==\'a\' && b==\'e\'){\n c
PeeroNappper
NORMAL
2022-06-16T17:30:54.935660+00:00
2022-06-16T17:30:54.935706+00:00
261
false
```\nclass Solution {\npublic:\n int cnt=0;\n bool help(char a,char b){\n if(a==b) return true;\n else if(a==\'a\' && b==\'e\'){\n cnt++;\n return true;\n }\n else if(a==\'e\' && b==\'i\'){\n cnt++;\n return true;\n }\n else if(a==\'i\' && b==\'o\'){\n cnt++;\n return true;\n }\n else if(a==\'o\' && b==\'u\'){\n cnt++;\n return true;\n }\n return false;\n }\n int longestBeautifulSubstring(string s) {\n int maxi=0,start=0;\n char p=s[0];\n for(int i=0;i<s.length();i++){\n if(help(p,s[i]) || s[i]==\'u\'){\n p=s[i];\n if(s[i]==\'u\' && cnt==4) maxi=max(maxi,i-start+1);\n }\n else{\n cnt=0;\n while(i<s.length() && s[i]!=\'a\') i++;\n p=\'a\';\n start=i;\n }\n }\n return maxi;\n }\n};\n```
1
0
['Sliding Window', 'C++']
0
longest-substring-of-all-vowels-in-order
Short & clean c++ intuitive code using sliding window & unordered_map
short-clean-c-intuitive-code-using-slidi-tfxj
\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n unordered_map<char, int> mp;\n int i = 0, ans = 0; \n for(i
yashrajyash
NORMAL
2022-06-02T16:19:52.953405+00:00
2022-06-02T16:19:52.953436+00:00
86
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n unordered_map<char, int> mp;\n int i = 0, ans = 0; \n for(int j=0; j<word.length(); j++) {\n if(mp.empty() && word[j] == \'a\') {\n i = j;\n mp[word[j]]++;\n } else if(!mp.empty()) {\n if(word[j] < word[j-1]) {\n mp.clear();\n j--;\n continue;\n }\n mp[word[j]]++;\n if(mp.size() == 5) ans = max(ans, j - i + 1); \n }\n }\n return ans;\n }\n};\n```
1
0
['Two Pointers', 'C', 'Sliding Window']
0
longest-substring-of-all-vowels-in-order
JAVA | Lets Bitmask | O(1) space , O(n) time
java-lets-bitmask-o1-space-on-time-by-pr-c3tz
We create a bitmask of all the vowlels i.e a , e , i , o , u.\n2. for every character in word we update the currentMask , where charAt(i) >= charAt(i - 1).\n3.
PrasadDas
NORMAL
2022-05-12T17:44:27.122269+00:00
2022-05-12T17:45:17.916756+00:00
106
false
1. We create a bitmask of all the vowlels i.e a , e , i , o , u.\n2. for every character in word we update the currentMask , where charAt(i) >= charAt(i - 1).\n3. Where currentMask = originalMask , this could be a possible solution so we update out result\n4. where the order breaks i.e charAt(i) > charAt(i - 1) , we reset our current mask.\n\n```\n\n```public int longestBeautifulSubstring(String word) {``\n int originalMask = 0 , res = 0;\n\t\t int currentMask = 0 | (1 << word.charAt(0) - \'a\');\n char[] vowels = {\'a\' , \'e\' , \'i\' , \'o\' , \'u\'};\n \n for(int i = 0 ; i < vowels.length ; i++) \n\t\t originalMask |= 1 << (vowels[i] - \'a\');\n \n for(int i = 1 , last = 0; i < word.length() ; i++) { \n \tif(word.charAt(i) >= word.charAt(i - 1)) {\n \t\tcurrentMask |= 1 << (word.charAt(i) - \'a\');\n \t\tres = originalMask == currentMask ? Math.max(res , i - last + 1) : res;\n \t}\n \telse {\n \t\tcurrentMask = 0 | 1 << (word.charAt(i) - \'a\');\n \t last = i;\n \t}\n } \n return res;\n }
1
0
['Bitmask', 'Java']
0
longest-substring-of-all-vowels-in-order
two pointers
two-pointers-by-ttn628826-2s04
cpp\n// use this to simplify the comparison between vowels\nmap<char, int> idx = {\n\t{\'a\', 0}, \n\t{\'e\', 1},\n\t{\'i\', 2},\n\t{\'o\', 3},\n\t{\'u\', 4}\n}
ttn628826
NORMAL
2022-05-08T10:33:50.738613+00:00
2022-05-08T11:01:34.545250+00:00
201
false
```cpp\n// use this to simplify the comparison between vowels\nmap<char, int> idx = {\n\t{\'a\', 0}, \n\t{\'e\', 1},\n\t{\'i\', 2},\n\t{\'o\', 3},\n\t{\'u\', 4}\n};\n\nint longestBeautifulSubstring(string word) {\n\tint ret = 0;\n\t\n\t// for each char in word,\n\tfor (int i = 0; i < word.size(); ++i)\n\t{\n\t\t// we only consider possible start of substring, which should be \'a\',\n\t\tif (word[i] == \'a\')\n\t\t{\n\t\t\tint j = i + 1;\n\t\t\t// record the max vowel in this substring,\n\t\t\tchar ma = \'a\';\n\t\t\t\n\t\t\t// keep growing the current substring,\n\t\t\twhile (j < word.size())\n\t\t\t{\n\t\t\t\t// meet a same char, do nothing and keep growing\n\t\t\t\tif (ma == word[j])\n\t\t\t\t\t;\n\t\t\t\t// meet a next vowel, increase the ma and keep growing\n\t\t\t\telse if (idx[ma] + 1 == idx[word[j]])\n\t\t\t\t\tma = word[j];\n\t\t\t\t// invalid\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\t++ j;\n\t\t\t}\n\t\t\t\n\t\t\t// meet 2 criteria, record the max length\n\t\t\tif (ma == \'u\')\n\t\t\t\tret = max(ret, j - i);\n\t\t\t\n\t\t\t// jump to the end of this substring, make no sense to consider these chars.\n\t\t\ti = j - 1;\n\t\t}\n\t}\n\t\n\treturn ret;\n}\n```\n
1
0
['Two Pointers', 'C']
1
longest-substring-of-all-vowels-in-order
C++ || Sliding Window || Time Complexity - O(N)
c-sliding-window-time-complexity-on-by-l-oaer
\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int n = word.size(); \n if(n < 5){\n return 0;\n
lcninja_43
NORMAL
2022-04-18T09:56:32.522780+00:00
2022-04-18T09:56:32.522823+00:00
124
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int n = word.size(); \n if(n < 5){\n return 0;\n }\n unordered_map<char,char> m;\n m[\'a\'] = \'e\', m[\'e\'] = \'i\', m[\'i\'] = \'o\', m[\'o\'] = \'u\';\n int maxlen = 0, i = 0;\n while(i < n){\n if(word[i] == \'a\'){\n // Continue expanding the window till the point you get valid characters in correct order\n int j = i;\n for(; j+1 < n; j++){\n // If at character a -> next will be \'a\' or \'e\'\n // It at character e -> next will be \'e\' or \'i\'\n // It at character i -> next will be \'i\' or \'o\'\n // It at character o -> next will be \'o\' or \'u\'\n // It at character u -> next will be \'u\' otherwise stop (Now you cant expand current window)\n if(word[j+1] == word[j] or (m.count(word[j]) && (word[j+1] == m[word[j]]))){\n continue;\n }else{\n break;\n }\n }\n // Current window is valid iff j points at \'u\'\n if(word[j] == \'u\'){\n maxlen = max(maxlen, j-i+1);\n }\n // Next valid window will start at j+1\n i = j;\n }\n i++;\n }\n return maxlen;\n }\n};\n```
1
0
['Sliding Window']
0
longest-substring-of-all-vowels-in-order
easy to understand c++ solution
easy-to-understand-c-solution-by-ritesh_-4dvw
\n int longestBeautifulSubstring(string word) {\n // please do a dry run on this example "aeiaaioaaaaeiiiiouuuooaauuaeiu"\n// you will understand it better.\n
Ritesh_Mangdare
NORMAL
2022-04-03T10:09:45.737114+00:00
2022-04-03T10:09:45.737155+00:00
162
false
```\n int longestBeautifulSubstring(string word) {\n // please do a dry run on this example "aeiaaioaaaaeiiiiouuuooaauuaeiu"\n// you will understand it better.\n int i=0,j=0;// two pointers\n int maxlen=0;\n char curr=word[0];// we will use it check that next vowel appeared should be greated than curr\n \n int appeared=1;// counter for number of distinct vowels appeared till now\n while(i<word.size() && j<word.size()){\n if(word[i]==\'a\' || word[i]==\'e\' || word[i]==\'i\' || word[i]==\'o\' || word[i]==\'u\'){\n \n if(curr> word[i]){// when sorted order gets interrupted\n \n if(appeared==5) maxlen=max(maxlen,i-j);// if all five vowels appeared\n j=i;\n appeared=1;\n curr=word[i];\n \n }\n else {\n \n if(curr != word[i]) appeared++;// counting distinct vowels in window\n curr=word[i];\n i++;\n }\n \n }\n else i++;\n }\n if(appeared==5) maxlen=max(maxlen,i-j);\n return maxlen;\n }\n```
1
0
['C', 'Sliding Window', 'C++']
0
longest-substring-of-all-vowels-in-order
simple Java solution
simple-java-solution-by-sugale85-adfb
\npublic int longestBeautifulSubstring(String word) {\n int cnt = 1;\n int len = 1;\n int max_len = 0;\n for (int i = 1; i != word.
sugale85
NORMAL
2022-02-20T12:16:55.843659+00:00
2022-02-20T12:17:21.542505+00:00
186
false
```\npublic int longestBeautifulSubstring(String word) {\n int cnt = 1;\n int len = 1;\n int max_len = 0;\n for (int i = 1; i != word.length(); ++i) {\n if (word.charAt(i - 1) == word.charAt(i)) {\n ++len;\n } else if (word.charAt(i - 1) < word.charAt(i)) {\n ++len;\n ++cnt;\n } else {\n cnt = 1;\n len = 1;\n }\n \n if (cnt == 5) {\n max_len = Math.max(max_len, len);\n }\n }\n return max_len;\n }\n```
1
0
['Java']
0
longest-substring-of-all-vowels-in-order
C++ short easy to understand , using unordered_set
c-short-easy-to-understand-using-unorder-txk2
\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int ans = 0;\n int start = 0;\n unordered_set<char> set;\n
larryleizhou
NORMAL
2022-02-18T23:19:01.844732+00:00
2022-02-18T23:19:01.844767+00:00
81
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n int ans = 0;\n int start = 0;\n unordered_set<char> set;\n set.insert(word[0]);\n for(int i=1; i<word.size(); ++i) {\n if (word[i]<word[i-1]) { \n start = i;\n set.clear();\n }\n set.insert(word[i]);\n if (set.size()==5) ans = max(ans, i - start + 1);\n }\n return ans;\n }\n};\n```
1
0
['C']
0
longest-substring-of-all-vowels-in-order
Kotlin Sliding window O(n)
kotlin-sliding-window-on-by-ashabib-czm5
\n\nfun longestBeautifulSubstring(word: String): Int {\n\t// edge cases\n if (word.length < 5) {\n return 0\n }\n if (word.toList().distinct().s
ashabib
NORMAL
2022-01-03T12:14:44.522058+00:00
2022-01-03T12:14:44.522089+00:00
84
false
```\n\nfun longestBeautifulSubstring(word: String): Int {\n\t// edge cases\n if (word.length < 5) {\n return 0\n }\n if (word.toList().distinct().size < 5) {\n return 0\n }\n\t\n val characters = word.toCharArray()\n var counter = 1\n var maxValue = 0\n var currentLength = 1\n\t\n for (index in 1 until characters.size) {\n when {\n characters[index - 1] == characters[index] -> currentLength++\n characters[index - 1] < characters[index] -> {\n currentLength++\n counter++\n }\n else -> {\n currentLength = 1\n counter = 1\n }\n }\n if (counter == 5) maxValue = max(maxValue, currentLength)\n }\n return maxValue\n}\n```
1
0
['Sliding Window', 'Kotlin']
0
longest-substring-of-all-vowels-in-order
Python Sliding Window
python-sliding-window-by-pathrise-fellow-6nau
So here is the method of thinking. \nThink brute force first. If you can\'t get the brute force correct you have never understood sliding window. For every ques
pathrise-fellows
NORMAL
2021-11-22T06:49:18.222421+00:00
2021-11-22T06:49:18.222457+00:00
98
false
So here is the method of thinking. \nThink brute force first. If you can\'t get the brute force correct you have never understood sliding window. For every question out there in sliding window no matter how easy/hard it is solve it using brute force even if you know the answer. Understand very clearly in the brute force what is being repeated in every iteration. Figure out how you can use the previous iteration in the new iteration. If you can figure out this, then sliding window comes down to just coding. Stick to a pattern that you can get comfortable with and solve every question with just one rule\nBrute first -> Sliding window next using the patttern you have learnt all the along the way. \n\n\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n maxlen = 0\n order = {"a": 0, "e": 1, "i": 2, "o": 3, "u": 4}\n \n if len(word) == 0:\n return 0\n prev = word[0]\n seen = set(prev)\n start = 1\n for end, char in enumerate(word, 1):\n if order[char] >= order[prev]:\n seen.add(char)\n if len(seen) == 5:\n maxlen = max(maxlen, end - start + 1)\n prev = char\n elif order[char] < order[prev]:\n seen = set()\n seen.add(char)\n start = end\n prev = char\n else:\n seen.add(char)\n prev = char\n return maxlen\n \n```
1
0
[]
0
longest-substring-of-all-vowels-in-order
Python Sliding Window Method with Explanation and Extension
python-sliding-window-method-with-explan-ml4i
\nclass Solution:\n def longestBeautifulSubstring(self, word):\n n = len(word)\n length = 0\n order = {"a": 0, "e": 1, "i": 2, "o": 3, "
jinghuayao
NORMAL
2021-10-16T05:10:19.280568+00:00
2021-10-16T06:07:39.987380+00:00
93
false
```\nclass Solution:\n def longestBeautifulSubstring(self, word):\n n = len(word)\n length = 0\n order = {"a": 0, "e": 1, "i": 2, "o": 3, "u": 4}\n l, r = 0, 0\n while l < n:\n \n # 1. Find the index of "a" after pointer l\n if word[l] != "a":\n l += 1\n continue\n # 2. Expand the window\n r = l + 1\n while r < n and (\n (order[word[r - 1]] == order[word[r]])\n or (order[word[r - 1]] + 1 == order[word[r]])\n ):\n r += 1\n # Once come out of the inner while loop, check the below\n # if condition to see if the window from l up to r-1 ending with "u"\n if word[r - 1] == "u":\n length = max(length, r - l)\n # 3. reset left side of the window to check if\n # there are further desired beautiful substring \n l = r\n return length\n\n```\nQuestion: What if we allow other characters to appear in word, and still ask: find longest substring which is beautiful in the sense that the substring allow non-vowels and must contain all the vowels and the vowels are in sorted order?\n\nComment: Modify the solution to get the answer.\nNote: Below code cetainly also solve leetcode 1839 which is a simpler/special case.\n```\ndef findBeautifulSubstring(word):\n res = 0\n order = {"a": 0, "e": 1, "i": 2, "o": 3, "u": 4}\n # first find a\n n = len(word)\n i = 0\n while i < n:\n if word[i] != "a":\n i += 1\n continue\n\n j = i + 1\n prev_vowel = word[j - 1]\n while j < n:\n if word[j] not in order:\n j += 1\n else:\n if (\n order[word[j]] == order[prev_vowel]\n or order[word[j]] == 1 + order[prev_vowel]\n ):\n prev_vowel = word[j]\n j += 1\n else:\n break\n\n if prev_vowel == "u":\n t = i - 1\n while t >= 0 and (word[t] not in order):\n t -= 1\n res = max(res, j - t - 1)\n\n i = j\n return res\n\n\nfor word in words:\n print(findBeautifulSubstring(word))\n\nprint(findBeautifulSubstring("xyzaccceiouyyyyaaaaaaaaaaaaaaaeiou")) # return 23\nprint(findBeautifulSubstring("xyzaccceiouyyyyabafaaagaaaaaaaaaaeiou")) # return 26 b/c add b, f, g in the previous length 23 substring\nprint(findBeautifulSubstring("aaaaaaaaaaaaaaaeiou")) # return 19\nprint(findBeautifulSubstring("aeiaaioaaaaeiiiiouuuooaauuaeiu")) # return 13\nprint(findBeautifulSubstring("aeeeiiiioooauuuaeiou")) # return 5\nprint(findBeautifulSubstring("aeeeiiiioooauuuaeiouyao")) # return 6\n```\n
1
0
[]
0
longest-substring-of-all-vowels-in-order
JAVA || Sliding Window || if -else || easy solution by 2 methods
java-sliding-window-if-else-easy-solutio-g3s2
\n public int longestBeautifulSubstring(String word) {\n \n int count =1,vowels=1,ans=0;\n \n for(int i=1;i<word.length();i++){\n
ayushx
NORMAL
2021-07-30T12:30:25.313831+00:00
2021-07-30T12:45:59.558955+00:00
277
false
```\n public int longestBeautifulSubstring(String word) {\n \n int count =1,vowels=1,ans=0;\n \n for(int i=1;i<word.length();i++){\n char cur=word.charAt(i);\n char pre=word.charAt(i-1);\n \n if(pre>cur){\n count=1;\n vowels=1;\n }else if(pre < cur){\n count++;\n vowels++;\n }else{\n count++;\n } \n \n if(vowels==5){\n ans=Math.max(ans,count);\n } \n \n \n }\n return ans;\n \n \n }\n```\n **Sliding window:-**\n```\n int i=0,j=1;\n while(j<word.length()){\n \n if(word.charAt(j)<word.charAt(j-1)){\n i=j;\n count=1;\n }\n \n else if(word.charAt(j)!=word.charAt(j-1)) {\n count++;\n }\n \n if(count==5){\n ans=Math.max(ans,j-i+1);\n }\n \n j++;\n } \n \n \n return ans; \n \n```\nplease upvote it if you find it simple to understand
1
0
['Sliding Window', 'Java']
0
longest-substring-of-all-vowels-in-order
c++ Solution || Heavy one
c-solution-heavy-one-by-ngaur6834-yb9v
\tint longestBeautifulSubstring(string word) {\n int n = word.length();\n if(n == 0){\n return 0;\n }\n \n unorder
ngaur6834
NORMAL
2021-07-30T06:22:17.973111+00:00
2021-07-30T06:22:17.973150+00:00
155
false
\tint longestBeautifulSubstring(string word) {\n int n = word.length();\n if(n == 0){\n return 0;\n }\n \n unordered_map<char, int> mp;\n mp[\'a\'] = 0;\n mp[\'e\'] = 1;\n mp[\'i\'] = 2;\n mp[\'o\'] = 3;\n mp[\'u\'] = 4;\n \n int ans = 0;\n int count = 1;\n unordered_set<char> visited;\n visited.insert(word[0]);\n \n for(int i=1; i<n; i++){\n if((mp[word[i]] - mp[word[i-1]]) >= 0 && (mp[word[i]] - mp[word[i-1]]) <= 1){\n visited.insert(word[i]);\n count++;\n bool flag = true;\n \n if(word[i] == \'u\'){\n for(auto itr: mp){\n if(visited.find(itr.first) == visited.end()){\n flag = false;\n break;\n }\n }\n\n if(flag){\n ans = max(ans, count);\n }\n }\n \n }\n else{\n visited.clear();\n visited.insert(word[i]);\n count = 1;\n }\n }\n \n return ans;\n }
1
0
['C']
0
longest-substring-of-all-vowels-in-order
Java O(n) solution O(1) space, easy to understand. with alternative sliding window solution.
java-on-solution-o1-space-easy-to-unders-5tqt
\nSimple solution \n\nBelow solution runs faster then sliding window.\n\n\n public int longestBeautifulSubstring(String str) {\n char[] vowels = {\'a\
jayantnarwani
NORMAL
2021-07-03T06:33:09.028919+00:00
2021-07-03T06:40:39.731652+00:00
124
false
\nSimple solution \n\nBelow solution runs faster then sliding window.\n\n```\n public int longestBeautifulSubstring(String str) {\n char[] vowels = {\'a\', \'e\', \'i\', \'o\', \'u\'};\n int count = 0, i =0, max = 0, j = 0;\n \n while (i < str.length()) {\n if (j >= vowels.length) {\n j = 0;\n }\n\n if (str.charAt(i) == vowels[j]) {\n // string char == previous vowel\n count++; \n } else if (j < vowels.length-1 && str.charAt(i) == vowels[j+1] && count > 0) {\n // string char is next vowel, a -> e\n count++; j++;\n } else {\n // precondition break\n j= 0; count = str.charAt(i) == vowels[j] ? 1:0;\n }\n i++;\n if (j == 4) {\n max = Math.max(max, count);\n }\n }\n\n return max;\n }\n```\n\n\nSliding window solution \n\n```\n public int longestBeautifulSubstring(String word) {\n int max = 0;\n Set<Character> set = new HashSet<>();\n int start = 0,end = 0;\n int n = word.length();\n \n while(end < n){\n \n if(end > 0 && word.charAt(end) < word.charAt(end-1)){\n set.clear();\n start = end;\n }\n set.add(word.charAt(end));\n \n if(set.size() == 5)\n max = Math.max(max,end-start+1);\n end++;\n \n }\n return max;\n }\n```
1
0
[]
0
longest-substring-of-all-vowels-in-order
C++ || Two Pointers || Beats 100% Time and Space
c-two-pointers-beats-100-time-and-space-hr97f
class Solution {\npublic:\n\n int longestBeautifulSubstring(string word) {\n int i=0;\n int j=1;\n int count=1;\n int ans=0;\n
Mohammed_Qubaisuddin
NORMAL
2021-07-02T09:16:58.590738+00:00
2021-07-02T09:16:58.590768+00:00
76
false
class Solution {\npublic:\n\n int longestBeautifulSubstring(string word) {\n int i=0;\n int j=1;\n int count=1;\n int ans=0;\n char ch=word[0];\n while(j<word.length()){\n if(ch==word[j]){\n j++;\n continue;\n }\n if(ch<word[j]){\n ch=word[j];\n j++;\n count++;\n }else{\n if(count==5){\n ans=max(ans,j-i);\n }\n i=j;\n j++;\n ch=word[i];\n count=1;\n }\n }\n if(count==5){\n ans=max(ans,j-i);\n }\n return ans;\n }\n};
1
0
[]
0
longest-substring-of-all-vowels-in-order
Simple C++ Solution
simple-c-solution-by-four901-oybi
\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word)\n {\n int maxi=0;\n for(int i=0;i<word.length();)\n {\n
Four901
NORMAL
2021-06-14T15:11:40.996938+00:00
2021-06-14T15:11:40.996987+00:00
78
false
```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string word)\n {\n int maxi=0;\n for(int i=0;i<word.length();)\n {\n int a=0,e=0,ii=0,o=0,u=0;\n while(i<word.length())\n {\n if(word[i]!=\'a\')\n {\n break;\n }\n a++;\n i++;\n }\n while(i<word.length())\n {\n if(word[i]!=\'e\')\n {\n break;\n }\n e++;\n i++;\n }\n while(i<word.length())\n {\n if(word[i]!=\'i\')\n {\n break;\n }\n ii++;\n i++;\n }\n while(i<word.length())\n {\n if(word[i]!=\'o\')\n {\n break;\n }\n o++;\n i++;\n }\n while(i<word.length())\n {\n if(word[i]!=\'u\')\n {\n break;\n }\n u++;\n i++;\n }\n if(a>0&&e>0&&ii>0&&o>0&&u>0)\n {\n maxi=max(maxi,a+e+ii+o+u);\n }\n }\n return maxi;\n }\n};\n```
1
0
[]
0
longest-substring-of-all-vowels-in-order
C++ O(n) time , O(1) space
c-on-time-o1-space-by-shubham-khare-xi17
//keep record of previously appeared all vowels in order.\nclass Solution {\n\npublic:\n int longestBeautifulSubstring(string word) {\n \n int
Shubham-Khare
NORMAL
2021-06-03T16:40:59.282506+00:00
2021-06-03T16:45:44.371986+00:00
113
false
//keep record of previously appeared all vowels in order.\nclass Solution {\n\npublic:\n int longestBeautifulSubstring(string word) {\n \n int ans = 0;\n int count=0;\n int fa=0;\n int fe=0;\n int fo=0;\n int fi=0;\n int fu=0;\n if(word[0]==\'a\') {\n fa=1;\n count++;\n }\n \n for(int i =1;i<word.length();i++){\n if(word[i]==\'a\') fa=1;\n if(word[i]==\'e\'&&fa) fe=1;\n if(word[i]==\'i\'&&fa&&fe) fi=1;\n if(word[i]==\'o\'&&fe&&fa&&fi) fo=1;\n if(word[i]==\'u\'&&fa&&fe&&fo&&fi) fu=1;\n\n if(word[i]>=word[i-1]) count++;\n else {\n if(fa&&fe&&fi&&fo&&fu){\n \n ans=max(ans,count);\n }\n fa=0;\n fe=0;\n fo=0;\n fi=0;\n fu=0;\n if(word[i]==\'a\'){\n fa=1;\n count=1;\n }\n else count = 0;\n }\n\t\t\t//Case when last letter is u itself.\n if(fa&&fe&&fi&&fo&&fu)\n ans=max(ans,count);\n }\n return ans;\n \n }\n};
1
0
[]
0