Problem Description
Given a string s and an integer k, create a new encrypted string where for each character in s, you replace it with the kth character after it in s (wrapping around to the beginning of s if necessary).
Key Insights
- The string is treated as a circular array.
- Instead of shifting letters based on the alphabet, we shift positions within the string.
- For each index i, the new character is at the index (i + k) mod n, where n is the length of s.
- A simple iteration over the string with modular arithmetic solves the problem in linear time.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string
Space Complexity: O(n), to store the resulting encrypted string
Solution
The idea is to use the given integer k to compute a new index for each character in the string. By taking each index i and adding k (then applying modulo n, where n is the string length), we can retrieve the character at the corresponding position in a cyclic manner. This directly constructs the encrypted string. The algorithm uses a simple loop and modular arithmetic, making it efficient and straightforward.