First unique character

strings

First unique character

Amazon Python Interview Question

Amazon's warehouse scanners read product codes made of lowercase letters. The label team wants the position of the first letter that appears only once in a code.

Write a function first_unique(code) that returns the position of the first character that appears exactly once, or -1 if every character repeats. Positions start at 0.

Asked of

  • Data Analyst
  • Data Engineer
  • Data Scientist
  • ML Engineer
  • AI Engineer

Example 1

Input

code = "leetcode"

Output

0

Example 2

Input

code = "loveleetcode"

Output

2

Example 3

Input

code = "aabb"

Output

-1

Explanation

In the first example, "l" in "leetcode" appears only once and comes first, so the answer is 0. In the second example, "l" appears once but "o" at position 2 is the first character that never repeats. In "aabb", every letter repeats, so the answer is -1.

Submit also runs 3 hidden test cases that check edge cases.