|
| 1 | +function firstNonRepeatingCharWithMap(inputStr) { |
| 2 | + if(inputStr.length === 0) return null; |
| 3 | + let charCountsMap = new Map(); |
| 4 | + for(let ch of inputStr) { |
| 5 | + charCountsMap.set(ch, (charCountsMap.get(ch) || 0) + 1); |
| 6 | + } |
| 7 | + |
| 8 | + for(let [key, value] of charCountsMap.entries()) { |
| 9 | + if(value === 1) { |
| 10 | + return key; |
| 11 | + } |
| 12 | + } |
| 13 | + return null; |
| 14 | +} |
| 15 | + |
| 16 | +function firstNonRepeatingCharWithObj(inputStr) { |
| 17 | + if(inputStr.length === 0) return null; |
| 18 | + let charCountsObj = {}; |
| 19 | + for(let ch of inputStr) { |
| 20 | + charCountsObj[ch] = (charCountsObj[ch] || 0) + 1; |
| 21 | + } |
| 22 | + |
| 23 | + for(let [key, value] of Object.entries(charCountsObj)) { |
| 24 | + if(value === 1) { |
| 25 | + return key; |
| 26 | + } |
| 27 | + } |
| 28 | + return null; |
| 29 | +} |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +/**--------------- |
| 34 | + All Unique |
| 35 | + --------------- */ |
| 36 | +console.log("Input: 'abcdefgh'"); |
| 37 | +console.log("Output: ", firstNonRepeatingCharWithObj('abcdefgh')); |
| 38 | +console.log("---------------"); |
| 39 | + |
| 40 | +/**--------------- |
| 41 | + Some Duplicates |
| 42 | + --------------- */ |
| 43 | +console.log("Input: 'abccddefgggh'"); |
| 44 | +console.log("Output: ", firstNonRepeatingCharWithObj('abccddefgggh')); |
| 45 | +console.log("---------------"); |
| 46 | + |
| 47 | +/** --------------- |
| 48 | + All Duplicates |
| 49 | + --------------- */ |
| 50 | +console.log("Input: 'aabbccdddeeeff'"); |
| 51 | +console.log("Output: ", firstNonRepeatingCharWithMap('aabbccdddeeeff')); |
| 52 | +console.log("---------------"); |
| 53 | + |
| 54 | +/** --------------- |
| 55 | + Empty String |
| 56 | + --------------- */ |
| 57 | +console.log("Input: ''"); |
| 58 | +console.log("Output: ", firstNonRepeatingMap('')); |
| 59 | +console.log("---------------"); |
0 commit comments