Skip to main content

Rearrange String to Avoid Character Pair - Solution & Explanation

Practice this problem

Problem Statement

You are given a string s and two distinct lowercase English letters x and y.

Rearrange the characters of s to construct a new string t such that:

  • t is a permutation of s.
  • Every occurrence of y appears before every occurrence of x in t.

Return any valid string t.

 

Example 1:

Input: s = "aabc", x = "a", y = "c"

Output: "cbaa"

Explanation:

The string "cbaa" is a permutation of "aabc", and every occurrence of 'c' appears before every occurrence of 'a'.

Example 2:

Input: s = "dcab", x = "d", y = "b"

Output: "cabd"

Explanation:

The string "cabd" is a permutation of "dcab", and every occurrence of 'b' appears before every occurrence of 'd'.

Example 3:

Input: s = "axe", x = "o", y = "x"

Output: "axe"

Explanation:

The string "axe" is already valid. Since 'o' does not occur in the string, the required condition is automatically satisfied.

 

Constraints:

  • 1 <= s.length <= 100
  • s consists of lowercase English letters.
  • x and y are lowercase English letters.
  • x != y

Approach Overview

Problem Overview: You need to rearrange characters in a string so a restricted character pair does not appear next to each other. The challenge is preserving all characters while building a valid ordering. Most solutions rely on frequency tracking and careful placement of characters during iteration.

Approach 1: Generate All Permutations (O(n!))

The brute force approach generates every possible permutation of the string and checks whether the resulting arrangement contains the forbidden adjacent pair. You iterate through each permutation and validate neighboring characters with a simple scan. This approach is useful for understanding the constraint, but it becomes unusable once the string length grows beyond small test cases. Space complexity is O(n) for recursion and temporary storage.

Approach 2: Greedy Frequency Placement with Sorting (O(n log n))

A more practical method counts character frequencies using a hash map, sorts characters by frequency, then places them strategically to avoid invalid adjacency. The key insight is to distribute high-frequency characters first so they do not cluster into restricted pairs later. You repeatedly append a valid character while tracking the previously placed character and the restricted combination. This approach works well when the alphabet size is limited and is commonly implemented with arrays or hash maps. Time complexity is O(n log k), where k is the number of distinct characters, and space complexity is O(k).

Approach 3: Max Heap Greedy (O(n log k))

The optimal interview approach uses a max heap to always pick the character with the highest remaining frequency that does not violate the adjacency rule. You pop the best candidate, append it to the result, then temporarily hold the previously used character until it becomes valid again. This prevents invalid pairs while ensuring characters are consumed efficiently. Heap operations keep insertion and extraction fast, making this approach scalable for larger inputs. It combines greedy algorithms with priority queues. Time complexity is O(n log k) and space complexity is O(k).

Recommended for interviews: Interviewers typically expect the heap-based greedy solution because it demonstrates control over ordering constraints and efficient frequency management. Showing the brute force approach first proves you understand the problem definition, but moving to the heap optimization shows stronger algorithmic thinking and better scalability analysis.

Solution

We need to construct a permutation t of s such that every occurrence of y appears before every occurrence of x. There are no extra constraints on the other characters.

Therefore, it suffices to move all occurrences of y to the front of the string. Traverse the string with two pointers: i points to the next position where a y should be placed, and j scans from left to right. Whenever t[j] = y, swap t[i] with t[j] and increment i. After the scan, the prefix of t consists entirely of y, which naturally satisfies the requirement that all y appear before all x.

The time complexity is O(n), and the space complexity is O(n), where n is the length of s.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Generate All PermutationsO(n!)O(n)Tiny inputs or brute force validation
Greedy Frequency PlacementO(n log k)O(k)General-purpose solution with manageable character set
Max Heap GreedyO(n log k)O(k)Best interview solution and large-scale inputs

Video Solution

3992. Rearrange String to Avoid Character Pair (Leetcode Easy) • Programming Live with Larry • 64 views views

Watch 2 more video solutions →

Frequently Asked Questions

Is Rearrange String to Avoid Character Pair easy or hard?
The problem is generally classified as Easy when constraints are small or only basic adjacency rules exist. The heap-based optimization moves it closer to Medium interview difficulty because it requires careful greedy reasoning.
Rearrange String to Avoid Character Pair Python/Java solution
Python solutions usually use collections.Counter with heapq, while Java implementations commonly use HashMap and PriorityQueue. Both approaches achieve O(n log k) time complexity with clean greedy logic.
How to solve Rearrange String to Avoid Character Pair in O(n)?
An O(n) solution is possible when the character range is fixed and small, such as lowercase English letters. You can use frequency arrays and direct placement instead of a heap. For the general case with arbitrary characters, O(n log k) is the standard optimal complexity.
What is the best approach for Rearrange String to Avoid Character Pair?
The max heap greedy approach is usually the best solution because it always selects the most frequent valid character while avoiding restricted adjacent pairs. It runs in O(n log k) time, where k is the number of unique characters, and uses O(k) extra space.
Is Rearrange String to Avoid Character Pair asked at Google/Amazon/Meta?
String rearrangement and greedy scheduling problems are common in interviews at Google, Amazon, Meta, and other large tech companies. Variants often test heap usage, frequency counting, and adjacency constraints under time pressure.
What data structure is used in Rearrange String to Avoid Character Pair?
Most efficient solutions use a hash map for frequency counting and a max heap or priority queue for selecting the next valid character. Arrays can replace hash maps when the character set is fixed.
What is the time complexity of Rearrange String to Avoid Character Pair?
The optimal solution typically runs in O(n log k) time using a priority queue or heap. Frequency counting takes O(n), and each heap insertion or removal costs O(log k). Space complexity is O(k).

Ready to solve this problem?

Practice Rearrange String to Avoid Character Pair with our built-in code editor and test cases.

Practice on FleetCode