{"id":171,"date":"2024-09-28T18:58:45","date_gmt":"2024-09-28T18:58:45","guid":{"rendered":"https:\/\/feellikelearning.com\/en\/?p=171"},"modified":"2024-09-28T18:58:45","modified_gmt":"2024-09-28T18:58:45","slug":"leetcode-767-reorganize-string","status":"publish","type":"post","link":"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/","title":{"rendered":"Leetcode 767 Reorganize String"},"content":{"rendered":"\n<p>You can solve this problem by using a max-heap (priority queue) to always try to place the most frequent character at each position, ensuring that no two adjacent characters are the same. Here&#8217;s how you can implement it:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, count the frequency of each character.<\/li>\n\n\n\n<li>Use a max-heap to keep track of characters by their frequency.<\/li>\n\n\n\n<li>Greedily place characters one by one while ensuring no two adjacent characters are the same.<\/li>\n<\/ol>\n\n\n\n<p>Here&#8217;s the complete solution:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import heapq\nfrom collections import Counter\n\nclass Solution:\n    def reorganizeString(self, s: str) -> str:\n        # Step 1: Count the frequency of each character\n        char_count = Counter(s)\n        \n        # Step 2: Create a max heap based on frequency (negative to simulate max heap with heapq)\n        max_heap = &#91;(-count, char) for char, count in char_count.items()]\n        heapq.heapify(max_heap)\n        \n        # Step 3: The result array where we will build the solution\n        result = &#91;]\n        \n        # Step 4: Keep track of the previous character used (we start with None)\n        prev_count, prev_char = 0, ''\n        \n        while max_heap:\n            # Pop the most frequent character\n            count, char = heapq.heappop(max_heap)\n            \n            # Add the previous character back to the heap if it still has remaining occurrences\n            if prev_count &lt; 0:\n                heapq.heappush(max_heap, (prev_count, prev_char))\n            \n            # Append the current character to the result\n            result.append(char)\n            \n            # Decrease the count (since we have used one occurrence of this character)\n            prev_count, prev_char = count + 1, char  # count + 1 because it's a negative number in max heap\n            \n        # Step 5: Join the result array into a string and check if it is valid\n        result_str = ''.join(result)\n        if len(result_str) != len(s):\n            return \"\"\n        return result_str\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Frequency Count:<\/strong> We use <code>collections.Counter<\/code> to count how many times each character appears in the input string.<\/li>\n\n\n\n<li><strong>Max-Heap:<\/strong> We push the characters into a heap based on their frequency (negative to simulate a max heap). The most frequent characters will always come first.<\/li>\n\n\n\n<li><strong>Greedy Placement:<\/strong> In each iteration, we pop the most frequent character and append it to the result. We then push the previous character back into the heap if it still has remaining occurrences.<\/li>\n\n\n\n<li><strong>Validity Check:<\/strong> If the length of the final string does not match the input string, it means we couldn&#8217;t create a valid arrangement, and we return an empty string.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Time Complexity:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>O(n log k)<\/strong>, where <code>n<\/code> is the length of the string, and <code>k<\/code> is the number of unique characters. This is because we insert and pop from the heap, which takes <code>O(log k)<\/code> time.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example:<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>sol = Solution()\nprint(sol.reorganizeString(\"aab\"))  # Output: \"aba\"\nprint(sol.reorganizeString(\"aaab\")) # Output: \"\"\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>You can solve this problem by using a max-heap (priority queue) to always try to place the most frequent character at each position, ensuring that no two adjacent characters are the same. Here&#8217;s how you can implement it: Here&#8217;s the complete solution: Explanation: Time Complexity: Example:<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-171","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Leetcode 767 Reorganize String - Feel Like Learning<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Leetcode 767 Reorganize String - Feel Like Learning\" \/>\n<meta property=\"og:description\" content=\"You can solve this problem by using a max-heap (priority queue) to always try to place the most frequent character at each position, ensuring that no two adjacent characters are the same. Here&#8217;s how you can implement it: Here&#8217;s the complete solution: Explanation: Time Complexity: Example:\" \/>\n<meta property=\"og:url\" content=\"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/\" \/>\n<meta property=\"og:site_name\" content=\"Feel Like Learning\" \/>\n<meta property=\"article:published_time\" content=\"2024-09-28T18:58:45+00:00\" \/>\n<meta name=\"author\" content=\"feellikelearning\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"feellikelearning\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"1 minute\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/\",\"url\":\"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/\",\"name\":\"Leetcode 767 Reorganize String - Feel Like Learning\",\"isPartOf\":{\"@id\":\"https:\/\/feellikelearning.com\/en\/#website\"},\"datePublished\":\"2024-09-28T18:58:45+00:00\",\"dateModified\":\"2024-09-28T18:58:45+00:00\",\"author\":{\"@id\":\"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/1ec5aac313d6de20215fe2b8e176b8a7\"},\"breadcrumb\":{\"@id\":\"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/feellikelearning.com\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Leetcode 767 Reorganize String\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/feellikelearning.com\/en\/#website\",\"url\":\"https:\/\/feellikelearning.com\/en\/\",\"name\":\"Feel Like Learning\",\"description\":\"keep curiosity alive\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/feellikelearning.com\/en\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/1ec5aac313d6de20215fe2b8e176b8a7\",\"name\":\"feellikelearning\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/36aec9d519f02362e3e89b0716ae640d08701f57e818830f3f197db5fbc1ae20?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/36aec9d519f02362e3e89b0716ae640d08701f57e818830f3f197db5fbc1ae20?s=96&d=mm&r=g\",\"caption\":\"feellikelearning\"},\"sameAs\":[\"http:\/\/feellikelearning.com\/en\"],\"url\":\"https:\/\/feellikelearning.com\/en\/index.php\/author\/feellikelearning\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Leetcode 767 Reorganize String - Feel Like Learning","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/","og_locale":"en_US","og_type":"article","og_title":"Leetcode 767 Reorganize String - Feel Like Learning","og_description":"You can solve this problem by using a max-heap (priority queue) to always try to place the most frequent character at each position, ensuring that no two adjacent characters are the same. Here&#8217;s how you can implement it: Here&#8217;s the complete solution: Explanation: Time Complexity: Example:","og_url":"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/","og_site_name":"Feel Like Learning","article_published_time":"2024-09-28T18:58:45+00:00","author":"feellikelearning","twitter_card":"summary_large_image","twitter_misc":{"Written by":"feellikelearning","Est. reading time":"1 minute"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/","url":"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/","name":"Leetcode 767 Reorganize String - Feel Like Learning","isPartOf":{"@id":"https:\/\/feellikelearning.com\/en\/#website"},"datePublished":"2024-09-28T18:58:45+00:00","dateModified":"2024-09-28T18:58:45+00:00","author":{"@id":"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/1ec5aac313d6de20215fe2b8e176b8a7"},"breadcrumb":{"@id":"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/feellikelearning.com\/en\/index.php\/2024\/09\/28\/leetcode-767-reorganize-string\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/feellikelearning.com\/en\/"},{"@type":"ListItem","position":2,"name":"Leetcode 767 Reorganize String"}]},{"@type":"WebSite","@id":"https:\/\/feellikelearning.com\/en\/#website","url":"https:\/\/feellikelearning.com\/en\/","name":"Feel Like Learning","description":"keep curiosity alive","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/feellikelearning.com\/en\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/1ec5aac313d6de20215fe2b8e176b8a7","name":"feellikelearning","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/feellikelearning.com\/en\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/36aec9d519f02362e3e89b0716ae640d08701f57e818830f3f197db5fbc1ae20?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/36aec9d519f02362e3e89b0716ae640d08701f57e818830f3f197db5fbc1ae20?s=96&d=mm&r=g","caption":"feellikelearning"},"sameAs":["http:\/\/feellikelearning.com\/en"],"url":"https:\/\/feellikelearning.com\/en\/index.php\/author\/feellikelearning\/"}]}},"_links":{"self":[{"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/posts\/171","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/comments?post=171"}],"version-history":[{"count":1,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/posts\/171\/revisions"}],"predecessor-version":[{"id":172,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/posts\/171\/revisions\/172"}],"wp:attachment":[{"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/media?parent=171"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/categories?post=171"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/feellikelearning.com\/en\/index.php\/wp-json\/wp\/v2\/tags?post=171"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}