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 out in a line and write down their colours as letters: r for red, g for green, b for blue, and so on.

Your signature touch is to put the clasp next to a bead whose colour appears nowhere else on that bracelet. If there are several such beads, 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 appears twice and green appears twice. Blue, at position 3, appears once, and so does yellow at position 5. Blue comes first, so the answer is 3.

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

White and black both appear twice. No bead is one of a kind, so the answer is -1.

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, so it does not count.

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.

Every bead triggers a full scan, so this is O(n²). With 100,000 beads that is up to 10 billion letter comparisons, and most of them repeat the same counting work.

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