Practice problem · easy
A banking app writes one lowercase letter to its log for every failed transfer. The letter is the error code: t is a timeout, d is a declined card, and so on.
The most common codes are well understood. The first code that happened only once all day is the most likely new bug, so an engineer wants to open it first.
Write first_rare_code(codes).
codes[i] is the error code of the i-th failed transfer.i whose letter appears exactly once in the whole log. Return i.-1 when every letter that appears, appears at least twice.Input: codes = "abcab"
Output: 2The trace counts every letter first, then scans the log again from the left and stops at the first letter whose count is 1.
| Step | Letter | Count of that letter | Result |
|---|---|---|---|
| count | a, b, c, a, b | a: 2, b: 2, c: 1 | table built |
| scan 0 | a | 2 | not rare |
| scan 1 | b | 2 | not rare |
| scan 2 | c | 1 | stop: return 2 |
The only letter that appears once is c, at position 2.
Input: codes = "aabb"
Output: -1Both letters appear twice, so no letter is rare.
Input: codes = "dcdc"
Output: -1Each letter appears twice. A rare letter must appear exactly once in the whole log, not only once in a row.
1 ≤ codes.length ≤ 100,000 (failed transfers in one day)codes[i] is a lowercase letter from a to z (the error code)Counting how often each position's letter appears, by scanning the whole log for every position, costs about n × n steps. At n = 100,000 that is 10^10, far over the budget of about 10^8 simple steps a second. The log has only 26 possible letters, so a table of 26 counters, filled in one pass, answers every "how often?" question in one step.
first_rare_code · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.