From 0cf4881c1b6905c0585b78dc47c9faf4ff271708 Mon Sep 17 00:00:00 2001 From: AnishMandal939 Date: Mon, 25 Oct 2021 15:06:43 +0545 Subject: [PATCH] added more solution approach with well comments to understand --- chapter01/1.1 - Is Unique/isUnique.js | 47 +++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/chapter01/1.1 - Is Unique/isUnique.js b/chapter01/1.1 - Is Unique/isUnique.js index 3321571..e9775a4 100644 --- a/chapter01/1.1 - Is Unique/isUnique.js +++ b/chapter01/1.1 - Is Unique/isUnique.js @@ -23,7 +23,7 @@ const everyCharUnique = (str, indexOffset = 'a'.charCodeAt()) => { return true; }; -function everyCharUnique(str) { +function everyCharUniques(str) { let obj = {}; for (let i = 0; i < str.length; i++) { if (obj[str[i]] && obj[str[i]] >= 1) { @@ -35,8 +35,51 @@ function everyCharUnique(str) { return true; } +// So we have two methods to one by creating extra space annd without creating extra space +// with extra spaces + let uniqueChars = (str) =>{ + // creating a empty variable to map + let characters = {}; + // iterate through all characters of the string and start inserting them one by one characters tabole + for(var i = 0; i < str.length; i++){ + // check if string already present in characters variable + if(characters[str[i]] != null) { + // if present repetation of character than return false + characters[str[i]] = 1; + return false; + }else{ + // !present duplicate characters than return true + characters[str[i]] = 0; + + } + + } + return true; + } +// Since we are iterating trough each element of string only once string of length 1 average and worst case time complexity is O(n) +// without extra spaces + + let uniqueChar = (str) => { + // iterate through string + for(let i =0; i< str.length; i++){ + // checking against the subsequent characters & iterating through them + for(let j = i+1; j <=str.length-1; j++){ + if(str[i] == str[j]){ + return false; + } + } + } + return true; + } + /* TESTS */ console.log(everyCharUnique('abcd'), 'true'); console.log(everyCharUnique('abccd'), 'false'); console.log(everyCharUnique('bhjjb'), 'false'); -console.log(everyCharUnique('mdjq'), 'true'); +console.log(everyCharUniques('mdjq'), 'true'); +console.log(uniqueChars('hello'), 'false'); +console.log(uniqueChars('anish'), 'true'); +console.log(uniqueChar('hello'), 'false'); +console.log(uniqueChar('anish'), 'true'); + +