EasyHash TableStringCounting

First Unique Character in a String

LeetCode
1 approach, code in all languages

Given a string, scan it from left to right and find the earliest character that appears exactly once across the whole string. Report the zero-based index of that character.

If every character in the string repeats, no such character exists and you should return -1.

Example 1

Input: s = "swiss"

Output: 1

's' occurs three times, so it is skipped. 'w' at index 1 is the first character that shows up only once.

Example 2

Input: s = "aabbcc"

Output: -1

Every character appears twice, so there is no character that occurs exactly once.

Constraints

  • 1 <= s.length <= 10^5
  • s contains only lowercase English letters
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now