Coding problem · Easy · Basics

First Unique Character

Easy Algorithms & data structures

Given a string s of lower-case letters, return the index of the first character that appears exactly once. If there's none, return -1.

Example 1

Input: s = "leetcode"
Output: 0

Example 2

Input: s = "loveleetcode"
Output: 2

Example 3

Input: s = "aabb"
Output: -1

Hints

Hint 1

First count how many times each character appears.

Hint 2

Then scan again and return the first index whose character has count 1.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Two passes: build a frequency map, then find the first character with frequency 1. Both passes are O(n).

Reference solution

function firstUniqueChar(s) {
  const count = new Map();
  for (const ch of s) count.set(ch, (count.get(ch) ?? 0) + 1);
  for (let i = 0; i < s.length; i++) if (count.get(s[i]) === 1) return i;
  return -1;
}

Was this page helpful?