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;
$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?
javascript performance algorithm compression
$endgroup$
add a comment |
$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?
javascript performance algorithm compression
$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
add a comment |
$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?
javascript performance algorithm compression
$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
javascript performance algorithm compression
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
add a comment |
$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
add a comment |
1 Answer
1
active
oldest
votes
$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 thanfor in
$endgroup$
$begingroup$
Wow. thank you.
$endgroup$
– iamwhitebox
2 hours ago
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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 thanfor in
$endgroup$
$begingroup$
Wow. thank you.
$endgroup$
– iamwhitebox
2 hours ago
add a comment |
$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 thanfor in
$endgroup$
$begingroup$
Wow. thank you.
$endgroup$
– iamwhitebox
2 hours ago
add a comment |
$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 thanfor in
$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 thanfor in
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
add a comment |
$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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
$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