- Practice
- Algorithms
- Implementation
- Encryption
- Discussions

# Encryption

# Encryption

Schuetzl + 35 comments I see a lot of people in the discussions are using a 2d array, did anyone else solve it by simply iterating through the input string? Is there a difference in efficiency? All of my submissions were 0.09s of quicker (using Java). Is there a better way to do it?

dan_mar_042 + 0 comments 0s in every case without using 2d array (c++). It was a great hint! Thanks!

xXGoziXx + 0 comments I did it like this and got all submissions 0.06. Great hint! :D https://www.hackerrank.com/challenges/encryption/submissions/code/16330491

cangktvn + 3 comments I have the same approach with you, why everybody have to do it the hard way?

`int main(){ string s; cin >> s; auto n = s.size(); int row = round(sqrt(n)); int column; if (row >= sqrt(n)) column = row; else column = row + 1; for(int j=0;j<column;++j) { for(int i=j; i<n;i+=column)cout << s[i]; cout << ' '; } return 0; }`

vidushig2 + 1 comment int main(){ char s[10000]; cin >> s; int l = strlen(s); int rows = floor(sqrt(l)); int columns = ceil(sqrt(l)); if((rows*columns)

`return 0;`

}

please tell why test case 1 and 2 are failing.

slash331erock + 0 comments same problem my output and expected output is exactly the same still it is showing wrong answer

ganeshmukesh111 + 7 comments how you manage to skip spaces from orignal string (s)?

beshm + 1 comment if you are using java, you could use trim method.

vyavaharkardeve1 + 0 comments trim() removes only the spaces before and after the string.

beastieric + 0 comments There are no spaces in the original string.

knivendha + 0 comments usre replace()

s=s.replace(" ", "");

naeemalicious + 0 comments s.replaceAll(" ", "");

tthrash + 0 comments [deleted]tthrash + 0 comments s = s.replaceAll("\\s+","");

vishal_nimavat + 0 comments in java string.replaceAll("\\s+", "");

tarabahadur_tha1 + 1 comment Could you please explain the logic behind determining the noOfRows and noOfCols

vishal_nimavat + 0 comments in java

`final double length = string.length(); int row = (int) Math.floor(Math.sqrt(length)); final int column = (int) Math.ceil(Math.sqrt(length));`

Kthompso + 1 comment Sure:

`#!/bin/python3 import sys from math import ceil, sqrt s = input().strip() c = ceil(sqrt(len(s))) print(' '.join(map(lambda x: s[x::c], range(c))))`

Anyone see a way to turn this into a 1-liner without calculating c twice?

qu4ku + 2 comments but you will need s in the separate line using this method

import sys from math import ceil, sqrt s=input().strip() exec("print(' '.join(map(lambda x: s[x::{0}], range({0}))))".format(ceil(sqrt(len(s)))))

FilipF + 2 comments Hi! Your improvement got me thinking, how to combine those statements into one, and this seems to work? Rather than wrap your statement inside of another string and format, I wrapped the exec with a lambda, and applied it to the input. There's a copy online to play with.

from math import ceil, sqrt (lambda s: exec("print(' '.join(map(lambda x: \"{1}\"[x::{0}], range({0}))))".format(ceil(sqrt(len(s))),s)))(input().strip())

I also tried to use

`"+s+"`

instead of`{1}`

and`,s`

, but both use five characters, so there's not a big improvement.## =====

That got me thinking though... what about using another nested lambda instead of format and exec? I tweaked it again, and got a new version. Cool. But what about the import statement? With a little syntactic trickery, we can turn

`sqrt`

into`n**0.5`

, and I learned you can replicate the`ceil`

function by doing`-(-n//1)`

instead. Finally! A single statement.# This is all one line, I swear. Only three spaces total. (lambda s:(lambda r:print(' '.join(map(lambda x:s[x::r],range(r)))))(int(-(-(len(s)**0.5)//1))))(input().strip())

# Here's the statement blown up to make things clearer. Maybe. (lambda s: (lambda r: print( ' '.join( map( lambda x: s[x::r], range(r) ) ) ) ) ( int(-(-(len(s)**0.5)//1)) ) ) ( input().strip() )

# And here's that second parameter, blown up too. int( -( -( len(s)**0.5 ) // 1 ) )

I hope some one gets a kick out of that like I did. ;) It's not great code golf, but it is satisfying to put it all together on one line. Especially since it's, well, python, hehe.

### References: Python grammar, Ceiling function.

dangerDon + 0 comments This is what i am searching for, One liner

You have just teach me a new way to make more one liners :)

Dragg + 1 comment this is awesome! :D

ganeshmukesh111 + 0 comments thanks

mridula_bvs + 0 comments Could anyone please explain this line in detail?

exec("print(' '.join(map(lambda x: s[x::{0}], range({0}))))".format(ceil(sqrt(len(s)))))

qu4ku + 1 comment once you said it it actually seems to be stupid to solve it with arrays :D

MichaelDsa + 0 comments Yeah, the hint was great! :D

Epshita + 0 comments int main() { string s;

`cin >> s; auto n = s.size(); int row, column; row = = round(sqrt(n)); if( row >= sqrt(n) ) column = row; else column = row + 1; for( int j = 0; j < column; j++ ) { for( int i = j; i < n; i += column ) cout << s[i]; cout << ' '; }`

}

Sure, I did it this way.

shouki + 1 comment 0.02s or quicker in C#. Didn't even bother with the grid approach but it's got to be slower because of the extra iteration and memory writes. The additional space requirements of allocating a grid also impacts overall performance. And if we're talking about cryptography here, you want it to be as performant as possible.

AndreaR + 1 comment yes, C# .02s, no array, using StringBuilder

KUTlime + 0 comments A C# solution without anything ;)

using System; class Solution { static void Main(String[] args) { string s = Console.ReadLine(); Int32 Lmax = (Int32)Math.Ceiling(Math.Sqrt(s.Length)); for(Int32 i = 0; i < Lmax; i++){ Console.Write(s[i]); for(Int32 j = i+Lmax; j < s.Length; j+=Lmax){Console.Write(s[j]);} Console.Write(" "); } } }

mk9440 + 1 comment public class Solution { public static void main(String[] args) { Scanner in=new Scanner(System.in); String s=in.next(); double row=Math.floor(Math.pow(s.length(),0.5)); double col=Math.ceil(Math.pow(s.length(),0.5)); String ans =""; for(int i=0;i<col;i++){ int j=0; while(i+j<s.length()){ ans=ans+s.substring(i+j,i+j+1); j=(int) (j+col);} ans=ans+" ";} System.out.println(ans);}}

naeemalicious + 0 comments You forgot to remove the spaces between the words.

lifekills + 0 comments Honestly, using a 2D array barely even crossed my mind. I spent too long making binary trees in C++ to be afraid of some simple index math.

0.1 seconds in Java on every test.

ashsingh1 + 1 comment sometimes people overthink, I was going with the array approach then I saw this, thanks for the hint. here is my implementation in java

static void message(String string){ int row = (int)Math.floor(Math.sqrt(string.length())); int column = (int)Math.ceil(Math.sqrt(string.length())); if(row * column < string.length()) row = column; for(int i = 0; i < column; i++){ for(int j = i; j < string.length(); j = j + column ){ System.out.print(string.charAt(j)); } System.out.print(" "); } }

james_kurakula + 2 comments what is the use of this line in your code.....

if(row * column < string.length()) row = column;

zmingxie + 0 comments I don't see why this line is needed either...

_Nitin_Verma_ + 0 comments take case of string length=8 we will have row=2,col=3 condition 1 of ques states that row*col should be greater then length (which is false here) so take extreme case(i.e row=column)

meyer_greg_pro + 1 comment How can you the computation time?

lifekills + 0 comments The submissions tab then View Results

avasilev + 0 comments `std::string sentence; getline(cin, sentence); int length = sentence.length(), columns = ceil(sqrt(length)), rows = floor(sqrt(length)); if(rows*columns < length) rows = columns; for(int i = 0; i < columns; ++i) { for(int j = 0; j < rows; ++j) { if(i + j * columns < length) cout << sentence[i + j * columns]; } cout << ' '; }`

nagavenkatara + 0 comments Thank you for the hint. O(s.Length)

string s = Console.ReadLine().Trim(); var rowLength = (int)Math.Sqrt(s.Length)+1; if(Math.Sqrt(s.Length)-(int)Math.Sqrt(s.Length) == 0) rowLength = (int)Math.Sqrt(s.Length); for(int index = 0; index < rowLength;index++){ var verticalStrip = string.Empty; var k = index; while( k < s.Length){ verticalStrip += s[k]; k += rowLength; } Console.Write(verticalStrip+ " "); }

ryanfehr18 + 0 comments A solution to this question has been provided on the HackerRank solution repo! If you are interested in solutions to HackerRank problems as well as gaining some experience working on an GitHub open source project, check out HackerRank Solutions. We are working to make a repository of solutions to every HackerRank question.

AGRN96 + 1 comment Did it in this manner and got 0s in all test cases. https://www.hackerrank.com/challenges/encryption/forum/comments/280014

dangerDon + 0 comments Ya, I did the same just in python, you can also use ceil here

int coloumn = sqrt(length);

to remove this

if(row * coloumn < length){ coloumn+=1; }

i did that

Coder_AMiT + 0 comments I did :)

s = list(input().strip()) L = len(s) row = math.floor(L**(1/2)) col = math.ceil(L**(1/2)) for i in range(col): x = 0 while True: try: print(s[i+x],end='') x+= col except: break print(' ',end='')

Rys23 + 1 comment I did it this way

int main(){ char* s = (char *)malloc(10240 * sizeof(char)); scanf("%s",s); int len = strlen(s); int columns = ceil(sqrt(len)); for(int i = 0; i < columns; i++) { for(int j = i; j < len; j += columns) { printf("%c", s[j]); } printf(" "); } return 0; }

all of the test cases take 0s

yarpit90 + 4 comments I did it this way, simlar to what you have done

But its showing wrong answer, even though my output is same as was expected, same is happening for testcase1 as well, "feedthedog".

vkumarjjp123 + 1 comment that exactly what is happening with me too...

CometLi + 0 comments To solve this problem, just stop outputting when it reaches the length of the string. Hope it will help.

mrunalidhenge99 + 2 comments same issue. hv u solve it?

CometLi + 0 comments [deleted]snoisingla + 0 comments This happens beacuse you are adding undefined character into the string. If a char in the array is not set it will be undefined. When you are building the string don't add those charcters which are not set.

sandyboy + 0 comments without 2d array

#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int r,c; string s; cin>>s; int l=s.length(); r=floor(sqrt(l)); c=ceil(sqrt(l)); if((r*c)<l) r++; for(int i=0;i<c;i++) { for(int j=i;j<l;j+=c) { cout<<s[j]; } cout<<" "; } return 0; }

praheja661 + 1 comment How are checking the running time of your solution?

vishu006 + 1 comment If you are asking about running time in general, reading about Time Complexity will definitely help.

If this is related to time that test cases take for running your code, just hover on them and you would see their respective time.

Hope this helps

praheja661 + 0 comments This is related to test case run time. I tried hovering over test cases, but i am unable to see the run time of that case.

vishu006 + 0 comments Hey that was a great tip!! Passed all test cases in 0s in Python.

Check it out https://www.hackerrank.com/challenges/encryption/submissions/code/50674389

ahmad_abu_sheikh + 0 comments yep, 2D array is very unnecessary.

ravikumar_2402_1 + 0 comments # include

# include

# include

# include

# include

using namespace std;

int main(){ string s; cin >> s; int count=0; int l=s.length(); int rows=floor(sqrt(l)); int col=ceil(sqrt(l)); if(rows*col

`for(int i=0;i<rows&&m<l;i++){ cout<<s[m]; count++; m=m+col;}k++;n++; if(count<l) cout<<" ";} return 0;`

}

y_aitloutou + 1 comment how do you check the time per subimssion ?

CometLi + 0 comments Sorry I don't know how to do this either. :( If you figure it out could you please let me know too? Thx a lot.

smitparekh1995 + 0 comments [deleted]smitparekh1995 + 0 comments [deleted]will_whyang + 0 comments Don't need to use a 2d array.

package main import ( "fmt" "math" ) func main() { var text string fmt.Scan(&text) l := len(text) m := math.Sqrt(float64(l)) lower := int(math.Floor(m)) upper := int(math.Ceil(m)) // upper * upper must be >= l, so it safe to do following. Or just simply do one lower += 1 for lower * upper < l { lower += 1 } index := 0 for i := 0; i < upper; i++ { for j := 0; j < lower; j++ { index = i + j * upper if index >= l { break } fmt.Printf("%c", text[index]) } fmt.Printf(" ") } }

kirticism + 0 comments Why use 2D array when it can be done in single iteration...

void encryption(string s) { int row=ceil(sqrt(s.length())); int column=floor(sqrt(s.length())); for(int i=0;i<row;i++) { for(int j=i;j<s.length();j=j+row) cout<<s[j]; cout<<" "; } }

_dec0der_ + 0 comments int n=str.length(); int col=ceil(sqrt(n)); for(int i=0;i<col;i++) { for(int j=0;i+j<n;j+=col) { cout<<str[i+j]; } cout<<" "; }

sahulrajhansa + 0 comments *My code without using two dimensional array.*import java.io.

*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*;public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int hop = (int)Math.ceil(Math.sqrt(s.length())); int i = 0, j = 1,count = 0; while ( j <= hop ){ while( i < s.length()){ System.out.print(s.charAt(i)); i+=hop; } System.out.print(" "); i = j; j++; } in.close(); } }

JJJason + 0 comments My Python3 solution. Do not have to use 2-d array.

#!/bin/python3 import sys s = input().strip() rows = int(len(s) ** 0.5) if rows < len(s) ** 0.5: columns = rows + 1 else: columns = rows for i in range(columns): print(s[i::columns], end = ' ')

rahulkalita8 + 0 comments [deleted]rahulkalita8 + 0 comments Without any 2D array.

void encryption(string s) { int n = s.length(); int x = floor(sqrt(n)); int y = ceil(sqrt(n)); int k=0; if((x*y)<n) x++; for(int i=0; i<y; i++){ for(int j=0; j<x; j++){ k=i+(j*y); if(s[k]!='\0') cout<<s[k]; } cout<<" "; } }

d_kunal96 + 0 comments This worked for me..

int rows = 0, cols = 0, i, j = 0; StringBuffer sb = new StringBuffer();

`//rows = (int)Math.floor(Math.pow(s.length(), 0.5)); cols = (int)Math.ceil(Math.pow(s.length(), 0.5)); for(i = 0; i < cols; i++) { for(j = i; j < s.length(); j += cols) { sb.append(s.charAt(j)); } sb.append(" "); } return sb.toString();`

aniketnath283 + 0 comments solution without using 2d array https://www.hackerrank.com/challenges/encryption/forum/comments/483060

alimobasshir21 + 1 comment you mean like this '#include

using namespace std;

int main() {

`string s; getline(cin, s); int length=s.length(); int ul=0,ll=0; for(int i=1; i<=9; i++) { if(i*i>length) { ul=i; ll=i-1; break; } else if(i*i==length) { ul=i; ll=i; break; } } //cout<<ul<<" "<<ll<<endl; int i=0; while(i<ul && i<s.length()) { int j=i; while(j<s.length()) { cout<<s[j]; j=j+ul; //cout<<j; } cout<<" "; i=i+1; } return 0;`

}

aniketnath283 + 0 comments Yea something like that. The main logic is first find out the square root of length of the string. Then round of the square root value. Then take a loop upto the round of value and take an inner loop where you will append the result characters by jumping the round of value. Eg: hihowareyou. This string has 11 characters. Now its square root is 3.3166.... now if we round of this values are it will be 4. So the maximum no of append will be 4

saurabh_jasper + 16 comments why is this happening?

aditya_avs + 1 comment It may be due to trailing spaces. Add a check for iter less than length, print only then. You might be using a direct cout.

magician03 + 0 comments [deleted]

saurabh_jasper + 0 comments Sir,I took care about trailing spaces, but irrespective of no. of trailing spaces result was same, ie.it passed few test cases but failed is some.

akankshakunwar81 + 0 comments have you solved this ??? Iam getting the same problem

s_w_zzang + 0 comments Have you resolved? Same problem for me. I also checked trailing space

magician03 + 1 comment same issue for me, did u solve it ?

avkumar_19 + 0 comments the problem is you are printing '\0',try applying an if condition and print only if it's not '\0';

vinesh9876 + 0 comments same issue here

abhinavdayal + 1 comment It is because you need to ensure that rows*cols >= Lemgth of string.

We need to keep rows <= cols so we keep rows as the floor of squareroot and cols as the ceiling.

now if rows*cols < L then you need to add another row to make things fit.

vinesh9876 + 0 comments why dose it matter if I'm getting the same output

louisehmbc + 1 comment I'm having the same problem, did you solve it? What's stranger is that the first testcase doesn't mind whether or not I add a trailing space at the end, but the second two don't work even when they're identical (no trailing whitespace).

int main(){ string s; cin >> s; // Remove spaces from string for (auto it = s.begin(); it != s.end();){ if (*it == ' ') s.erase(it); else ++it; } // Caculate grid sizes int floor = sqrt(s.size()); int ceiling = sqrt(s.size()) + 1; if (floor * ceiling < s.size()) (floor < ceiling)? floor += 1 : ceiling += 1; // Create grid vector<string> encrypted(ceiling); for (int i = 0; i < floor; ++i) { for (int j = 0; j < ceiling; ++j) { encrypted[j] += s[j + i * ceiling]; } } // Ugly output method to remove trailing spaces for (int i = 0; i < encrypted.size(); ++i) { std::cout << encrypted[i]; if (i < encrypted.size()-1) std::cout << " "; } std::cout << std::endl; return 0; }

vinesh9876 + 0 comments yeah its not working

amrata_kasture + 0 comments I am facing same issue for test cases 1,3,6. I downloaded cases and output is correct but still test cases are failing. Anyone figured out cause?

sudhar287 + 0 comments After proceesing the input, my 2D matrix looked like this. When printing it column wise, ensure that

*cout*is not executed when a emply space is encountered i.e*'\0*'mails4ipiyush + 0 comments I am also facing the same issue. I even trimmed the trailing spaces. Still its showing wrong answer.

khadar111 + 0 comments for(int i=0;i

svfarande + 0 comments Same problem :(

a65b4139 + 1 comment I am having the exact same problem.

This is my code:

import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String message = in.nextLine(); String ciphertext = encrypt(message); System.out.println(ciphertext); } private static char[][] buildGrid(String message, int rows, int columns) { char[][] grid = new char[rows][columns]; char[] chars = message.toCharArray(); int row; int column; for (int i = 0; i < chars.length; i++) { row = i / columns; column = i % columns; grid[row][column] = chars[i]; } return grid; } private static String encrypt(String message) { int length = message.length(); double lengthSqrt = Math.sqrt(length); int rows = (int) Math.floor(lengthSqrt); int columns = (int) Math.ceil(lengthSqrt); rows = (rows * columns < length) ? columns : rows; char[][] grid = buildGrid(message, rows, columns); StringJoiner sj = new StringJoiner(" "); StringBuilder sb = new StringBuilder(); int charsTotal = 0; for (int column = 0; column < columns; column++) { sb.setLength(0); for (int row = 0; row < rows; row++) { if (charsTotal <= length) { sb.append(grid[row][column]); charsTotal++; } } sj.add(sb.toString()); } return sj.toString(); } }

Anutrix + 0 comments /** * * @author Anutrix */ import java.io.*; import java.util.*; public class Encrytion { public static void main(String[] args) { Scanner in = new Scanner(System.in); String msg = in.nextLine(); int n = msg.length(); int y = (int) Math.ceil(Math.sqrt(n)); for(int i=0; i<y; i++){ int pos = i; while(pos<n){ System.out.print(msg.charAt(pos)); pos +=y; } System.out.print(" "); } } }

Hows this?

blazefrostrider + 0 comments I had the same mistake and i solved it by checking whether it is a letter before printing it . You can identify your extra spaces by printing '#' or anything else instead of a space . Also , the row calculation is wrong when applied to second test case . I calculated row by Ceil(len of input / col)

kemalsreenivas38 + 0 comments Check if the character is null before printing.

sujithvm + 12 comments This is the solution i submitted. Can anyone please tell me why ideone is giving correct answer for TestCase 1 and Hackerrank is giving a different answer. No difference in code

`TestCase : feedthedog Ideone output : fto ehg ee dd Hackerrank editor output : fto ehg ee`

visrahane + 1 comment take care of the space(blank) and it works.

manavkothari + 2 comments how to solve space and null problem in c?

sachin_dandavati + 0 comments First initialise it with null or ' '. Then do function, it will work

srikanthk555 + 0 comments use isprint function before printing characters to stdin that would be useful in checking non printable characters like space etc,,

karantirthani + 1 comment i am facing the same problem

etayluz + 5 comments Here's one way:

`int main(){ char* s = (char *)malloc(10240 * sizeof(char)); scanf("%s",s); int len = strlen(s); int rows = floor(sqrt(len)); int cols = ceil(sqrt(len)); if (rows * cols < len) { rows = cols; } for (int c = 0; c < cols; c++) { for (int r = 0; r < rows; r++) { int idx = c + r * cols; if (idx < len) { printf("%c", s[idx]); } } printf(" "); } return 0; }`

GowthamSiddarth + 0 comments why did you allocate 10240 specifically?

highly_rated + 0 comments [deleted]vidushig2 + 1 comment int main(){ char s[10000]; cin >> s; int l = strlen(s); int rows = floor(sqrt(l)); int columns = ceil(sqrt(l)); if((rows*columns)

`return 0;`

}

test case 1 and 2 are failing.Please tell why

shahpujan1992 + 0 comments Input for 1st test case is- feedthedog Output - fto ehg ee dd

pp43076 + 2 comments But the question says that if two or more grids satisfy the condition for number of rows and columns, then choose the one with min rows(n) x columns(m).

The above code does not take minimum n x m.

Example : chillout It gives different answers for 2 x 4 and 3 x 3. And 2 x 4 has min n x m.

Testcase giving wroung output

ankit_mahajan_19 + 2 comments i agree with this statement. it should be 2*4 = 8 instead of 3*3 = 9.

lausanne_man + 1 comment Yes. For some L the constraint can't be met. 8 is one example: sqrt(8) ~= 2.8, so a 3x3 grid violates the constraint, and 2x3 which meets it is too small for 8 elements.

Another test where L = 3 has the same problem.

bearhack + 0 comments The whole point to constraining the grid parameters is to make sure that they are within 1 unit of each other. Thus, 2x4 is outside of the constraints of floor(sqrt(8)) = 2 and ceil(sqrt(8)) = 3 because 4 is greater than 3. However, because 2x3 is too small to use 8 units, you

*can*use 3x3 and still fit within the constraints. It's a really roundabout way of just saying keep your grid parameters within 1 unit of each other.

Aashish_J + 0 comments Column cannot be 4 (should be <= 3)

adi341875 + 0 comments According to constraint n,m should lie between the floor and ceil. In this case: floor = 2; ceil =3; For minimum area, 2*4 should be choosen but it violates the constraints. i.e. column >ceil; So we choose 3*3 to satisfy the condition.

Happy Coding :)

pankaj_mittal372 + 0 comments this code executed all the test cases but i think this code has some fault.....let say len=7 so we will get rows=2 and cols=3 rows*cols

ScottDuane + 4 comments Same problem here. My compiler outputs "fto ehg ee dd" for Sample #2 but Hackerrank outputs "fto ehg ee". Same thing with Test case #6, which is one of the test cases that Hackerrank graded "wrong". Here's my code:

https://www.hackerrank.com/challenges/encryption/submissions/code/11082541

areyoukiddingme + 0 comments similar issue here. http://ideone.com/PZaK34

StevoTVR + 0 comments I think your problem is on line 40. Everything needs to be flipped.

MetonymyQT + 0 comments Because you are printing unpritable characters. Check if the character is printable, if it is a letter.

lausanne_man + 0 comments It appears Sample #2 has been fixed.

thugwaffle + 0 comments I have the same problem. Spent a decent amount of time trying to find the bug, but I put it in Ideone and got the right answer.

Tatparya + 0 comments I had the same problem. You are basically going out of bounds when reading the string ( which is a memory error ) The HackerRank compiler just stops executing the code when you go out of bounds. Suggestion : Check for boundary conditions

alexgbelov + 0 comments I'm guessing because you never initialized the default value in arr, so you don't know if its going to be a space character. So, if (arr[r][c] != ' ') is useless.

shubham_sharma14 + 0 comments if (arr=='\0'); break

st4rk03 + 0 comments use this :----->

if(grid[j][i]==(char) 0){ break; }

TheRevenant + 0 comments Ignore the '\0' characters when displaying the output.

rajendra + 0 comments just add the condition if you are working in java char[i][j]!=0 since a emty cell in char array is 0 in java, here is my solution for that https://www.hackerrank.com/challenges/encryption/submissions/code/16072054

shahpujan1992 + 0 comments In this scenario if u used floor and ceil method then it gives row=2,col=3.. Actually to store that much data we need row=2,col=4.. So I done it and directly prints the characters without storing in the 2D array..

mserranom + 0 comments Same issue here, correct results are marked as failures:

import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int[] gridSize = findMinimumArea(s.length()); char[][] grid = new char[gridSize[0]][gridSize[1]]; int cursor = 0; for(int row = 0; row < gridSize[0]; row++) { for(int col = 0; col < gridSize[1]; col++) { if(cursor >= s.length()) { break; } else { grid[row][col] = s.charAt(cursor); cursor++; } } } String ans = ""; for(int col = 0; col < gridSize[1]; col++) { for(int row = 0; row < gridSize[0]; row++) { ans += grid[row][col]; } ans += " "; } System.out.println(ans.trim()); } // [rows, cols] private static int[] findMinimumArea(int n) { int min = (int)Math.round(Math.floor(Math.sqrt(n))); int max = (int)Math.ceil(Math.sqrt(n)); for(int row = min; row <= max; row++) { for(int col = row; col <= max; col++) { if(row * col >= n) { return new int[]{row,col}; } } } throw new Error("shouldn't get here : " + n); } }

samar5yadav + 2 comments `import math s=input() sm=s.replace(" ","") r=math.floor(math.sqrt(len(sm))) c=math.ceil(math.sqrt(len(sm))) for i in range(c): print(sm[i::c],end=" ")`

short and sweet. that's why you gotta love python

hamza_emra + 1 comment could you please explain the for loop part? specialy sm[i::c] part

samar5yadav + 1 comment okay. lets take example that is given in question.

input: if man was meant to stay on the ground god would have given us roots

sm=ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots

now we know the number of rows(r=7) and columns(c=8)

what sm[i::c] means is start from sm[i] to end of sm print every character with indices i,i+c,i+2c,i+3c... till the end. After that add " ". so let's take i=0 for example that means print characters with indices 0,8,16,24,32,40,48 (till you reach the end of sm). so here it is "imtgdvs" then add " ". Same goes on on till you are done with all the columns.

i hope this helps!

hamza_emra + 0 comments It helped alot thank you so much

Being_human + 0 comments NICE AND SORT

StopAsh12 + 1 comment hey what does poosible square with the minimum have to do with this,as i think there are going to be only two square.ceiling and floor of an integer are going to be two consecutive number,following the constraints one can be increased and the other can only be decreased.so there are going to be only 2 square.The language of the question could have been easy to understand.

shashank21jHackerRank Admin + 1 comment Actually square is unique, there is no question of max/min.

Will change the statementshubham_sharma14 + 3 comments /*If multiple grids satisfy the above conditions, choose the one with the minimum area, i.e. rowsÃ—columns. */

in test case "chillout" they have taken 3*3 but I want to take 2*4 and when i take 2*4 they show wrong answer!!!!!!

shubham_sharma14 + 2 comments leave it.

i got it

briandignan + 1 comment So what is the correct output here? In the case of "chillout", shouldn't it be 2*4 (area 8) and not 3*3 (area 9)? 2*4 meets the constraints. It's got more columns than rows, and the number of rows is greater/equalto floor(sqrt(L))

alkis + 1 comment You are right about the lower limit. What about the upper limit?

briandignan + 0 comments Ahh right. I forgot about that part. Thanks!

manthan19 + 0 comments coz 4 is greater than ceil of sqrt(8)

mish_16 + 1 comment in test case "chillout" my output and expected output are same. still they are showing wrong answer..help me out shubham_sir.. and same is the case with feedthedog test case.

shubham_sharma14 + 0 comments /*If multiple grids satisfy the above conditions, choose the one with the minimum area, i.e. rowsÃ—columns. */

also take care of ceil and floor function

Rajatsha90271 + 2 comments My first test case is getting passed but the other two are not ,while my output and "expected output " are same. Help

mendelAsked to answer + 1 comment I would like to help you, but I can't because I don't know what you are doing.

I just resubmitted my solution and it is still accepted, so the system seems to be working correctly.

Rajatsha90271 + 1 comment /

*Following is my code ,,,, Please go though it,,,*/# include

# include

# include

# include

int main() {

`int i = 0 , k = 0 , j , l , r , n = 0; char ch; char temp[101]; char str[101]; char res[101][101]; while(ch != EOF) { ch = getchar(); temp[i++] = ch; } temp[i] = '\0'; for(i = 0 ; temp[i] != '\0' ; i++) { if(temp[i] == ' ') continue; str[k++]= temp[i]; } str[k] = '\0'; l = ceil(sqrt(k)); r = floor(sqrt(k)); //if(l * r == k - 1) //{ for(i = 0 ; i < r ; i++) { for(j = 0 ; j < l ; j++) { res[i][j] = str[n++]; } } for(i = 0 ; i < l; i++) { for(j = 0 ; j < r ; j++) { printf("%c" , res[j][i]); } printf(" "); } return 0; //} /*else { }*/`

}

mendel + 1 comment l = ceil(sqrt(k)); r = floor(sqrt(k));

This code is too simple and does not reflect the problem statement properly.

It is possible (but not necessary) to create a solution that does not compute r at all.

roryneil + 0 comments I didn't use floor at all. x,y = 0,ceil, then take chunks of s[x:y], adding ceil to x and y each time. But as someone mentioned above, you don't have to create this matrix, since the string would be s[0] + s[ceil] + s[2*ceil] etc., add a space, then do it again starting at s[1]+s[1+ceil], etc.

saibhaskar1 + 1 comment i too have the same problem ... please let me know if you find some mistake

mendel + 1 comment Please check the last letters on the expected output - are they really the same?

saibhaskar1 + 1 comment thanks ..there was a difference in spaces

vinesh9876 + 0 comments trailing space?

neeraj_deshpand1 + 3 comments I am getting exact same answer still it is saying Wrong answer in compiler message. I double checked for spaces before and after the answer but there is no difference. For first testcase it is accepting the answer but for 2nd and 3rd testcase it is saying Wrong answer. What can be the probable reason?

ysrisumanth + 0 comments same problem here

cesarla + 0 comments Actually the problem in my case is that the string serialization was ok but it was producing the wrong equals since I was adding the null character '\u0000' to the result.

iamshardul + 0 comments What changes are suggested in this code to improve time complexity? https://www.hackerrank.com/challenges/encryption/submissions/code/15000772 Thank you!

Aabhas99 + 0 comments *SOLUTION TO THE PROBLEM:**First , try your level best and then , IF you have any problem :**You can visit the link below to have the solution:*https://github.com/Aabhas99/HackerRank-Solution-To-Algorithms

*GOOD LUCK!!ðŸ˜Š*

_Trojan_Horse + 0 comments Explain sample test case 3? How can row =2 and col=4 in this test case?

Sort 564 Discussions, By:

Please Login in order to post a comment