• + 0 comments

    My Java solution with o(n * m) time complexity and o(n) space complexity:

    public static String encryption(String s) {
            // remove the spaces from the string
            s.replaceAll(" ", "");
            
            // get the len of the string
            int length = s.length();
            
            // set x equal to floor of sqrt of len
            int x = (int) Math.floor(Math.sqrt(length));
            
            // set y equal to ceil of sqrt of len
            int y = (int) Math.ceil(Math.sqrt(length));
            if(x * y < length) x += 1;
            
            // print each char of the string x by y
            StringBuilder encryptedString = new StringBuilder();
            for(int i = 0; i < y; i++){
                for(int j = 0; j < x; j++){
                    int idx = j * y + i;
                    if(idx < length)
                        encryptedString.append(s.charAt(idx));
                }
                encryptedString.append(' '); //line break
            }
            return encryptedString.toString();
        }