{"id":4847,"date":"2023-06-27T19:41:54","date_gmt":"2023-06-27T14:11:54","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=4847"},"modified":"2023-06-27T19:42:34","modified_gmt":"2023-06-27T14:12:34","slug":"sort-string","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/sort-string\/","title":{"rendered":"Sort String (C++, Java, and Python)"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><li><a href=\"#approach-1-using-inbuilt-sort\">Approach 1: Using inbuilt sort<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code-implementation\">C++ Code Implementation<\/a><\/li><li><a href=\"#java-code-implementation\">Java Code Implementation<\/a><\/li><li><a href=\"#python-code-implementation\">Python Code Implementation<\/a><\/li><\/ul><li><a href=\"#approach-2-hashing\">Approach 2: Hashing<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code-implementation\">C++ Code Implementation<\/a><\/li><li><a href=\"#java-code-implementation\">Java Code Implementation<\/a><\/li><li><a href=\"#python-code-implementation\">Python Code Implementation<\/a><\/li><\/ul><li><a href=\"#practice-question---\">Practice Question &#8211; <\/a><\/li><li><a href=\"#faqs\">FAQs<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-how-to-count-the-frequency-of-characters-of-a-string\">Q.1: How to count the frequency of characters of a string?<\/a><\/li><li><a href=\"#q2-what-is-the-most-efficient-approach-to-solving-this-problem\">Q.2: What is the most efficient approach to solving this problem?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given a string S of lowercase English characters \u2018a\u2019 &#8211; \u2018z\u2019. The task is to sort the string.<\/p>\n\n\n\n<p id=\"examples\"><strong>Examples:<\/strong><\/p>\n\n\n\n<ul><li><strong>Input:\u00a0 <\/strong>S = \u201cdceabb\u201d<ul><li><strong>Output:<\/strong> \u201cabbcde\u201d<\/li><\/ul><\/li><\/ul>\n\n\n\n<ul><li><strong>Input:\u00a0 <\/strong>S = \u201ceeetag\u201d<strong>\u00a0<\/strong><ul><li><strong>Output:<\/strong> \u201caeeegt\u201d<\/li><\/ul><\/li><\/ul>\n\n\n\n<h2 id=\"approach-1-using-inbuilt-sort\">Approach 1: Using inbuilt sort<\/h2>\n\n\n\n<p>The most basic approach to solve this problem is to simply use the inbuilt sorting algorithms of the respective languages.<\/p>\n\n\n\n<h3 id=\"c-code-implementation\"><span id=\"c-code-implementation-2\">C++ Code Implementation<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">void sortString(string &amp;str){\n   sort(str.begin(), str.end());\n   cout &lt;&lt; str;\n}<\/pre>\n\n\n\n<h3 id=\"java-code-implementation\"><span id=\"java-code-implementation-2\">Java Code Implementation<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"> static void sortString(String str) {\n        char []arr = str.toCharArray();\n        Arrays.sort(arr);\n        System.out.print(String.valueOf(arr));\n }<\/pre>\n\n\n\n<h3 id=\"python-code-implementation\"><span id=\"python-code-implementation-2\">Python Code Implementation<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def sortString(str) :\n    str = ''.join(sorted(str))\n    print(str)<\/pre>\n\n\n\n<ul><li><strong>Time Complexity:<\/strong> O(NlogN), where N is the length of the string.<\/li><li><strong>Space Complexity:<\/strong> O(1) since no extra space is used.<\/li><\/ul>\n\n\n\n<h2 id=\"approach-2-hashing\">Approach 2: Hashing<\/h2>\n\n\n\n<p>A quick observation is that the string will contain the utmost 26 unique characters. Therefore, the idea is to count the frequency of each character using a map or similar data structure. Each index of the map will represent the characters from \u2018a\u2019 &#8211; \u2018z\u2019. Therefore for each index, we can print the total number of times the given character is present.<\/p>\n\n\n\n<p><strong>Algorithm<\/strong><\/p>\n\n\n\n<ul><li>Initialise a frequency array of size 26.<\/li><li>Iterate through the string and count the frequency of each character.<\/li><li>Run a loop from i = 0 till 26 and for each i, print the corresponding character freq[i] times.<\/li><\/ul>\n\n\n\n<h3 id=\"c-code-implementation\">C++ Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">const int MAX_CHAR = 26;\n \nvoid sortString(string &amp; str) {\n  int charCount[MAX_CHAR] = {\n    0\n  };\n  for (int i = 0; i &lt; str.length(); i++)\n    charCount[str[i] - 'a']++;\n \n  for (int i = 0; i &lt; MAX_CHAR; i++)\n    for (int j = 0; j &lt; charCount[i]; j++)\n      cout &lt;&lt; (char)('a' + i);\n}<\/pre>\n\n\n\n<h3 id=\"java-code-implementation\">Java Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"> public class SortString {\n  static final int MAX_CHAR = 26;\n \n  static void sortString(String str) {\n \n    int letters[] = new int[MAX_CHAR];\n    for (char x: str.toCharArray()) {\n      letters[x - 'a']++;\n    }\n    for (int i = 0; i &lt; MAX_CHAR; i++) {\n      for (int j = 0; j &lt; letters[i]; j++) {\n        System.out.print((char)(i + 'a'));\n      }\n    }\n  }\n}<\/pre>\n\n\n\n<h3 id=\"python-code-implementation\">Python Code Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">MAX_CHAR = 26\n \n \ndef sortString(str):\n    charCount = [0 for i in range(MAX_CHAR)]\n    for i in range(0, len(str), 1):\n        charCount[ord(str[i]) - ord(\"a\")] += 1\n \n    for i in range(0, MAX_CHAR, 1):\n        for j in range(0, charCount[i], 1):\n            print(chr(ord(\"a\") + i), end=\"\")<\/pre>\n\n\n\n<ul><li><strong>Time Complexity:<\/strong> O(N * 26), where N is the length of the string.<\/li><li><strong>Space Complexity:<\/strong> O(1) since constant space of size 26 is used.<\/li><\/ul>\n\n\n\n<h2 id=\"practice-question---\"><span id=\"practice-question\">Practice Question &#8211; <\/span><\/h2>\n\n\n\n<ul><li><a rel=\"noreferrer noopener\" href=\"https:\/\/www.interviewbit.com\/problems\/sorted-permutation-rank\/\" target=\"_blank\">Sorted Permutation Rank<\/a><\/li><\/ul>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<h3 id=\"q1-how-to-count-the-frequency-of-characters-of-a-string\"><span id=\"q-1-how-to-count-the-frequency-of-characters-of-a-string\">Q.1: How to count the frequency of characters of a string?<\/span><\/h3>\n\n\n\n<p><strong>Ans. <\/strong>The frequency of characters can be counted using a hashmap. Iterate through the string and for each character S[i], perform freq[S[i]]++<\/p>\n\n\n\n<h3 id=\"q2-what-is-the-most-efficient-approach-to-solving-this-problem\"><span id=\"q-2-what-is-the-most-efficient-approach-to-solving-this-problem\">Q.2: What is the most efficient approach to solving this problem?<\/span><\/h3>\n\n\n\n<p><strong>Ans: <\/strong>The hashing technique is the most efficient approach to solving the problem. The time complexity is O(N * 26) and the space complexity is O(1).<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given a string S of lowercase English characters \u2018a\u2019 &#8211; \u2018z\u2019. The task is to sort&hellip;\n","protected":false},"author":5,"featured_media":5028,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[675],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4847"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=4847"}],"version-history":[{"count":4,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4847\/revisions"}],"predecessor-version":[{"id":20922,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4847\/revisions\/20922"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/5028"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=4847"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=4847"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=4847"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}