Arrays and Hashing Hash map lookups

65. First Unique Character in a String

Easy

You are given a string s. Find the first letter of s that appears in it exactly once, and return its index. If every letter of s appears two or more times, return -1.

"First" means the smallest index in s, reading from left to right. Indexes start at 0.

Example 1

Input: s = "statistics"

Output: 2

Explanation: s and t appear three times each and i twice. Only a and c appear once, and a comes first, at index 2.

Example 2

Input: s = "aabbcc"

Output: -1

Example 3

Input: s = "racecar"

Output: 3

Explanation: r, a and c each appear twice. The only letter that appears once is the e in the middle, at index 3.

Check your understanding

Work out the answer for this input before you write any code.

s = "stress"

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds lowercase English letters only.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.