PHP Code – Find First Non-Repeated Character in a String

Given an input string, Write a PHP code to find the first Non-repeated character in a string. Suppose an input string is webrewrite, the first non-repeated character in this string is b.

How to Find First Non-Repeating Character in a String

Method 1 – Naive Approach

Use two for loops and compare each character with every character of a string.  But the time complexity of this approach is  O(n2).

Method 2 – Create a key and value pairs for character and it’s count

We can create a key and value pairs for character and it’s count. This approach is much better as compared to first one. Let’s implement this method.

PHP Code to Find the First Non-repeated Character in a String

PHP Code to Find the First Non-repeated Character in a String

PHP Code to Find the First Non-Repeated Character in a String

Let’s try to solve this problem in a single traversal.

Method 2:

How to sort string in PHP

Java Program to find the first non-repeated character in a string

Conclusion

If you know some other efficient way to solve this problem then let us know through your comments.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.