Difficulty: Easy | Acceptance: 68.20% | Paid: No Topics: String
You are given a string s and an integer k. The encryption rules are as follows:
For each character s[i] in the string, replace it with the character that is k positions ahead of it in the string.
If moving k positions ahead goes past the end of the string, wrap around to the beginning.
Return the resulting encrypted string.
- Examples
- Constraints
- Iterative Simulation
- String Slicing
Examples
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 <= 100
1 <= k <= 10⁴
s consists of lowercase English letters.
Iterative Simulation
Intuition We can directly simulate the encryption process by iterating through each character of the string and calculating the index of the character that should replace it using modulo arithmetic.
Steps
- Get the length
nof the strings. - Initialize an empty result string (or builder).
- Loop through each index
ifrom0ton - 1. - Calculate the target index as
(i + k) % n. - Append the character at the target index to the result.
- Return the result.
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
n = len(s)
res = []
for i in range(n):
res.append(s[(i + k) % n])
return ''.join(res)Complexity
- Time: O(n), where n is the length of the string. We iterate through the string once.
- Space: O(n) to store the result string.
- Notes: This approach is straightforward and works well for the given constraints.
String Slicing
Intuition
The encryption process effectively rotates the string to the left by k positions. The character at index i in the result comes from index (i + k) % n in the original string. This is equivalent to taking the substring starting from index k and appending the substring ending at index k.
Steps
- Calculate
k = k % nto handle cases wherekis larger than the string length. - Return the concatenation of
s[k:]ands[:k].
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
n = len(s)
k %= n
return s[k:] + s[:k]Complexity
- Time: O(n) for creating the new string (slicing and concatenation).
- Space: O(n) to store the result.
- Notes: This is the most idiomatic and concise solution in languages that support string slicing.