Check for characters in a string being unique Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How to check empty/undefined/null string in JavaScript?How do I check if an element is hidden in jQuery?How do I check if an array includes an object in JavaScript?Setting “checked” for a checkbox with jQuery?How to check if a string “StartsWith” another string?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Check if a variable is a string in JavaScriptHow to check if an object is an array?Is it possible to apply CSS to half of a character?

Why do early math courses focus on the cross sections of a cone and not on other 3D objects?

Random body shuffle every night—can we still function?

If Windows 7 doesn't support WSL, then what is "Subsystem for UNIX-based Applications"?

Is it dangerous to install hacking tools on my private linux machine?

Tannaka duality for semisimple groups

Printing attributes of selection in ArcPy?

Special flights

Should a wizard buy fine inks every time he want to copy spells into his spellbook?

What does Turing mean by this statement?

A proverb that is used to imply that you have unexpectedly faced a big problem

What is the chair depicted in Cesare Maccari's 1889 painting "Cicerone denuncia Catilina"?

How would a mousetrap for use in space work?

What is the difference between CTSS and ITS?

Project Euler #1 in C++

How to write capital alpha?

Did Mueller's report provide an evidentiary basis for the claim of Russian govt election interference via social media?

What initially awakened the Balrog?

Getting out of while loop on console

Why is std::move not [[nodiscard]] in C++20?

Co-worker has annoying ringtone

Trying to understand entropy as a novice in thermodynamics

"klopfte jemand" or "jemand klopfte"?

Why does electrolysis of aqueous concentrated sodium bromide produce bromine at the anode?

Can an iPhone 7 be made to function as a NFC Tag?



Check for characters in a string being unique



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How to check empty/undefined/null string in JavaScript?How do I check if an element is hidden in jQuery?How do I check if an array includes an object in JavaScript?Setting “checked” for a checkbox with jQuery?How to check if a string “StartsWith” another string?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Check if a variable is a string in JavaScriptHow to check if an object is an array?Is it possible to apply CSS to half of a character?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








8















I implemented my algorithm for checking if the string passed in is unique. I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. Why?






function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true












share|improve this question
























  • FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

    – Frax
    Apr 3 at 5:55

















8















I implemented my algorithm for checking if the string passed in is unique. I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. Why?






function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true












share|improve this question
























  • FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

    – Frax
    Apr 3 at 5:55













8












8








8


1






I implemented my algorithm for checking if the string passed in is unique. I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. Why?






function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true












share|improve this question
















I implemented my algorithm for checking if the string passed in is unique. I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. Why?






function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true








function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true





function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true






javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 3 at 11:13









Peter Mortensen

14k1987114




14k1987114










asked Apr 3 at 5:35









user3763875user3763875

745




745












  • FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

    – Frax
    Apr 3 at 5:55

















  • FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

    – Frax
    Apr 3 at 5:55
















FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

– Frax
Apr 3 at 5:55





FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

– Frax
Apr 3 at 5:55












2 Answers
2






active

oldest

votes


















25














return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








share|improve this answer




















  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    Apr 3 at 5:42







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    Apr 3 at 5:50


















0














Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








share|improve this answer

























  • Why is r a parameter?

    – JollyJoker
    Apr 3 at 8:01











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    Apr 3 at 8:07












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: "1"
;
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: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
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%2fstackoverflow.com%2fquestions%2f55487722%2fcheck-for-characters-in-a-string-being-unique%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









25














return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








share|improve this answer




















  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    Apr 3 at 5:42







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    Apr 3 at 5:50















25














return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








share|improve this answer




















  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    Apr 3 at 5:42







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    Apr 3 at 5:50













25












25








25







return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








share|improve this answer















return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));





function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 3 at 6:03









Patrick Roberts

21.3k33777




21.3k33777










answered Apr 3 at 5:37









CertainPerformanceCertainPerformance

101k166292




101k166292







  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    Apr 3 at 5:42







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    Apr 3 at 5:50












  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    Apr 3 at 5:42







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    Apr 3 at 5:50







1




1





Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

– Patrick Roberts
Apr 3 at 5:42






Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

– Patrick Roberts
Apr 3 at 5:42





5




5





The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

– Patrick Roberts
Apr 3 at 5:50





The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

– Patrick Roberts
Apr 3 at 5:50













0














Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








share|improve this answer

























  • Why is r a parameter?

    – JollyJoker
    Apr 3 at 8:01











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    Apr 3 at 8:07
















0














Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








share|improve this answer

























  • Why is r a parameter?

    – JollyJoker
    Apr 3 at 8:01











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    Apr 3 at 8:07














0












0








0







Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








share|improve this answer















Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));





function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 3 at 8:07

























answered Apr 3 at 5:52









Kamil KiełczewskiKamil Kiełczewski

14.5k87497




14.5k87497












  • Why is r a parameter?

    – JollyJoker
    Apr 3 at 8:01











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    Apr 3 at 8:07


















  • Why is r a parameter?

    – JollyJoker
    Apr 3 at 8:01











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    Apr 3 at 8:07

















Why is r a parameter?

– JollyJoker
Apr 3 at 8:01





Why is r a parameter?

– JollyJoker
Apr 3 at 8:01













r (I rename it to t) is temporary hash map (define in tricky way as default param)

– Kamil Kiełczewski
Apr 3 at 8:07






r (I rename it to t) is temporary hash map (define in tricky way as default param)

– Kamil Kiełczewski
Apr 3 at 8:07


















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • 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.

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%2fstackoverflow.com%2fquestions%2f55487722%2fcheck-for-characters-in-a-string-being-unique%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

Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

Tähtien Talli Jäsenet | Lähteet | NavigointivalikkoSuomen Hippos – Tähtien Talli

Do these cracks on my tires look bad? The Next CEO of Stack OverflowDry rot tire should I replace?Having to replace tiresFishtailed so easily? Bad tires? ABS?Filling the tires with something other than air, to avoid puncture hassles?Used Michelin tires safe to install?Do these tyre cracks necessitate replacement?Rumbling noise: tires or mechanicalIs it possible to fix noisy feathered tires?Are bad winter tires still better than summer tires in winter?Torque converter failure - Related to replacing only 2 tires?Why use snow tires on all 4 wheels on 2-wheel-drive cars?