Encrypt the string - 2 Last Updated : 25 Mar, 2025 Comments Improve Suggest changes Like Article Like Report Try it on GfG Practice Given a lowercase English string s of length n, encrypt it as follows:Replace each contiguous group of the same character with the character followed by the lowercase hexadecimal representation of its length.Reverse the entire modified string.Return the encrypted string.Note: All Hexadecimal letters should be converted to Lowercase letters.Examples:Input: s = "aaaaaaaaaaa"Output: ba Explanation: Count consecutive characters: "aaaaaaaaaaa" → "a11".Convert frequency to hexadecimal: "a11" → "ab".Reverse the string: "ab" → "ba".Input: s = "abc"Output: 1c1b1aExplanation: Convert to character-frequency format: "abc" → "a1b1c1".Convert counts to hexadecimal (no change as 1 remains 1).Reverse the string: "a1b1c1" → "1c1b1a".Approach:Iterate over string s and count consecutive occurrences of each character. Convert the count to hexadecimal, append it to the answer, and build the result. Finally, reverse the result and return it. C++ #include <bits/stdc++.h> using namespace std; // Function to convert Decimal to Hex string convertToHex(int num) { string temp = ""; while (num != 0) { int rem = num % 16; char c; if (rem < 10) { c = rem + 48; } else { c = rem + 87; } temp += c; num = num / 16; } return temp; } // Function to encrypt the string string encryptString(string s, int n) { string ans = ""; // Iterate the characters // of the string for (int i = 0; i < n; i++) { char ch = s[i]; int count = 0; string hex; // Iterate until S[i] is equal to ch while (i < n && s[i] == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal // representation hex = convertToHex(count); // Append the character ans += ch; // Append the characters frequency // in hexadecimal representation ans += hex; } // Reverse the obtained answer reverse(ans.begin(), ans.end()); // Return required answer return ans; } int main() { string s = "abc"; int n = s.size(); cout << encryptString(s, n); return 0; } C #include <stdio.h> #include <string.h> // Function to reverse a string void reverseStr(char *str) { int left = 0, right = strlen(str) - 1; while (left < right) { char temp = str[left]; str[left] = str[right]; str[right] = temp; left++; right--; } } // Function to convert Decimal to Hex void convertToHex(int num, char *hex) { int i = 0; while (num != 0) { int rem = num % 16; hex[i++] = (rem < 10) ? (rem + '0') : (rem - 10 + 'a'); num /= 16; } hex[i] = '\0'; reverseStr(hex); // Reverse the hex string } // Function to encrypt the string void encryptString(char *s, char *ans) { int n = strlen(s); int j = 0; for (int i = 0; i < n; i++) { char ch = s[i]; int count = 0; char hex[10]; // Count consecutive occurrences while (i < n && s[i] == ch) { count++; i++; } i--; // Adjust i after extra increment // Convert count to hexadecimal convertToHex(count, hex); // Append character ans[j++] = ch; // Append hexadecimal frequency for (int k = 0; hex[k] != '\0'; k++) { ans[j++] = hex[k]; } } ans[j] = '\0'; // Reverse the final encrypted string reverseStr(ans); } int main() { char s[] = "abc"; char ans[100]; encryptString(s, ans); printf("%s\n", ans); return 0; } Java import java.util.*; public class GfG{ // Function to convert Decimal to Hex static String convertToHex(int num) { StringBuilder temp = new StringBuilder(); while (num != 0) { int rem = num % 16; if (rem < 10) { temp.append((char)(rem + '0')); } else { temp.append((char)(rem - 10 + 'a')); } num = num / 16; } return temp.reverse().toString(); } // Function to encrypt the string static String encryptString(String s) { StringBuilder ans = new StringBuilder(); int n = s.length(); // Iterate the characters of the string for (int i = 0; i < n; i++) { char ch = s.charAt(i); int count = 0; // Iterate until S[i] is equal to ch while (i < n && s.charAt(i) == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal representation String hex = convertToHex(count); // Append the character ans.append(ch); // Append the characters frequency in hexadecimal representation ans.append(hex); } // Reverse the obtained answer return ans.reverse().toString(); } public static void main(String[] args) { String s = "abc"; System.out.println(encryptString(s)); } } Python def convert_to_hex(num): temp = "" while num != 0: rem = num % 16 if rem < 10: temp += chr(rem + 48) else: temp += chr(rem + 87) num //= 16 return temp[::-1] # Function to encrypt the string def encrypt_string(s): ans = "" n = len(s) # Iterate the characters of the string i = 0 while i < n: ch = s[i] count = 0 # Iterate until S[i] is equal to ch while i < n and s[i] == ch: # Update count and i count += 1 i += 1 # Convert count to hexadecimal representation hex_count = convert_to_hex(count) # Append the character ans += ch # Append the characters frequency in hexadecimal representation ans += hex_count # Reverse the obtained answer return ans[::-1] s = "abc" print(encrypt_string(s)) C# using System; using System.Text; class GfG{ // Function to convert Decimal to Hex static string ConvertToHex(int num) { StringBuilder temp = new StringBuilder(); while (num != 0) { int rem = num % 16; if (rem < 10) { temp.Append((char)(rem + '0')); } else { temp.Append((char)(rem - 10 + 'a')); } num /= 16; } char[] arr = temp.ToString().ToCharArray(); Array.Reverse(arr); return new string(arr); } // Function to encrypt the string static string EncryptString(string s) { StringBuilder ans = new StringBuilder(); int n = s.Length; // Iterate the characters of the string for (int i = 0; i < n; i++) { char ch = s[i]; int count = 0; // Iterate until S[i] is equal to ch while (i < n && s[i] == ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal representation string hex = ConvertToHex(count); // Append the character ans.Append(ch); // Append the characters frequency in hexadecimal representation ans.Append(hex); } // Reverse the obtained answer char[] result = ans.ToString().ToCharArray(); Array.Reverse(result); return new string(result); } static void Main() { string s = "abc"; Console.WriteLine(EncryptString(s)); } } JavaScript function convertToHex(num) { let temp = ''; while (num !== 0) { let rem = num % 16; if (rem < 10) { temp += String.fromCharCode(rem + 48); } else { temp += String.fromCharCode(rem + 87); } num = Math.floor(num / 16); } return temp.split('').reverse().join(''); } // Function to encrypt the string function encryptString(s) { let ans = ''; let n = s.length; // Iterate the characters of the string for (let i = 0; i < n; i++) { let ch = s[i]; let count = 0; // Iterate until S[i] is equal to ch while (i < n && s[i] === ch) { // Update count and i count++; i++; } // Decrement i by 1 i--; // Convert count to hexadecimal representation let hex = convertToHex(count); // Append the character ans += ch; // Append the characters frequency in hexadecimal representation ans += hex; } // Reverse the obtained answer return ans.split('').reverse().join(''); } let s = 'abc'; console.log(encryptString(s)); Output1c1b1aTime Complexity: O(n)Auxiliary Space: O(n) Comment More infoAdvertise with us Next Article Encrypt the string - 2 R rohan007 Follow Improve Article Tags : Strings Mathematical DSA Practice Tags : MathematicalStrings Similar Reads Program to Encrypt a String using ! and @ Given a string, the task is to encrypt this string using ! and @ symbols, alternatively. While encrypting the message the encrypted format must repeat the symbol as many times as the letter position in Alphabetical order. Examples: Input: string = "Ab" Output: !@@ Explanation: Position of 'A' in alp 11 min read Program to find the Encrypted word Given a string, the given string is an encrypted word, the task is to decrypt the given string to get the original word. Examples: Input: str = "abcd"Output: bdeeExplanation:a -> a + 1 -> bb -> b + 2 -> dc -> c + 2 -> ed -> d + 1 -> e Input: str = "xyz"Output: yaaExplanation: 4 min read Decrypt the Message string by using Key Phrases Given two strings Encrypted message and a key phrase. The message is encrypted using a key phrase. Find the original message by decrypting the encrypted message using a key phrase by following the below-mentioned rules: The number of words in the message and key phrase will always be equal.The first 15 min read Encrypt a string by repeating i-th character i times Given string str, the task is to encrypt the string with the given encryption algorithm. The 1st character of the string will be repeated once in the encrypted string, the 2nd character will be repeated twice, â¦, nth character will be repeated n times. Examples: Input: str = "geeks" Output: geeeeekk 4 min read Decrypt a string according to given rules Given encrypted string str, the task is to decrypt the given string when the encryption rules are as follows: Start with the first character of the original string.In every odd step, append the next character to it.In every even step, prepend the next character to the encrypted string so far.For exa 15+ min read Find k'th character of decrypted string | Set 1 Given an encoded string, where repetitions of substrings are represented as substring followed by count of substrings. For example, if encrypted string is "ab2cd2" and k=4 , so output will be 'b' because decrypted string is "ababcdcd" and 4th character is 'b'. Note: Frequency of encrypted substring 8 min read K-th lexicographical string of given length Given two integers N and K, the task is to find lexicographically Kth string of length N. If the number of possible strings of length N is less than K, print -1.Examples: Input: N = 3, K = 10 Output: "aaj" Explanation: The 10th string in the lexicographical order starting from "aaa" is "aaj".Input: 7 min read Find the valid integer from given String Given a string str of size N, containing ' ', '.', '-', '+', and ['0'-'9'], the task is to find the valid integer from this string.An integer is known as valid if follows the following rules: If str has leading whitespaces, ignore them.The first valid character should be '-', '+', or ['0'-'9']If no 8 min read Encrypt the given string with the following operations Given a string s, the task is to encrypt the string in the following way: If the frequency of current character is even, then increment current character by x.If the frequency of current character is odd, then decrement current character by x. Note: All the operations are circular that is adding 1 t 6 min read Encrypt a string into the Rovarspraket (The Robber Language) Given a string, task is to write a function translate() that will translate a text into "rovarspraket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. Examples: Input : this is funOutput : tothohisos isos fofunont is consonant then double 5 min read Like