Skip to content
Advertisement

First Unique Character in a String

Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.

JavaScript

I came up with the following solution. How can I make it more efficient for very long input strings?

JavaScript

Advertisement

Answer

Your version isn’t bad for few cases with “nice” strings… but using count is quite expensive for long “bad” strings, I’d suggest you cache items, for instance:

JavaScript

The results on my laptop are:

JavaScript

The version using cache gives you 8x speed up factor vs yours wich is using count function all the time. So, my general advice would be… cache as much as possible whether it’s possible

EDIT:

I’ve added Patrick Haugh version to the benchmark and it gave 10.92784585620725

EDIT2:

I’ve added Mehmet Furkan Demirel version to the benchmark and it gave 10.325440507549331

EDIT3:

I’ve added wim version to the benchmark and it gave 12.47985351744839

CONCLUSION:

I’d use the version i’ve proposed initially using a simple cache without relying on Python counter modules, it’s not necessary (in terms of performance)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement