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...of loop to count each character

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