Day 12: First Non-Repeating Character in a String – JavaScript DSA Challenge
๐ Day 12: First Non-Repeating Character in a String – JavaScript DSA
Welcome to #Day12 of our CodeWithJaffer JavaScript DSA Challenge! In this post, we will find the first non-repeating character in a given string using simple JavaScript logic.
๐ Problem Statement:
Given a string, find the first character that does not repeat. If all characters repeat, return -1.
๐งช Example:
Input: "javascript" Output: "j" Input: "aabbcc" Output: -1
✅ JavaScript Code:
function firstUniqueChar(str) {
let freq = {};
for (let char of str) {
freq[char] = (freq[char] || 0) + 1;
}
for (let char of str) {
if (freq[char] === 1) return char;
}
return -1;
}
// Output Examples
console.log(firstUniqueChar("javascript")); // "j"
console.log(firstUniqueChar("aabbcc")); // -1
๐ก Tips to Remember:
- Use a
for...ofloop to count each character
Comments
Post a Comment