• + 0 comments

    simple javascript solution with time and space complexity both O(n):

    var caesarCipher = function (s, k) {
        let strArr = [];
        for (const ch of s) {
            if (!/^[a-zA-Z]$/.test(ch)) {
                strArr.push(ch);
            } else {
                strArr.push(rotatedChar(ch, k));
            }
    
        }
        return strArr.join('');
    }
    
    function rotatedChar(char, k) {
        let smallLetters = "abcdefghijklmnopqrstuvwxyz"
        let capitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        if (smallLetters.includes(char)) {
            let index = smallLetters.indexOf(char);
            return smallLetters.charAt((index + k) % 26);
        } else {
            let index = capitalLetters.indexOf(char);
            return capitalLetters.charAt((index + k) % 26);
        }
    }