Skip to content

Commit 3125364

Browse files
committed
rearrange
1 parent 543eace commit 3125364

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
- [Longest Common Subsequence](https://practice.geeksforgeeks.org/problems/longest-common-subsequence-1587115620/1 "view question") - [Cpp Solution](./solutions/Longest%20Common%20Subsequence.cpp)
8787
- [Program to generate all possible valid IP addresses from given string](https://www.geeksforgeeks.org/program-generate-possible-valid-ip-addresses-given-string/ "view topic")
8888
- [Smallest distinct window](https://practice.geeksforgeeks.org/problems/smallest-distant-window3132/1 "view question") - [Cpp Solution](./solutions/Smallest%20distinct%20window.cpp)
89+
- [Rearrange characters](https://practice.geeksforgeeks.org/problems/rearrange-characters/0# "view question") - [Cpp Solution](./solutions/Rearrange%20characters.cpp)
8990
- []( "view question") - [Cpp Solution](./solutions/.cpp)
9091

9192
### Searching & Sorting
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Rearrange characters
3+
====================
4+
5+
Given a string S with repeated characters (only lowercase). The task is to rearrange characters in a string such that no two adjacent characters are same.
6+
7+
Note : It may be assumed that the string has only lowercase English alphabets.
8+
9+
Input:
10+
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains a single line containing a string of lowercase english alphabets.
11+
12+
Output:
13+
For each test case in a new line print "1" (without quotes) if the generated string doesn't contains any same adjacent characters, else if no such string is possible to be made print "0" (without quotes).
14+
15+
Constraints:
16+
1 <= T <= 100
17+
1 <= length of string <= 104
18+
19+
Example:
20+
Input:
21+
3
22+
geeksforgeeks
23+
bbbabaaacd
24+
bbbbb
25+
Output:
26+
1
27+
1
28+
0
29+
30+
Explanation:
31+
Testcase 1: All the repeated characters of the given string can be rearranged so that no adjacent characters in the string is equal.
32+
Testcase 3: Repeated characters in the string cannot be rearranged such that there should not be any adjacent repeated character.
33+
*/
34+
35+
#include <bits/stdc++.h>
36+
using namespace std;
37+
38+
int solve()
39+
{
40+
string s;
41+
cin >> s;
42+
int size = (s.size() + 1) / 2;
43+
unordered_map<char, int> f;
44+
for (auto &i : s)
45+
f[i]++;
46+
for (auto &i : f)
47+
{
48+
if (i.second > size)
49+
{
50+
return 0;
51+
}
52+
}
53+
return 1;
54+
}
55+
56+
int main()
57+
{
58+
int t;
59+
cin >> t;
60+
while (t--)
61+
{
62+
cout << solve() << endl;
63+
}
64+
return 0;
65+
}

0 commit comments

Comments
 (0)