JSFiddle - React, Tailwind, and code Playground

by Shridhar Baddur

JavaScript

/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
  let map = new Map();
  let n = s.length;

  // count the appearance of each character in the string    
  for (let i = 0; i < n; i++) {
    const count = map.get(s[i]) || 0;
    map.set(s[i], count + 1);
  }

  // find first letter with count == 1
  for (let i = 0; i < n; i++) {
    if (map.get(s[i]) === 1) return i;
  }
  return -1;
};
let s = "loveleetcode";
// let s = "leetcode";
console.log(firstUniqChar(s));