Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Reorganize String

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "767" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return "" if not possible. Example 1: Input: s = "aab" Output: "aba" Example 2: Input: s = "aaab" Output: "" Constraints: 1 <= s.length <= 500 s consists of lowercase English letters.

Explanation

Here's a breakdown of the approach and the Python code:

  • High-Level Approach:

    • Count character frequencies. The character with the highest frequency is critical.
    • Check feasibility: If the most frequent character appears more than (n+1)/2 times, rearrangement is impossible.
    • Use a max heap (priority queue) to greedily pick the most frequent character available and place it in the result.
  • Complexity:

    • Runtime: O(n log k), where n is the length of the string and k is the number of distinct characters (at most 26).
    • Storage: O(k), to store the character counts in the heap.

Code

    import heapq
from collections import Counter

def reorganize_string(s: str) -> str:
    """
    Rearranges a string such that no two adjacent characters are the same.

    Args:
        s: The input string.

    Returns:
        A rearranged string that satisfies the condition, or an empty string if not possible.
    """

    counts = Counter(s)
    max_heap = [(-count, char) for char, count in counts.items()]  # Use negative count for max heap
    heapq.heapify(max_heap)

    result = ""
    previous_count = 0
    previous_char = ''

    while max_heap:
        count, char = heapq.heappop(max_heap)
        result += char

        if previous_count < 0:
            heapq.heappush(max_heap, (previous_count, previous_char))

        previous_count = count + 1  # Decrement count (add 1 since count is negative)
        previous_char = char

    if len(result) == len(s):
        return result
    else:
        return ""

More from this blog

C

Chatmagic blog

2894 posts