From f0eaafe857a98f5a86b58a293a68afc74a49104d Mon Sep 17 00:00:00 2001 From: harshbhagwani94 <39380791+harshbhagwani94@users.noreply.github.com> Date: Sat, 10 Nov 2018 16:47:17 +0530 Subject: [PATCH] Added IITR Flipkart 2018 --- smallestRestrictedPalindrome.cpp | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 smallestRestrictedPalindrome.cpp diff --git a/smallestRestrictedPalindrome.cpp b/smallestRestrictedPalindrome.cpp new file mode 100644 index 0000000..b9d45db --- /dev/null +++ b/smallestRestrictedPalindrome.cpp @@ -0,0 +1,35 @@ +/* +IITR Flipkart 2018 + +Given a string s, return a string t satisfying the following: +1. s contains t +2. t is a palindrome +3. t is largest possible +If multiple t exists, return the lexicographically smallest t. + +1 <= |s| <= 100000 + +O(|s| + 26) +*/ +string smallestRestrictedPalindrome(string s) { + int c[26] = {}; + for (char ch : s) c[ch - 'a']++; + string t = ""; + for (int i = 0; i < 26; i++) { + for (int j = c[i] >> 1; j--; ) { + t += (char)('a' + i); + } + } + int fl = 0; + for (int i = 0; not fl and i < 26; i++) { + if (c[i] & 1) { + t += (char)('a' + i); + fl = 1; + } + } + int n = t.size() - fl; + for (int i = n; i--; ) { + t += t[i]; + } + return t; +}