// SOLUTION 1 - MY (DISCOVERED) SOLUTION (RUNTIME - 84MS, MEMORY - 41.2MB) var firstUniqChar = function(s) { // loop through the characters of the string for (var i = 0; i < s.length; i++) { // set a variable for the char var c = s.charAt(i); // if the index of the char == i, and the index of 'c', starting search from index 'i + 1' == -1 if (s.indexOf(c) == i && s.indexOf(c, i + 1) == -1) { return s.indexOf(c); } } return -1; }; // SOLUTION 2 (BEST RUNTIME - 68MS) var firstUniqChar = function(s) { count = [] for(let i=0;i<s.length;i++){ index = s.charCodeAt(i)-'a'.charCodeAt(0) if(count[index]==undefined){ count[index]=1 }else{ count[index]++ } } for(let i=0;i<s.length;i++){ index = s.charCodeAt(i)-'a'.charCodeAt(0) if(count[index]==1){ return i } } return -1 }; // SOLUTION 3 - (RUNTIME - 96MS) var firstUniqChar = function(s) { for (i=0; i < s.length; i++) { if (s.indexOf(s[i]) == s.lastIndexOf(s[i])) { return i } } return -1 }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter