{"id":1875,"date":"2024-03-06T22:00:00","date_gmt":"2024-03-06T22:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1875"},"modified":"2024-03-08T09:11:28","modified_gmt":"2024-03-08T09:11:28","slug":"first-unique-character-string","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/first-unique-character-string\/","title":{"rendered":"First Unique Character in a String (C++, Java, Python)"},"content":{"rendered":"\n<p>Data Structures is one of the most important subjects to conquer to become a good programmer. In this article, we will discuss the \u201cFirst Unique Character in a String\u201d problem from leetcode and how to code the solution.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>First Unique Character in a String problem<\/strong><\/h2>\n\n\n\n<p><strong>In the First Unique Character in a String problem, we have given a string and we must find the index of the first non-repeating character from the string. <\/strong><\/p>\n\n\n\n<p>For example, if you have given a string \u201cfavtutor\u201d<strong> <\/strong>then non-repeating characters in this string are f, a, v, u, o, r. The first non-repeating character is &#8216;f&#8217;. So the index is 0.&nbsp;<\/p>\n\n\n\n<p>Let&#8217;s look at some more examples:<\/p>\n\n\n\n<p><strong>Input<\/strong>: s = \u201camma\u201d<\/p>\n\n\n\n<p><strong>Output:<\/strong> -1 &nbsp; &nbsp; (as all the characters in this string have more than one occurrence)<\/p>\n\n\n\n<p><strong>Input:<\/strong> s = \u201cfavtutor\u201d<\/p>\n\n\n\n<p><strong>Output<\/strong>: 0<\/p>\n\n\n\n<p><strong>Input<\/strong>: s = \u201cabcac\u201d<\/p>\n\n\n\n<p><strong>Output:<\/strong> 1<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/0lw0lMR1A3MNZLc7zND76FlpY1zu-AO571QwRrwGP7T3GoQdMF5ETcsdNHEdHKnLsn1L1RScjKfA39-7htvHZU7EHGBFStQIRvhMMgKLzOoNMaJ7bg-tSWmE1Jhy_68aPTZGhI-tQkCniBcDYhC_E-M\" alt=\"Example of First Unique Character in a String problem\"\/><\/figure>\n\n\n\n<p>Note:&nbsp; String only contains lowercase alphabetical characters.<\/p>\n\n\n\n<p><strong>The easiest way is to go to each index and check if the same character is present in the string or not. <\/strong>If not, return this index; otherwise, check for the next index. If no such element is present, return -1.<\/p>\n\n\n\n<p>Let&#8217;s examine this approach on the string s = \u201cfavtutor.\u201d Simply, Iterate over the string and check if that character is present in that string or not. In this case, f is only present at index 0. So the answer is 0.<\/p>\n\n\n\n<p>Time Complexity here will be O(n^2), where \u2018n\u2019 is the size of the string. As we are iterating over two loops. One to go at each place, another to check if that character is present more than once or not. Space complexity will be O(1) as we are not using any extra space.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Hash-Map Approach<\/strong><\/h2>\n\n\n\n<p>The brute force approach is taking too much time. We can reduce the time complexity if we use a<a href=\"https:\/\/favtutor.com\/blogs\/pandas-map\"> hash map<\/a> to store the characters of the string. This will reduce the time complexity from O(n^2) to O( n log(n) ).&nbsp;<\/p>\n\n\n\n<p>Let\u2019s find out the steps involved:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create a hash map that will store the frequency of each character.<\/li>\n\n\n\n<li>Store each character on the map.<\/li>\n\n\n\n<li>Iterate over the string and check the frequency of that character. If the frequency is one then return this index. Otherwise, check for the next index.<\/li>\n\n\n\n<li>If there is no such character, return -1.<\/li>\n<\/ol>\n\n\n\n<p>Time Complexity will be O( n log(n) ). Here n is the size of the string. As we are storing each character in the map and storing values in the map it requires log(n) time. Space complexity will be O(26), which is approximately O(1), as there are only 26 different characters.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimized Approach<\/strong><\/h2>\n\n\n\n<p>In the hash map approach, we saw that if we store the frequency of each character we can easily find out the first non-repeating character. However, storing elements into the hash map requires Log(n) time complexity. This can be reduced if we use an array of size 26 and store the frequency using it.&nbsp;<\/p>\n\n\n\n<p>Let&#8217;s examine this approach.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, create an array of size 26 with initially all values equal to 0.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/4WIfhQeULraMwWLREs7idF0xFySTkaRdDic_dhrrAKmoPmusPcSIeiiIUJHRCCO1gQeuutZF-v1hkcAwB31s3pQScPyKSbV0c3dPRDsO1hjdFxX5BFl5LwcCyfyMWekIIoJCh1Sia1GIoHwgu-uAr88\" alt=\"Create Initial Array\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Iterate over the string and keep updating the values of the array.&nbsp;<\/li>\n\n\n\n<li>Index: 0<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/xRWlejh0-hJLnYpgnDDt3wJWE5eBu_CobA3mD0XTiwGlONdmI1iLUCY0M6eZhHOF7-wO5HeLPy-aB0rYICXmlb2bcX00fNoTVkniYsIZs_zvpuRy0OAJAyoqaGTUDQaS3k-rPeg1pyRoKrPuRfPa7J0\" alt=\"Index 0\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Index: 1<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/waQDop6biXm9Vsu2ZgvRLfhhA_VV40YqWJJ8ivULbhSuVvvkiqayGlnzQpdcNFPKWyt-CUgd2RgCpaEdGWniSMSMJ2-8wl_kxfbkQVhvV-r7jbJV40A_mv0uChi3BmKbApldkwT5AnZat2oF5yq9Gok\" alt=\"Index 1\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Index: 2<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/hm4EjnWRAKbbnQmsmVP4O-yUO8GTLBmvIP3zesQEqEPcL-tyXy68I3kM8heKFNd8gex4pxFNw932P2kKmBGZ3SAu5M2WDUtGHA64_G1_mBwA1017Wtk33GG6xQUobjblAyKmQIlGqr1zvPZ2kBwJKUo\" alt=\"Index 2\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Index: 3<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/odp-UwO6zmqnRPihKcZrNKkKR__HkOaPjd4YE1F9vOLIupAVpww16GMdyOJlxkKaQSq-GZez9YMfq-ikJK3189zKdcAN45nRhgUXM5ORfgnBeRLxRnSMyJvgTiWA4Ko40Sx5bT3gbDNSC5PzgfOTZKw\" alt=\"Index 3\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Index: 4<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/QsnkV10lBM46Ha_v69bhPWXm89oYJ_n89hxkrzozxLOVVzo-H_9BJzKnRPvOTxseSKBRGoIE1iHdJrLJqVP-928D0LfJeEEUAulAQCNMJJIR_oAYqfxcPfQnmItBAhrkw-p55bhqJLvxLxM-LgvmbpI\" alt=\"Index 4\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Index: 5<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/MEMM1KcKsFY9GaWErQ9pmPy8T9WTbrhC_x87fnchT11wvjPoOFKewo19WFWXd_Bm2YVBt7o1AOWN_Nb58E-hrrgLcOsiMi6bCoEwxDRVtfSFdl9iK_wuICLaqcwAA-W8bEvvh9zYnAftPoF-YPT1xUY\" alt=\"Index 5\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Index: 6<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/EZbbWq9Ej8wrBn8e3L0_Enk9kB9kdwLbn78L_4Jyxm4IZ-P6L6rQueM6l4kIda-G3DYEOkZjQWNx2bx6nh7yrT_pOVsL4Dvwy_vBOPObCLMcib00xlYn4yPWsE-4VWxVHfp6J1Mvrjrq3tFfWaxOJo8\" alt=\"Index 6\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Index: 7<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/YIRziCG1rlNfLBULpb9nM9mI7qZ_qnKeWHx_nXKpnUUrAeBAfBBS-rAi_DofGp6FljuI2caHxmNiVrKJzpfAmdWmpXli8KjL4A5I2auP28SHqhai3o1ebgnYLzbkbpZzgyvwXtVbSROkx8Pox5LPW8E\" alt=\"Index 7\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Last, Iterate over the string again and check in the array if the character frequency is one or not. If one returns that index.<\/li>\n<\/ul>\n\n\n\n<p>Let\u2019s see the code for the above approach.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ solution:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nint main(){\n\n    string s =  &quot;favtutor&quot;;\n\n    \/\/ array count to store the frequency of characters. \n    vector&lt;int&gt;count(26,0);\n\n    for(int i=0;i&lt;s.size();i++){\n        \/\/ storing the frequency of the character.\n        count[s[i]-'a']++;\n    }\n\n    for(int i=0;i&lt;s.size();i++){\n        \/\/ checking if the character is non-repeating or not.\n        if(count[s[i]-'a']==1) {\n            cout&lt;&lt;i&lt;&lt;endl;\n            goto he;\n        }\n    }\n\n    cout&lt;&lt;-1&lt;&lt;endl;\n    he:;\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Below is the Java program to find the first unique character in a string:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">public class Main {\n    public static void main(String[] args) {\n        String s = &quot;favtutor&quot;;\n\n        \/\/ array count to store the frequency of characters. \n        int[] count = new int[26];\n\n        for (int i = 0; i &lt; s.length(); i++) {\n\n\t \/\/ storing the frequency of the character.\n            count[s.charAt(i) - 'a']++;\n        }\n\n        for (int i = 0; i &lt; s.length(); i++) {\n            \/\/ checking if the character is non-repeating or not.\n            if (count[s.charAt(i) - 'a'] == 1) {\n                System.out.println(i);\n                break;\n            }\n        }\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>We can implement the optimized apprach in Python also:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">s = &quot;favtutor&quot;\ncount = [0] * 26\n\nfor char in s:\n     # storing the frequency of the character.\n    count[ord(char) - ord('a')] += 1\n\nfor i, char in enumerate(s):\n    if count[ord(char) - ord('a')] == 1:\n        print(i)\n        break\nelse:\n    print(-1)<\/pre><\/div>\n\n\n\n<p><strong>Output:&nbsp;<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-f0454ca1e2dae3802c9e2bf8b8fde5c5\" style=\"background-color:#fedcba\"><code>0<\/code><\/pre>\n\n\n\n<p>In this approach, we are storing the values in the array which requires O(1) time to store which reduces our time complexity to O( n log(n) ). Space Complexity is O(1) as only 26 values are stored in the array.<\/p>\n\n\n\n<p>Here is a comparison of the three approaches we discussed:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th><strong>Approach<\/strong><\/th><th class=\"has-text-align-center\" data-align=\"center\"><strong>Time Complexity<\/strong><\/th><th class=\"has-text-align-center\" data-align=\"center\"><strong>Space Complexity<\/strong><\/th><th><strong>Description<\/strong><\/th><\/tr><\/thead><tbody><tr><td>Brute Force Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n^2)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td>As we are iterating the string two times.<\/td><\/tr><tr><td>Hash Map Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O( n log(n) )&nbsp;<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td>Storing the values in the hash map requires log(n) time complexity.<\/td><\/tr><tr><td>Optimized Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td>Storing the values in the array reduces the time to O(n).<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we found various ways to find the first unique character in a string, a problem listed in <a href=\"https:\/\/leetcode.com\/problems\/first-unique-character-in-a-string\/description\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode<\/a> as well. We had only considered lowercase in this article to try to solve this question if there are both lower and uppercase on your own. Try to find out those and also find out their time complexity.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to find the First Unique Character in a String, a leetcode problem, with implementation in C++, Java, and Python.<\/p>\n","protected":false},"author":14,"featured_media":1877,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1875","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1875","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1875"}],"version-history":[{"count":5,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1875\/revisions"}],"predecessor-version":[{"id":2263,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1875\/revisions\/2263"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1877"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1875"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1875"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1875"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}