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:
- LinkedIn: www.linkedin.com/in/reach-jaffer
- YouTube: @codewithjaffer
Comments
Post a Comment