💻 JavaScript Interview Question Write a function that takes a string input, and returns the first character that is not repeated anywhere in the string. For example, if given the input "stress", the function should return 't', since the letter t only occurs once in the string, and occurs first in the string. If a string contains only repeating characters, return an empty string (""); function firstNonRepeatingLetter(s) { let mySet = new Set(); //stress for(let c of s) { if(mySet.has(c.toLowerCase())) { mySet.delete(c.toLowerCase()); } else if(mySet.has(c.toUpperCase())) { mySet.delete(c.toUpperCase()); } else { mySet.add(c); } } const setAsArray = Array.from(mySet); if(setAsArray.length == 0) return (""); return (setAsArray[0]); } #javaScript #CodingInterview #WebDevelopment #Frontend #React
Hi Nilesh Sinha, Small observation here. Although the solution claims O(1) space, the time complexity becomes O(n²) because indexOf() and lastIndexOf() each scan the string in O(n) and are executed inside a loop running n times. So effectively: O(n) × O(n) = O(n²). For better scalability, a frequency map approach keeps the complexity O(n): function firstNonRepeatingLetter(s) { const freq = {}; for (const c of s) { const k = c.toLowerCase(); freq[k] = (freq[k] || 0) + 1; } for (const c of s) { if (freq[c.toLowerCase()] === 1) return c; } return ""; } This avoids repeated scans and keeps the algorithm linear.
O(1) Space complexity solution- function firstNonRepeatingLetter(s) { let str = s.toLowerCase(); for(let i = 0; i < str.length; i++) { if(str.indexOf(str[i]) === str.lastIndexOf(str[i])) { return s[i]; } } return ""; }