Two Pointers
Container With Most Water
Link: https://leetcode.com/problems/container-with-most-water/
Code:
Two pointers;
Time complexity: O(n);
Remove Nth Node From End of List
Link: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Code:
add an auxiliary "dummy" node;
two pointers;
Time complexity: O(L), where L is the length of the list;
Reverse Vowels of a String
Link: https://leetcode.com/problems/reverse-vowels-of-a-string/
To solve the problem of reversing only the vowels in a given string, we can use a two-pointer approach. Here's a step-by-step breakdown of the solution:
Identify Vowels: First, identify what constitutes a vowel. For this problem, the vowels are 'a', 'e', 'i', 'o', 'u' (both lowercase and uppercase).
Two-Pointer Technique: Use two pointers, one starting from the beginning of the string and the other from the end. Move these pointers towards each other:
The left pointer moves to the right until it finds a vowel.
The right pointer moves to the left until it finds a vowel.
Swap the vowels at these pointers.
Continue the Process: Continue the process until the two pointers meet or cross each other.
Here's the Python code to achieve this:
Explanation:
Line 1: Define the function
reverseVowels
which takes a strings
as input.Line 2: Create a set of vowels for quick lookup.
Line 3: Convert the string to a list since strings are immutable in Python.
Line 4: Initialize two pointers,
left
at the start andright
at the end of the list.Lines 6-15: Loop until the two pointers meet or cross.
Lines 7-9: Move the
left
pointer to the right if the current character is not a vowel.Lines 10-12: Move the
right
pointer to the left if the current character is not a vowel.Lines 13-15: If both pointers point to vowels, swap them and move both pointers towards the center.
Line 17: Convert the list back to a string and return it.
This approach ensures that we only traverse the string once, making the solution efficient with a time complexity of O(n), where n is the length of the string.
Last updated