#767

Reorganize String

Medium
Hash TableStringGreedySortingHeap (Priority Queue)Counting
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach involves generating all possible permutations of the string and checking if any of them meet the requirement of no two adjacent characters being the same. This is straightforward but inefficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate all permutations of the string.
  2. 2Step 2: Check each permutation to see if it has adjacent characters that are the same.
  3. 3Step 3: Return the first valid permutation found, or return an empty string if none are valid.
solution.py7 lines
1from itertools import permutations
2
3def reorganizeString(s):
4    for perm in set(permutations(s)):
5        if all(perm[i] != perm[i + 1] for i in range(len(perm) - 1)):
6            return ''.join(perm)
7    return ''

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.