Find the Encrypted String Problem
#3210
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3210.
You are given a string s and an integer k. Encrypt the string using the following algorithm:
- For each character
cins, replacecwith thek^thcharacter aftercin the string (in a cyclic manner).
Return the encrypted string.
Example 1:
Input: s = "dart", k = 3
Output: "tdar"
Explanation:
- For i = 0, the 3^rd character after 'd' is 't'.
- For i = 1, the 3^rd character after 'a' is 'd'.
- For i = 2, the 3^rd character after 'r' is 'a'.
- For i = 3, the 3^rd character after 't' is 'r'.
Example 2:
Input: s = "aaa", k = 1
Output: "aaa"
Explanation:
As all the characters are the same, the encrypted string will also be the same.
Constraints:
1 <= s.length <= 1001 <= k <= 10^4sconsists only of lowercase English letters.
Solution
Approach: Simulation
For each position i, the encrypted character is s[(i + k) % n]. Build the result by applying this to every index.
Complexity: O(n) time and O(n) space.
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
cs = list(s)
n = len(s)
for i in range(n):
cs[i] = s[(i + k) % n]
return "".join(cs)