{"id":1060,"date":"2025-09-01T18:33:58","date_gmt":"2025-09-01T13:03:58","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=1060"},"modified":"2025-09-01T18:33:59","modified_gmt":"2025-09-01T13:03:59","slug":"sort-characters-by-frequency","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/sort-characters-by-frequency\/","title":{"rendered":"Sort Characters By Frequency | Leetcode 451 | Hash Map + Sorting Solution"},"content":{"rendered":"\n<p>The <strong>Sort Characters By Frequency<\/strong> problem asks us to rearrange the characters of a given string in <strong>descending order of frequency<\/strong>.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If multiple characters have the same frequency, their order does not matter.<\/li>\n\n\n\n<li>The output should be a new string where characters appear grouped by frequency.<\/li>\n<\/ul>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/sort-characters-by-frequency\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Examples<\/h3>\n\n\n\n<p><strong>Example 1<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"Input: s = &quot;tree&quot;\nOutput: &quot;eetr&quot;\nExplanation: 'e' appears 2 times, 't' and 'r' appear once.\nSo &quot;eetr&quot; or &quot;eert&quot; are both valid answers.\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">Input<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">s = &quot;tree&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">Output<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">&quot;eetr&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">Explanation<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">&#39;e&#39;<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #CE9178\">appears 2 times, &#39;t&#39; and &#39;r&#39; appear once.<\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">So &quot;eetr&quot; or &quot;eert&quot; are both valid answers.<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p><strong>Example 2<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"Input: s = &quot;cccaaa&quot;\nOutput: &quot;cccaaa&quot;\nExplanation: 'c' and 'a' both appear 3 times. \nEither &quot;cccaaa&quot; or &quot;aaaccc&quot; are valid outputs.\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">Input<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">s = &quot;cccaaa&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">Output<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">&quot;cccaaa&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">Explanation<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">&#39;c&#39;<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #CE9178\">and &#39;a&#39; both appear 3 times.<\/span><span style=\"color: #D4D4D4\"> <\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">Either &quot;cccaaa&quot; or &quot;aaaccc&quot; are valid outputs.<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p><strong>Example 3<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"Input: s = &quot;Aabb&quot;\nOutput: &quot;bbAa&quot;\nExplanation: 'b' appears 2 times, 'A' and 'a' appear once.\n&quot;bbAa&quot; or &quot;bbaA&quot; are valid outputs.\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">Input<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">s = &quot;Aabb&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">Output<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">&quot;bbAa&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">Explanation<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #CE9178\">&#39;b&#39;<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #CE9178\">appears 2 times, &#39;A&#39; and &#39;a&#39; appear once.<\/span><\/span>\n<span class=\"line\"><span style=\"color: #CE9178\">&quot;bbAa&quot;<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #CE9178\">or &quot;bbaA&quot; are valid outputs.<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Intuition and Approach<\/h2>\n\n\n\n<p>To solve the <strong>Sort Characters By Frequency<\/strong> problem, we can use a simple two-step approach:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Count frequencies of characters:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Use a hash map (dictionary) to store the frequency of each character.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Sort characters by frequency:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Use Python\u2019s <code>sorted()<\/code> function with a custom key to sort characters in descending order of frequency.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Build the result string:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Multiply each character by its frequency and append to the result.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p>This guarantees that the most frequent characters come first.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Code Implementation<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def frequencySort(self, s: str) -&gt; str:\n        result = &quot;&quot;\n        hash_map = {}\n        \n        # Step 1: Count frequencies\n        for ch in s:\n            hash_map[ch] = hash_map.get(ch, 0) + 1\n\n        # Step 2: Sort by frequency in descending order\n        for ch, freq in sorted(hash_map.items(), key=lambda x: x[1], reverse=True):\n            result += ch * freq  # Step 3: Build result string\n        \n        return result\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">frequencySort<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">s<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        result = <\/span><span style=\"color: #CE9178\">&quot;&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        hash_map = {}<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Step 1: Count frequencies<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> ch <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> s:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            hash_map[ch] = hash_map.get(ch, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">) + <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Step 2: Sort by frequency in descending order<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> ch, freq <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">sorted<\/span><span style=\"color: #D4D4D4\">(hash_map.items(), <\/span><span style=\"color: #9CDCFE\">key<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">lambda<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #9CDCFE\">x<\/span><span style=\"color: #D4D4D4\">: x[<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">reverse<\/span><span style=\"color: #D4D4D4\">=<\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            result += ch * freq  <\/span><span style=\"color: #6A9955\"># Step 3: Build result string<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> result<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Code Explanation<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Hash Map Counting:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Iterate over <code>s<\/code> and count frequency of each character.<\/li>\n\n\n\n<li>Example: <code>\"tree\"<\/code> \u2192 <code>{'t': 1, 'r': 1, 'e': 2}<\/code><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Sorting:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Sort dictionary items by frequency in descending order using <code>sorted(..., key=lambda x: x[1], reverse=True)<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Building Result:<\/strong>\n<ul class=\"wp-block-list\">\n<li>For each <code>(ch, freq)<\/code> pair, append <code>ch * freq<\/code> to the result string.<\/li>\n\n\n\n<li>Example: <code>'e' \u2192 \"ee\"<\/code>, <code>'t' \u2192 \"t\"<\/code>, <code>'r' \u2192 \"r\"<\/code> \u2192 final string <code>\"eert\"<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Dry Run<\/h2>\n\n\n\n<p>Input: <code>s = \"tree\"<\/code><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Count frequencies: <code>{'t': 1, 'r': 1, 'e': 2}<\/code><\/li>\n\n\n\n<li>Sort by frequency: <code>[('e', 2), ('t', 1), ('r', 1)]<\/code><\/li>\n\n\n\n<li>Build result:\n<ul class=\"wp-block-list\">\n<li><code>'e' * 2 \u2192 \"ee\"<\/code><\/li>\n\n\n\n<li><code>'t' * 1 \u2192 \"t\"<\/code><\/li>\n\n\n\n<li><code>'r' * 1 \u2192 \"r\"<\/code><br>Final string = <code>\"eetr\"<\/code><\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p>Output: <code>\"eetr\"<\/code><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Time and Space Complexity<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Counting characters: <code>O(N)<\/code><\/li>\n\n\n\n<li>Sorting unique characters: <code>O(K log K)<\/code>, where <code>K<\/code> = number of unique characters.<\/li>\n\n\n\n<li>Building result: <code>O(N)<\/code><\/li>\n\n\n\n<li>Overall = <strong>O(N + K log K)<\/strong><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Extra hash map for frequency count: <code>O(K)<\/code><\/li>\n\n\n\n<li>Output string: <code>O(N)<\/code><\/li>\n\n\n\n<li>Overall = <strong>O(N + K)<\/strong><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>The <strong>Sort Characters By Frequency<\/strong> problem can be efficiently solved using a <strong>hash map for counting<\/strong> and <strong>sorting by frequency<\/strong>.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Step 1: Count character frequencies.<\/li>\n\n\n\n<li>Step 2: Sort characters in descending order of frequency.<\/li>\n\n\n\n<li>Step 3: Build and return the result string.<\/li>\n<\/ul>\n\n\n\n<p>This approach runs in <strong>O(N + K log K)<\/strong> and is simple to implement in Python using hash maps and sorting.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Sort Characters By Frequency problem asks us to rearrange the characters of a given string in descending order of frequency. Here&#8217;s the [Problem Link] to begin with. Examples Example 1 Example 2 Example 3 Intuition and Approach To solve the Sort Characters By Frequency problem, we can use a simple two-step approach: This guarantees<\/p>\n","protected":false},"author":1,"featured_media":1062,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[3,4],"tags":[8,22],"class_list":{"0":"post-1060","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner","9":"tag-easy","10":"tag-strings"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/09\/sort-characters-by-frequency-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1060","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=1060"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1060\/revisions"}],"predecessor-version":[{"id":1061,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/1060\/revisions\/1061"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/1062"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=1060"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=1060"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=1060"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}