🎨Now live:  Try our Free AI Image Generation Feature

Intuition
 The problem requires encrypting a string s by shifting each character k positions forward in a cyclic manner. This means if the shift goes beyond the end of the string, it wraps around to the beginning. 
Approach
- Handle Edge Cases: If sis empty orkis 0, returnsdirectly since no encryption is needed.
- Calculate Effective Shift: Compute the effective shift as k % len(s)to handle cases wherekis larger than the length ofs.
- Construct the Encrypted String:
- Iterate through each character cin the strings. - Compute the new position forcusing(current_position + effective_shift) % len(s). - Append the shifted character to the result string.
- Return the Result: Once all characters are shifted, return the encrypted string.
Example
 Given s = "abcdef" and k = 3: 
- Effective shift is 3 % 6 = 3.
- Encryption:
- 'a' shifts to 'd'
- 'b' shifts to 'e'
- 'c' shifts to 'f'
- 'd' shifts to 'a'
- 'e' shifts to 'b'
- 'f' shifts to 'c'
- Resulting in encrypted string "defabc".
Complexity
- Time Complexity: O(n), where n is the length of the string s. Each character insis processed exactly once.
- Space Complexity: O(n), additional space is used to store the resulting encrypted string.
Code
C++
class Solution {
public:
    string getEncryptedString(string s, int k) {
        k %= s.length();
        return s.substr(k) + s.substr(0, k);
    }
};Python
class Solution:
    def getEncryptedString(self, s: str, k: int) -> str:
        k %= len(s)
        return s[k:] + s[:k]Java
class Solution {
    public String getEncryptedString(String s, int k) {
        k %= s.length();
        return s.substring(k) + s.substring(0, k);
    }
}JavaScript
/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var getEncryptedString = function (s, k) {
  k %= s.length;
  return s.substring(k) + s.substring(0, k);
};