Print a string of characters with their occurrencesSimplified regular expression engineTesting distance between characters in a stringAlgorithm that tells the user what current “status” they fall under based on their current time in comparison to an array of meeting data timesSocial network broadcast message algorithmPartition Equal Subset Sum Challenge LeetCodeSecond degree connection rankingK Messed Array sort in JavaHackerrank ransomnoteSimple function returning 1 if the Mean = Mode, or 0 if notInverse mapping with bilinear interpolation on an image

Two researchers want to work on the same extension to my paper. Who to help?

How to select certain lines (n, n+4, n+8, n+12...) from the file?

Can more than one creature benefit from multiple Hunter's Mark spells cast on the same target?

Why are low spin tetrahedral complexes so rare?

Create less file for custom Theme

Can the president of the United States be guilty of insider trading?

How to slow yourself down (for playing nice with others)

How do I compare the result of "1d20+x, with advantage" to "1d20+y, without advantage", assuming x < y?

Is it a good idea to copy a trader when investing?

Is this state of Earth possible, after humans left for a million years?

How to efficiently lower your karma

Is every story set in the future "science fiction"?

How are one-time password generators like Google Authenticator different from having two passwords?

Improving Sati-Sampajañña (situative wisdom)

Windows OS quantum vs. SQL OS Quantum

Extending Kan fibrations, without using minimal fibrations

How is CoreiX like Corei5, i7 is related to Haswell, Ivy Bridge?

What was the notion of limit that Newton used?

What food production methods would allow a metropolis like New York to become self sufficient

Passport stamps art, can it be done?

Can 'sudo apt-get remove [write]' destroy my Ubuntu?

How to get my matrix to fit on the page

What does formal training in a field mean?

Is it a Munchausen Number?



Print a string of characters with their occurrences


Simplified regular expression engineTesting distance between characters in a stringAlgorithm that tells the user what current “status” they fall under based on their current time in comparison to an array of meeting data timesSocial network broadcast message algorithmPartition Equal Subset Sum Challenge LeetCodeSecond degree connection rankingK Messed Array sort in JavaHackerrank ransomnoteSimple function returning 1 if the Mean = Mode, or 0 if notInverse mapping with bilinear interpolation on an image






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I have worked out a solution for this problem, however I am trying to reach an O(1) solution without the use of two for loops. The output should read as a3b2c4d1 for the solution below.



i.e. I want to be able to describe which is a "greedy" approach and the tradeoffs of each.



Here is my current solution:






let countLetters = (str) => 
let arr = str.split(''),
map = ,
ret = '';

for (var i = 0; i < arr.length; i++)
map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length


for (let i in map)
ret += `$i + map[i]`


return ret;


console.log(countLetters('aaabbccccd'));





Can someone explain to me what is the time complexity of the current solution, and possible how to think in better terms of reaching a better time complexity?










share|improve this question











$endgroup$











  • $begingroup$
    Strings are basically unordered list so... you can't really get O(1) since there is no way to tell the remaining without checking them. And you need the second for loop because you don't know what count you'll have until the end of the first loop.
    $endgroup$
    – Neil
    3 hours ago


















2












$begingroup$


I have worked out a solution for this problem, however I am trying to reach an O(1) solution without the use of two for loops. The output should read as a3b2c4d1 for the solution below.



i.e. I want to be able to describe which is a "greedy" approach and the tradeoffs of each.



Here is my current solution:






let countLetters = (str) => 
let arr = str.split(''),
map = ,
ret = '';

for (var i = 0; i < arr.length; i++)
map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length


for (let i in map)
ret += `$i + map[i]`


return ret;


console.log(countLetters('aaabbccccd'));





Can someone explain to me what is the time complexity of the current solution, and possible how to think in better terms of reaching a better time complexity?










share|improve this question











$endgroup$











  • $begingroup$
    Strings are basically unordered list so... you can't really get O(1) since there is no way to tell the remaining without checking them. And you need the second for loop because you don't know what count you'll have until the end of the first loop.
    $endgroup$
    – Neil
    3 hours ago














2












2








2





$begingroup$


I have worked out a solution for this problem, however I am trying to reach an O(1) solution without the use of two for loops. The output should read as a3b2c4d1 for the solution below.



i.e. I want to be able to describe which is a "greedy" approach and the tradeoffs of each.



Here is my current solution:






let countLetters = (str) => 
let arr = str.split(''),
map = ,
ret = '';

for (var i = 0; i < arr.length; i++)
map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length


for (let i in map)
ret += `$i + map[i]`


return ret;


console.log(countLetters('aaabbccccd'));





Can someone explain to me what is the time complexity of the current solution, and possible how to think in better terms of reaching a better time complexity?










share|improve this question











$endgroup$




I have worked out a solution for this problem, however I am trying to reach an O(1) solution without the use of two for loops. The output should read as a3b2c4d1 for the solution below.



i.e. I want to be able to describe which is a "greedy" approach and the tradeoffs of each.



Here is my current solution:






let countLetters = (str) => 
let arr = str.split(''),
map = ,
ret = '';

for (var i = 0; i < arr.length; i++)
map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length


for (let i in map)
ret += `$i + map[i]`


return ret;


console.log(countLetters('aaabbccccd'));





Can someone explain to me what is the time complexity of the current solution, and possible how to think in better terms of reaching a better time complexity?






let countLetters = (str) => 
let arr = str.split(''),
map = ,
ret = '';

for (var i = 0; i < arr.length; i++)
map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length


for (let i in map)
ret += `$i + map[i]`


return ret;


console.log(countLetters('aaabbccccd'));





let countLetters = (str) => 
let arr = str.split(''),
map = ,
ret = '';

for (var i = 0; i < arr.length; i++)
map[arr[i]] = str.match(new RegExp(arr[i], 'g')).length


for (let i in map)
ret += `$i + map[i]`


return ret;


console.log(countLetters('aaabbccccd'));






javascript performance algorithm compression






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 3 hours ago









200_success

132k20159426




132k20159426










asked 4 hours ago









iamwhiteboxiamwhitebox

1535




1535











  • $begingroup$
    Strings are basically unordered list so... you can't really get O(1) since there is no way to tell the remaining without checking them. And you need the second for loop because you don't know what count you'll have until the end of the first loop.
    $endgroup$
    – Neil
    3 hours ago

















  • $begingroup$
    Strings are basically unordered list so... you can't really get O(1) since there is no way to tell the remaining without checking them. And you need the second for loop because you don't know what count you'll have until the end of the first loop.
    $endgroup$
    – Neil
    3 hours ago
















$begingroup$
Strings are basically unordered list so... you can't really get O(1) since there is no way to tell the remaining without checking them. And you need the second for loop because you don't know what count you'll have until the end of the first loop.
$endgroup$
– Neil
3 hours ago





$begingroup$
Strings are basically unordered list so... you can't really get O(1) since there is no way to tell the remaining without checking them. And you need the second for loop because you don't know what count you'll have until the end of the first loop.
$endgroup$
– Neil
3 hours ago











1 Answer
1






active

oldest

votes


















3












$begingroup$

Big $O$



Time complexity is a ratio of some input metric (e.g. the number of character in the string) to the number of instructions required to complete the function.



In this case the metric $n$ is the string length. The first loop that uses String.match must for each character check all characters to find a count. That means at least $n * n$ steps need to be performed to do the operation.



Thus the complexity of the function is said to be $O(n^2)$



If you think about how you would solve it on paper. You would go over each character once with a list of characters found adding 1 to each count as you find them. This would have a time complexity of $O(n)$



Maps use a hash function to locate an item $O(1)$. So the time complexity to find out if you have counted a character before is $O(1)$, rather than your regExp $O(n)$



function countLetters(str) 
const charCounts = ;
var result = "";
for (const c of str)
if (charCounts[c]) charCounts[c] += 1
else charCounts[c] = 1

for (const [char, count] of Object.entries(charCounts))
result += char + " has " + count + " ";

return result;



The second loop to create the result, will count in the worst case each character again. Thus the number of instructions is $2n$ In big $O$ notation the scale $2$ is insignificant compared to powers, even if it was $1000000n$ we ignore the scale and make it just $n$



It can not be done with less complexity as you need to check every character at least once. Because you do not know what the characters are before you check them.



Style Notes.



  • Use ; or not, never use them sometimes.

  • Careful with indentation. You indent 4 and sometime 2 spaces, use either not both.

  • Use Function declarations in favor of arrow functions when in global scope.

  • Variables that do not change should be declared as constants const

  • Use for of rather than for in





share|improve this answer











$endgroup$












  • $begingroup$
    Wow. thank you.
    $endgroup$
    – iamwhitebox
    2 hours ago











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220026%2fprint-a-string-of-characters-with-their-occurrences%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3












$begingroup$

Big $O$



Time complexity is a ratio of some input metric (e.g. the number of character in the string) to the number of instructions required to complete the function.



In this case the metric $n$ is the string length. The first loop that uses String.match must for each character check all characters to find a count. That means at least $n * n$ steps need to be performed to do the operation.



Thus the complexity of the function is said to be $O(n^2)$



If you think about how you would solve it on paper. You would go over each character once with a list of characters found adding 1 to each count as you find them. This would have a time complexity of $O(n)$



Maps use a hash function to locate an item $O(1)$. So the time complexity to find out if you have counted a character before is $O(1)$, rather than your regExp $O(n)$



function countLetters(str) 
const charCounts = ;
var result = "";
for (const c of str)
if (charCounts[c]) charCounts[c] += 1
else charCounts[c] = 1

for (const [char, count] of Object.entries(charCounts))
result += char + " has " + count + " ";

return result;



The second loop to create the result, will count in the worst case each character again. Thus the number of instructions is $2n$ In big $O$ notation the scale $2$ is insignificant compared to powers, even if it was $1000000n$ we ignore the scale and make it just $n$



It can not be done with less complexity as you need to check every character at least once. Because you do not know what the characters are before you check them.



Style Notes.



  • Use ; or not, never use them sometimes.

  • Careful with indentation. You indent 4 and sometime 2 spaces, use either not both.

  • Use Function declarations in favor of arrow functions when in global scope.

  • Variables that do not change should be declared as constants const

  • Use for of rather than for in





share|improve this answer











$endgroup$












  • $begingroup$
    Wow. thank you.
    $endgroup$
    – iamwhitebox
    2 hours ago















3












$begingroup$

Big $O$



Time complexity is a ratio of some input metric (e.g. the number of character in the string) to the number of instructions required to complete the function.



In this case the metric $n$ is the string length. The first loop that uses String.match must for each character check all characters to find a count. That means at least $n * n$ steps need to be performed to do the operation.



Thus the complexity of the function is said to be $O(n^2)$



If you think about how you would solve it on paper. You would go over each character once with a list of characters found adding 1 to each count as you find them. This would have a time complexity of $O(n)$



Maps use a hash function to locate an item $O(1)$. So the time complexity to find out if you have counted a character before is $O(1)$, rather than your regExp $O(n)$



function countLetters(str) 
const charCounts = ;
var result = "";
for (const c of str)
if (charCounts[c]) charCounts[c] += 1
else charCounts[c] = 1

for (const [char, count] of Object.entries(charCounts))
result += char + " has " + count + " ";

return result;



The second loop to create the result, will count in the worst case each character again. Thus the number of instructions is $2n$ In big $O$ notation the scale $2$ is insignificant compared to powers, even if it was $1000000n$ we ignore the scale and make it just $n$



It can not be done with less complexity as you need to check every character at least once. Because you do not know what the characters are before you check them.



Style Notes.



  • Use ; or not, never use them sometimes.

  • Careful with indentation. You indent 4 and sometime 2 spaces, use either not both.

  • Use Function declarations in favor of arrow functions when in global scope.

  • Variables that do not change should be declared as constants const

  • Use for of rather than for in





share|improve this answer











$endgroup$












  • $begingroup$
    Wow. thank you.
    $endgroup$
    – iamwhitebox
    2 hours ago













3












3








3





$begingroup$

Big $O$



Time complexity is a ratio of some input metric (e.g. the number of character in the string) to the number of instructions required to complete the function.



In this case the metric $n$ is the string length. The first loop that uses String.match must for each character check all characters to find a count. That means at least $n * n$ steps need to be performed to do the operation.



Thus the complexity of the function is said to be $O(n^2)$



If you think about how you would solve it on paper. You would go over each character once with a list of characters found adding 1 to each count as you find them. This would have a time complexity of $O(n)$



Maps use a hash function to locate an item $O(1)$. So the time complexity to find out if you have counted a character before is $O(1)$, rather than your regExp $O(n)$



function countLetters(str) 
const charCounts = ;
var result = "";
for (const c of str)
if (charCounts[c]) charCounts[c] += 1
else charCounts[c] = 1

for (const [char, count] of Object.entries(charCounts))
result += char + " has " + count + " ";

return result;



The second loop to create the result, will count in the worst case each character again. Thus the number of instructions is $2n$ In big $O$ notation the scale $2$ is insignificant compared to powers, even if it was $1000000n$ we ignore the scale and make it just $n$



It can not be done with less complexity as you need to check every character at least once. Because you do not know what the characters are before you check them.



Style Notes.



  • Use ; or not, never use them sometimes.

  • Careful with indentation. You indent 4 and sometime 2 spaces, use either not both.

  • Use Function declarations in favor of arrow functions when in global scope.

  • Variables that do not change should be declared as constants const

  • Use for of rather than for in





share|improve this answer











$endgroup$



Big $O$



Time complexity is a ratio of some input metric (e.g. the number of character in the string) to the number of instructions required to complete the function.



In this case the metric $n$ is the string length. The first loop that uses String.match must for each character check all characters to find a count. That means at least $n * n$ steps need to be performed to do the operation.



Thus the complexity of the function is said to be $O(n^2)$



If you think about how you would solve it on paper. You would go over each character once with a list of characters found adding 1 to each count as you find them. This would have a time complexity of $O(n)$



Maps use a hash function to locate an item $O(1)$. So the time complexity to find out if you have counted a character before is $O(1)$, rather than your regExp $O(n)$



function countLetters(str) 
const charCounts = ;
var result = "";
for (const c of str)
if (charCounts[c]) charCounts[c] += 1
else charCounts[c] = 1

for (const [char, count] of Object.entries(charCounts))
result += char + " has " + count + " ";

return result;



The second loop to create the result, will count in the worst case each character again. Thus the number of instructions is $2n$ In big $O$ notation the scale $2$ is insignificant compared to powers, even if it was $1000000n$ we ignore the scale and make it just $n$



It can not be done with less complexity as you need to check every character at least once. Because you do not know what the characters are before you check them.



Style Notes.



  • Use ; or not, never use them sometimes.

  • Careful with indentation. You indent 4 and sometime 2 spaces, use either not both.

  • Use Function declarations in favor of arrow functions when in global scope.

  • Variables that do not change should be declared as constants const

  • Use for of rather than for in






share|improve this answer














share|improve this answer



share|improve this answer








edited 32 mins ago









yuri

3,85221135




3,85221135










answered 3 hours ago









Blindman67Blindman67

10.6k1623




10.6k1623











  • $begingroup$
    Wow. thank you.
    $endgroup$
    – iamwhitebox
    2 hours ago
















  • $begingroup$
    Wow. thank you.
    $endgroup$
    – iamwhitebox
    2 hours ago















$begingroup$
Wow. thank you.
$endgroup$
– iamwhitebox
2 hours ago




$begingroup$
Wow. thank you.
$endgroup$
– iamwhitebox
2 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220026%2fprint-a-string-of-characters-with-their-occurrences%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Log på Navigationsmenu

Creating second map without labels using QGIS?How to lock map labels for inset map in Print Composer?How to Force the Showing of Labels of a Vector File in QGISQGIS Valmiera, Labels only show for part of polygonsRemoving duplicate point labels in QGISLabeling every feature using QGIS?Show labels for point features outside map canvasAbbreviate Road Labels in QGIS only when requiredExporting map from composer in QGIS - text labels have moved in output?How to make sure labels in qgis turn up in layout map?Writing label expression with ArcMap and If then Statement?

Nuuk Indholdsfortegnelse Etyomologi | Historie | Geografi | Transport og infrastruktur | Politik og administration | Uddannelsesinstitutioner | Kultur | Venskabsbyer | Noter | Eksterne henvisninger | Se også | Navigationsmenuwww.sermersooq.gl64°10′N 51°45′V / 64.167°N 51.750°V / 64.167; -51.75064°10′N 51°45′V / 64.167°N 51.750°V / 64.167; -51.750DMI - KlimanormalerSalmonsen, s. 850Grønlands Naturinstitut undersøger rensdyr i Akia og Maniitsoq foråret 2008Grønlands NaturinstitutNy vej til Qinngorput indviet i dagAntallet af biler i Nuuk må begrænsesNy taxacentral mødt med demonstrationKøreplan. Rute 1, 2 og 3SnescootersporNuukNord er for storSkoler i Kommuneqarfik SermersooqAtuarfik Samuel KleinschmidtKangillinguit AtuarfiatNuussuup AtuarfiaNuuk Internationale FriskoleIlinniarfissuaq, Grønlands SeminariumLedelseÅrsberetning for 2008Kunst og arkitekturÅrsberetning for 2008Julie om naturenNuuk KunstmuseumSilamiutGrønlands Nationalmuseum og ArkivStatistisk ÅrbogGrønlands LandsbibliotekStore koncerter på stribeVandhund nummer 1.000.000Kommuneqarfik Sermersooq – MalikForsidenVenskabsbyerLyngby-Taarbæk i GrønlandArctic Business NetworkWinter Cities 2008 i NuukDagligt opdaterede satellitbilleder fra NuukområdetKommuneqarfik Sermersooqs hjemmesideTurist i NuukGrønlands Statistiks databankGrønlands Hjemmestyres valgresultaterrrWorldCat124325457671310-5