Java encryption decryption HackerRank solution

published on 28 May 2024

The encryption decryption problem on HackerRank involves removing spaces from a given text, arranging the characters into a grid based on the square root of the text's length, and then reading the grid column by column to create an encrypted message. The grid dimensions are chosen to minimize the area while ensuring the number of rows is less than or equal to the columns.

In this post, we will demonstrate how our tool, HackerRankGPT, can give you the encryption decryption hackerrank solution in Java, and help you succeed in your HackerRank coding interview.

HackerRankGPT, powered by GPT-4, provides real-time, undetectable support for solving coding problems during your HackerRank interviews 👈

Here is the Java encryption decryption HackerRank solution using HackerRankGPT:

Encryption decryption HackerRank problem
Encryption decryption HackerRank problem

Encryption decryption HackerRank solution:

public static String encryption(String s) {
        // Remove spaces from the string
        s = s.replaceAll("\\s", "");
        int length = s.length();

        // Determine grid dimensions
        int floor = (int) Math.floor(Math.sqrt(length));
        int ceil = (int) Math.ceil(Math.sqrt(length));

        // Adjust rows and columns based on calculated dimensions
        int rows = floor;
        int columns = ceil;
        if (rows * columns < length) {
            if (ceil * ceil >= length) {
                rows = ceil;
                columns = ceil;
            } else if (ceil * floor >= length) {
                rows = ceil;
            }
        }

        StringBuilder encrypted = new StringBuilder();
        // Construct column-wise encryption
        for (int col = 0; col < columns; col++) {
            for (int row = 0; row < rows; row++) {
                int index = row * columns + col;
                if (index < length) {
                    encrypted.append(s.charAt(index));
                }
            }
            if (col < columns - 1) {
                encrypted.append(' ');
            }
        }

        return encrypted.toString();
    }

}


When we use this code, we pass all HackerRank tests:

Java encryption decryption HackerRank solution in Java using HackerRankGPT
Java encryption decryption HackerRank solution in Java using HackerRankGPT

If you have a HackerRank coding test soon, you can use HackerRankGPT to your advantage. It will undetectably assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job.

Use HackerRankGPT. 
Don't fall behind.

Read more

Make your website with
Unicorn Platform Badge icon