One-of-a-Kind Bead

Easyhash mapAlso known as First Unique Character in a String

You make bracelets. Before tying one off, you lay the beads in a line and write their colours as letters: r for red, g for green, b for blue, and so on.

The clasp goes next to a bead whose colour appears nowhere else on the bracelet. If several beads qualify, you pick the one closest to the start.

Your task

Write firstSoloBead(beads). beads is a string of lowercase letters, one per bead. Return the position (index) of the first bead whose letter appears exactly once in the whole string.

If every colour appears at least twice, or the string is empty, return -1.

firstSoloBead(beads: string) → int

Examples

Example 1
Input
beads = "rgrbgy"
Output
3
Why

Red and green appear twice. Blue (position 3) and yellow (position 5) appear once. Blue comes first, so the answer is 3.

Example 2
Input
beads = "wkkw"
Output
-1
Why

White and black both appear twice, so no bead is one of a kind.

Example 3
Input
beads = "ppob"
Output
2
Why

The answer is 2, not 0. Purple at position 0 has not been repeated yet when you first see it, but it is repeated right after.

Constraints

  • 0 ≤ beads.length ≤ 100,000
  • beads contains only lowercase letters a to z.
Start with brute force

For each bead, scan the whole string and count how many beads share its colour. Return the first bead whose count is 1.

That takes O(n²) time, which is up to 10 billion comparisons for 100,000 beads, and most of them repeat counting that was already done.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code