Q.no 1 :- Reverse Vowels of a String
Given a string s, reverse only all the vowels in the string and return it.
Example:
Input: s = "IceCreAm"
Output: "AceCreIm"
Approach
Two-Pointer Technique
We use two pointers — one starting from the beginning (start
) and one from the end (end
) — to scan the string from both sides.Create a Vowel Lookup Object
Create an object namedvowels
containing all vowels in both uppercase and lowercase (i.e.,a, e, i, o, u, A, E, I, O, U
) to allow quick lookup.-
Initialize Pointers
-
start
: initially points to the first character. -
end
: initially points to the last character.
-
-
Loop Through the String
- Use the loop to evaluate the characters at
start
andend
. - Use:
let isStartVowel = vowels[chars[start]]; let isEndVowel = vowels[chars[end]];
- Use the loop to evaluate the characters at
- If both are vowels, swap them and move both pointers (
start++
,end--
). - If
isStartVowel
is false, incrementstart
to skip non-vowels. - If
isEndVowel
is false, decrementend
to skip non-vowels.
-
Continue until the
start
pointer meets or crosses theend
pointer.
Dry Run
📈 Time and Space Complexity
- Time Complexity: O(n) — each character is checked at most once.
- Space Complexity: O(n) — due to splitting the string into a character array.
Code
/**
* @param {string} s
* @return {string}
*/
var reverseVowels = function(s) {
let vowels = {
a: true, e: true, i: true, o: true, u: true,
A: true, E: true, I: true, O: true, U: true
};
let chars = s.split('');
let start = 0;
let end = s.length - 1;
while (start < end) {
let isStartVowel = vowels[chars[start]];
let isEndVowel = vowels[chars[end]];
if(isStartVowel && isEndVowel){
let temp = chars[start]
chars[start] = chars[end];
chars[end] = temp;
start++
end--
}else if(!isStartVowel){
start++
}else if(!isEndVowel){
end--
}
}
return chars.join('');
};
Q.no 2 :- Add Digits
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example
Input: num = 38
Step 1: 3 + 8 = 11
Step 2: 1 + 1 = 2
Output: 2
Approach
There is a math shortcut that helps us jump directly to the final answer without doing all those steps.
Here's the rule:
If the number is 0, just return 0.
Otherwise, use this formula:
Answer = 1 + ((number - 1) % 9)
⏱️ Time and Space:
Time: O(1) → Always takes just one step.
Space: O(1) → Doesn’t use any extra memory.
/**
* @param {string} s
* @return {string}
*/
var reverseVowels = function(s) {
let vowels = {
a: true, e: true, i: true, o: true, u: true,
A: true, E: true, I: true, O: true, U: true
};
let chars = s.split('');
let start = 0;
let end = s.length - 1;
while (start < end) {
let isStartVowel = vowels[chars[start]];
let isEndVowel = vowels[chars[end]];
if(isStartVowel && isEndVowel){
let temp = chars[start]
chars[start] = chars[end];
chars[end] = temp;
start++
end--
}else if(!isStartVowel){
start++
}else if(!isEndVowel){
end--
}
}
return chars.join('');
};
Top comments (0)