HackerRank Problem: Encryption


Here is a problem involving splitting characters into a grid. I have a video explanation on the problem as well as the code commented for you in a nice way that hopefully is readable for you. Here is a link to the problem explanation and my code that passes tests for a solution.


import java.util.Scanner;

public class Solution {

	public static void main(String[] args) {
		// create our scanner object
		Scanner in = new Scanner(System.in);

		// read in next line as a string
		String inLine = in.nextLine();

		// remove the whitespace from it
		inLine = inLine.trim();

		// get the length of the string
		int L = inLine.length();

		// start with the ceiling for the columns
		int columns = (int) Math.ceil(Math.sqrt(L));

		// start with the floor for the rows
		int rows = (int) Math.floor(Math.sqrt(L));

		// if we need another row to fit the string in add it here
		if (columns * rows < L) {

		// will hold the unencrypted string into a grid
		char[][] message = new char[rows][columns];

		// get the string as a list of chars
		char[] chars = inLine.toCharArray();

		// populate the grid with the characters
		int index = 0;
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				if (index < chars.length) {
					message[i][j] = chars[index];

		// build the string from row and column
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < columns; i++) {
			for (int j = 0; j < rows; j++) {
				char temp = message[j][i];
				if (temp != 0)
					sb.append("" + message[j][i]);
			sb.append(" ");



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers