Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

First Non-Repeating Character

Hash Mapsmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 124: Maps: Fundamentals

Implement `firstUnique(str)` that returns the index of the first character in `str` that appears only once. Return `-1` if none exists.

Sample tests

Input: firstUnique("leetcode")
Output: 0
Input: firstUnique("loveleetcode")
Output: 2
Input: firstUnique("aabb")
Output: -1

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Returning the first not-yet-seen character is wrong; you need count exactly one.

Learning resources

  • MDN: Map
Approach & explanation (try first)

Count characters, then scan again for the first with count one. O(n) time and space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.