← Back to libraryQuestion 156 of 468
🧩JavaScript CodingIntermediate

First Non-Repeating Character

📌 Definition:

Return the first character in a string that appears exactly once (e.g. 'swiss' -> 'w').

📖 Detailed Explanation:

Two passes: first build a frequency map, then scan the string again and return the first character whose count is 1. O(n) time. A Map preserves insertion order which can simplify the second pass.

💻 Solutions:
function firstUnique(s) {
  const freq = {};
  for (const ch of s) freq[ch] = (freq[ch] || 0) + 1;
  for (const ch of s) if (freq[ch] === 1) return ch;
  return null;
}
🔑 Key Points:
  • Two passes: count, then find first with count 1
  • Return null / -1 when none exists
  • O(n) time, O(k) space (k = distinct chars)
  • Order matters — scan the ORIGINAL string in pass 2
🌍 Real-World Example:

This pattern (count then scan) generalizes to 'first unique request id' or 'first error that occurred only once' in log analysis.

🎯 Scenario-Based Interview Question:

A candidate returns the first key in the frequency object with count 1 instead of scanning the string. Why can that be wrong?