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

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

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

Why was wildfire not used during the Battle of Winterfell?

Why does increasing the sampling rate make implementing an anti-aliasing filter easier?

What does formal training in a field mean?

Why do Thanos' punches not kill Captain America or at least cause some mortal injuries?

Best species to breed to intelligence

Was there a contingency plan in place if Little Boy failed to detonate?

Print a string of characters with their occurrences

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

What do "KAL." and "A.S." stand for in this inscription?

Cryptography and elliptic curves

Early arrival in Australia, early check in not available

How to see that 1 is a solution?

Is it bad writing or bad story telling if first person narrative contains more information than the narrator knows?

Passport stamps art, can it be done?

Windows OS quantum vs. SQL OS Quantum

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

Why do the Avengers care about returning these items in Endgame?

How did Thanos not realise this had happened at the end of Endgame?

Thesis' "Future Work" section – is it acceptable to omit personal involvement in a mentioned project?

Is it nonsense to say B -> [A -> B]?

Cropping a message using array splits

How to get my matrix to fit on the page



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
    2 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
    2 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
    2 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
    2 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
2 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
2 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 13 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

Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單