Rearrange string

You are given a string “S”. Your task is to rearrange the characters of a string “S”, such that it does not contain any two adjacent characters which are the same.

If it is possible to rearrange the string “S”, then print any possible arrangement. else, print “not possible” without quotes.

For Example:

For a string  “qaacde”, This string has two same adjacent characters.
So, one possible way to rearrange the string is “qacade”. Now, this string does not have two adjacent characters that are the same. 
Input format :
The first line of input contains a single integer T, representing the number of test cases or queries to be run. 

Then the T test cases follow.

The first line of each test case contains a string S.
Output format :
For each test case, the output will be “Yes” if you have returned the correct answer, else it will be “No”.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10    
0 <= |S| <= 10^5 

Time Limit: 1 sec
CodingNinjas
author
2y
Brute force

In this approach, we will generate all the possible rearrangements of the string and check if the current string in our rearrangement does not have any two adjacent characters that are the ...read more

CodingNinjas
author
2y
Heap Approach

The idea is here to store the frequency of each character in a hashmap and then build a max heap of pairs containing the frequency of character and character.

We will always pick the highe...read more

CodingNinjas
author
2y
Sorting Approach

The idea is here to sort the string based on the frequency of characters and then merge characters one by one from the front and middle of the string using left and right pointers.

Ste...read more

CodingNinjas
author
2y
Hashing Approach

The idea here is to store the frequency of each character of a string in a frequency array.

Let’s consider the following two observations:

  1. We can fill the same characters in either even ...read more
Add answer anonymously...
Microsoft Corporation SDE-2 Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter