• + 0 comments

    Beats 100% Java O(N), T(1)

     public static String caesarCipher(String s, int k) {
            char[] arr = "abcdefghijklmnopqrstuvwxyz".toCharArray(); // T(26) - > T(1)
            k %= arr.length;
              
            reverse(arr, 0, k - 1);
            reverse(arr, k, arr.length - 1 );
            reverse(arr, 0, arr.length - 1);
            //O(N)
            StringBuilder sb = new StringBuilder();
            //[c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, a, b]
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if (Character.isLetter(ch)) {
                    if (Character.isLowerCase(ch)) {
                        int index = ch - 'a';
                        sb.append(arr[index]);
                    } else {
                        int index = Character.toLowerCase(ch) - 'a';
                        sb.append(Character.toUpperCase(arr[index]));
                    }
                } else {
                    sb.append(ch);
                }
            }
    
            return sb.toString();
        }
        
        static void reverse(char[] arr, int start, int end) {
            while (start < end) {
                swap(arr, start, end);
                start++;
                end--;
            }
        }
        
        static void swap(char[] arr, int start, int end) {
            char temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
        }