Skip to content

Commit 1330a2a

Browse files
authored
Merge pull request #3 from harshbhagwani94/patch-1
Added IITR Flipkart 2018
2 parents 5da2706 + f0eaafe commit 1330a2a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

smallestRestrictedPalindrome.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
IITR Flipkart 2018
3+
4+
Given a string s, return a string t satisfying the following:
5+
1. s contains t
6+
2. t is a palindrome
7+
3. t is largest possible
8+
If multiple t exists, return the lexicographically smallest t.
9+
10+
1 <= |s| <= 100000
11+
12+
O(|s| + 26)
13+
*/
14+
string smallestRestrictedPalindrome(string s) {
15+
int c[26] = {};
16+
for (char ch : s) c[ch - 'a']++;
17+
string t = "";
18+
for (int i = 0; i < 26; i++) {
19+
for (int j = c[i] >> 1; j--; ) {
20+
t += (char)('a' + i);
21+
}
22+
}
23+
int fl = 0;
24+
for (int i = 0; not fl and i < 26; i++) {
25+
if (c[i] & 1) {
26+
t += (char)('a' + i);
27+
fl = 1;
28+
}
29+
}
30+
int n = t.size() - fl;
31+
for (int i = n; i--; ) {
32+
t += t[i];
33+
}
34+
return t;
35+
}

0 commit comments

Comments
 (0)