Open In App

Encrypt the string - 2

Last Updated : 25 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 1c1b1a
Explanation: 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));

Output
1c1b1a

Time Complexity: O(n)
Auxiliary Space: O(n)


Next Article
Article Tags :
Practice Tags :

Similar Reads