We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
You're looping through the input string twice, doing the same thing, which breaks a very important rule in programming - DRY (don't repeat yourself). My advice is to try to produce a respone by looping only once through s, which will require vowels to be presented in more efficient way (the problem does not state they have to be stored in an array).
This According to me is very trivial requirement. Although it violates DRY. Asymptotically it does not make difference at all. And if efficiency were an aspect, in some way one could argue that concurrency(which is generally required for large data) would be well implemented in two loops. without using DS like string to store data. (Also your solution may introduce an unecessary (worstcase)O(n) space complexity).
I don't know why people downvoted your answer. It's quite stylish with these spread and ternary operators, and who cares if it loops through the string twice, this means nothing performance-wise, it's much better to have readable code.
vowels.includes(letter) ? console.log(letter) : consonants += letter + '\n';
Here is the "ternary" operator. The '?' says if this thing before the ?, do the thing right after the ?, else do the thing right after the :. It is a shortcut for the if statement. The statement reads: If the letter is found in the vowels, (log it), else add it to the list of consonants with a new line (This is the loop) to be logged in the final console log of consonants without whitespace.
}
console.log(consonants.trim());
}
Although I am fairly sure the complexity of .includes() depends on the array the method is called on, which in this case is small and constant (it's just the 5 vowels).
No, the amount of time has to be dependent on the input. The only way n(o) could happen is if you are doing a calculation not dependent on the length of the input( adition, lowest value, etc).
I did something similar in a one iteration, however I stored the consonents in an actual array whereas you used a string. Is my way less efficient. My reasoning is that behind the scenes I think that javascript is representing strings as an array. Therefore there should be no performance difference.
Why is there a need to store the remaining letters in a var first at the else condition then console.log the var later? Is there a way to console.log the remaining letters right away in the else condition?
Here if we have vowels as String, and call includes method, each time there is an extra work of converting String to array to check if the data is present. So This is happening for N times.
It's not necessary to consider them because input strings are guaranteed to be lowercase:
Complete the vowelsAndConsonants function in the editor below. It has one parameter, a string, s, consisting of lowercase English alphabetic letters (i.e., a through z).
only if you could do var len = s.length; and the use the variable in the for loop will save time. The program will not have to calculate the length eacch time if you do something like this.
You do loop through only once, so you have O(n) time complexity rather than O(2n). That's still linear.
However, by creating this consonants string, you're creating a variable that increases linearly in size with the size of input (worst case). That's O(n) space complexity.
instead of adding all the consonants to a seperarte variable is it not possible to simply remove the vowels (every time the 'if' loop is entered) from the original string and then print the original string itself instead of 'consonants'?
This is where trade of between memory and time complexity comes in
Some people perefer looping twice(linear complexity) and some prefer making use of extra variables.
Thanks for your response, i never used it that way, but i use arrow functions that way if its returning a single statement. Thanks for the heads up. Yeah it sure is a good practice to include the curly braces.
Try to avoid the "includes" method. You will find yourself running into road blocks when creating apps for internet explorer. I would recommend indexOf() which is recognized by IE and all modern browsers.
Day 2: Loops
You are viewing a single comment's thread. Return to all comments →
I did it like this. How good it is?
You're looping through the input string twice, doing the same thing, which breaks a very important rule in programming - DRY (don't repeat yourself). My advice is to try to produce a respone by looping only once through s, which will require vowels to be presented in more efficient way (the problem does not state they have to be stored in an array).
This According to me is very trivial requirement. Although it violates DRY. Asymptotically it does not make difference at all. And if efficiency were an aspect, in some way one could argue that concurrency(which is generally required for large data) would be well implemented in two loops. without using DS like string to store data. (Also your solution may introduce an unecessary (worstcase)O(n) space complexity).
here is Loops problem solution in javascript https://solution.programmingoneonone.com/2020/06/hackerrank-day-2-loops-solution-javascript.html
For complete updated problem solution in javascript programming language https://programs.programmingoneonone.com/2021/02/hackerrank-day-2-loops-solution-javascript.html
The KISS beats DRY here:
Its still 2 for loop right?
Yes.
please folow me
This returns unique characters only. Check it in your console. It will return the following: a i o j v s c r p t l p s
Idk if the ES versions have changed, but it works now
can you kindly explain this for me. Thanks
[...s] can be decomposed in :
... : the spread operator (check the documentation)
s : the string s
[] : array symbol
the spread operator will take each iterable of the string s (each character) and put it in an array.
A forEach loop is used on that array, that will call a function for each of its items, in which the item is used as parameter.
It could be writen as such :
That function will check if the character is included in the provided string of vowels, and return the value or not using the ternary operator.
can be writen like that :
I hope this can help anybody.
Much better when someone explain. Thank you
I don't know why people downvoted your answer. It's quite stylish with these spread and ternary operators, and who cares if it loops through the string twice, this means nothing performance-wise, it's much better to have readable code.
Nice one
what about similar approach, but looping only once through string, but again through array?
function vowelsAndConsonants(s) {
let vowels = [], consonants = [];
[...s].forEach(current => 'aeiou'.includes(current) ? vowels.push(current):consonants.push(current));
for (let element of vowels) { console.log(element); } for (let element of consonants) { console.log(element); } }
For DRY believers:
This solution is much more better in terms of timecomplexity
Giving a dislike coz it seems difficult for beginners.
Not sure why this has been so downvoted. The use of two for loops is meaningless. Doesn't add much of a speed hit at all.
Would you like to explain your code
see mine, lol.
looping only once:
Brilliant answer loved it
Actually, the includes method loops through vowels. So you're looping through the parameter string "s" and vowels too.
brilliant...
Sorry for my language but this is the sexiest answer
Put some tan on, using turnary operator :)
best thanks!
Nice solution!
could you explain this for me
Sneaky sneaky :D
Correct me if I'm wrong but isnt the complexity of
.includes()
of O(n)? So technically its not looping once.Can be fixed with RegEx
/[aeiou]/.test(s[i])
Although I am fairly sure the complexity of
.includes()
depends on the array the method is called on, which in this case is small and constant (it's just the 5 vowels).Its not O(n) but O(5), which makes it trivial
Well, it's not O(n) in this case because we know how many letters there are.
works fine without trim()
It actually adds an extra line break at the end if you don't include trim().
how do you write it with code format?
click on this symbol while writting comment.
But still the complexity of the code remains same as o(n).
Is there any solution with o(1).
No, the amount of time has to be dependent on the input. The only way n(o) could happen is if you are doing a calculation not dependent on the length of the input( adition, lowest value, etc).
I did something similar in a one iteration, however I stored the consonents in an actual array whereas you used a string. Is my way less efficient. My reasoning is that behind the scenes I think that javascript is representing strings as an array. Therefore there should be no performance difference.
I did some research on JavaScript string concatenation vs array performance-wise. My conclusion is that it depends.
The reason is not what you suspected: virtually all programming languages represent strings as a character array, by definition.
The KISS beats DRY here:
Awesome
Brillant answer.
Why is there a need to store the remaining letters in a var first at the else condition then console.log the var later? Is there a way to console.log the remaining letters right away in the else condition?
No, because you have to print out the vowels first. Everything in your else block is a consonant so you have to print those after the fact.
I had a fairly similar solution.
Best , i guess ! :)
Ternary operation is best. kinda liked it
The quickest
The KISS beats DRY here:
i am having trouble understanding your code. Would you be king enough to explain me ? i am a new student.
The most pleasing answer...
Here if we have vowels as String, and call includes method, each time there is an extra work of converting String to array to check if the data is present. So This is happening for N times.
thanks
Your wonderful solution may be compressed into a one-liner like this:
The KISS beats DRY here:
I learned a lot from this one. Thank you.
it doesnt run
why do you use trim()? you could just print the consonants, because you already have break-line
why are you using trim. Even if you don't use it this wil work.
It's not necessary to consider them because input strings are guaranteed to be lowercase:
That was genius...
Can anybody explain this part of the code: else { consonants += s[i] + '\n'; }
It means that it should be printed on a new line
A new line character. So everytime it will display new letter in new line.
Assign each loop index that's not vowel to a new line
Similar but used array:
var arr = new Array(s.length); var j = 0; for (let i = 0; i < s.length; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u') { console.log(s[i]); } else { arr[j] = s[i]; j++; } } for (let i of arr) { if(i!=undefined) console.log(i); }
The KISS beats DRY here:
i solved mine quite similary
Not sure if concatinating to plain string is memory efficient of Javascript string works like StringBuilder in other languages.
This is so beautiful.
Could you please explain the else part?
brilliant
only if you could do var len = s.length; and the use the variable in the for loop will save time. The program will not have to calculate the length eacch time if you do something like this.
\n is not working in consonants += s[i] + '\n';
we could use
in the place of \n
instead of string use an array:
}very smart answer.
nice idea
why did you use trim() function? not necessary
y is trim used can anybody explain
Thanks for the help ,the readability of code is commendable (without the trim function also it passes the testcases) .
This is a time-space complexity tradeoff.
You do loop through only once, so you have O(n) time complexity rather than O(2n). That's still linear.
However, by creating this consonants string, you're creating a variable that increases linearly in size with the size of input (worst case). That's O(n) space complexity.
for(var i = 0; i < s.length-1; i++) .. //s.length-1 will be required so as to avoid an undefined value being printed
that is what I need :D
why it's necessary to use .trim method?
instead of adding all the consonants to a seperarte variable is it not possible to simply remove the vowels (every time the 'if' loop is entered) from the original string and then print the original string itself instead of 'consonants'?
I am new to JS !! why did we use console.log(consonants.trim()); here ???
tanning a bit more
let consonants = '' let vowels = 'aeiou'; [...s].forEach((letter) => { vowels.includes(letter) ? console.log(letter) : consonants += letter + '\n'; } ) console.log(consonants.trim());
Clever. Certainly very efficient. Perhaps a bit less readable than two loops however.
I'm a noob here. what is the consonants.trim do in this can anyone explain?
trim()
removes whitespace from both ends of a string, so in this case it removes trailing newline\n
from theconsonants
variable.More on String.prototype.trim() on MDN.
This is where trade of between memory and time complexity comes in Some people perefer looping twice(linear complexity) and some prefer making use of extra variables.
Nicely Written code though.
NIce approach, but not sure if it would work without the if statements curly braces.
Curly braces are optional for single statements (MDN if syntax), so a line of code below will speak for itself.
Nevertheless, it is considered to be a good practice to turn single statements into block statements by using curly braces around them.
Thanks for your response, i never used it that way, but i use arrow functions that way if its returning a single statement. Thanks for the heads up. Yeah it sure is a good practice to include the curly braces.
Try to avoid the "includes" method. You will find yourself running into road blocks when creating apps for internet explorer. I would recommend indexOf() which is recognized by IE and all modern browsers.
it was Arsom
Thanks Man for this answer i was so confused but once i see this answer i remove all my worries
function vowelsAndConsonants(s) { for(var i=0;i } } for(var i=0;i
}}
kalinga_abishek yes eat
if you want download app download app