Day 14: First Non-Repeating Character – JavaScript DSA

๐Ÿš€ Day 14 – First Non-Repeating Character in JavaScript

This string problem is frequently asked in product companies like Amazon and PayPal.

๐Ÿงช Problem:

Given a string, return the index of the first non-repeating character. If no such character exists, return -1.

๐Ÿ“Œ Examples:


Input: "leetcode"      ➡️ Output: 0  

Input: "loveleetcode"  ➡️ Output: 2  

Input: "aabbcc"         ➡️ Output: -1

✅ JavaScript Code:



function firstUniqueChar(str) {

  const freq = {};

  for (let char of str) {

    freq[char] = (freq[char] || 0) + 1;

  }

  for (let i = 0; i < str.length; i++) {

    if (freq[str[i]] === 1) return i;

  }

  return -1;

}

✨ Alternate Solution (indexOf + lastIndexOf)



function firstUniqCharBuiltIn(s) {

  for (let i = 0; i < s.length; i++) {

    if (s.indexOf(s[i]) === s.lastIndexOf(s[i])) return i;

  }

  return -1;

}

๐ŸŽฏ Tips:

  • Use a hash map to store character frequency
  • indexOf + lastIndexOf is slower but useful for short strings

๐Ÿ”— Follow for more:

Comments

Popular posts from this blog

Day 4 – Palindrome Number in JavaScript Without Converting to String

Day 9 – Count Vowels in a String using JavaScript | DSA Challenge with Code & Explanation

Day 13: Find Missing Number in an Array – JavaScript DSA Challenge