An algorithm to check if there are duplicate letters in the string.
We will check if the given string has duplicate letters and if found we will return true
, false
otherwise.
Example
Input: 'learnersbucket' 'abcdefghijk' 'I Love learnersbucket' Output: true false true
Implementation
- We will create a Set and add letters of the string to it.
- While storing the letter we will check if Set has duplicate letters. If it is present then return
true
else returnfalse
. - We will check for both case-sensitive and incase-sensitive letters.
- Everything will be written in ES6.
For incase-sensitive letters
let containsDuplicates = (str) => { let set = new Set(); //convert str to lowercase //Remove this if you want to check for incase-sensitive strings str = str.toLowerCase(); //If it is not whitespace the check if aplhabet is present or not for(let i = 0; i < str.length; i++){ if(str[i] != ' '){ if(set.has(str[i])){ return true; } set.add(str[i]); } } return false; }
Input: console.log(containsDuplicates("learnersbucket")); console.log(containsDuplicates("abcdefghijk")); console.log(containsDuplicates("I Love learnersbucket")); Output: true false true
For case-sensitive letters
let containsDuplicates = (str) => { let set = new Set(); //If it is not whitespace the check if aplhabet is present or not for(let i = 0; i < str.length; i++){ if(str[i] != ' '){ if(set.has(str[i])){ return true; } set.add(str[i]); } } return false; }
Input: console.log(containsDuplicates("learnersbucket")); console.log(containsDuplicates("abcdefghijk")); console.log(containsDuplicates("I Luv life")); Output: true false false
Time Complexity: O(n).
Space Complexity: O(n).
Time and Space complexity
- We are traversing whole string and will be checking each character of it, so Time complexity is O(n).
- We will be storing each character of given string, so Space complexity is O(n).