Find the Encrypted String
EasyUpdated: Aug 2, 2025
Practice on:
Problem
You are given a string s and an integer k. Encrypt the string using the following algorithm:
- For each character
cins, replacecwith thekthcharacter aftercin the string (in a cyclic manner).
Return the encrypted string.
Examples
Example 1
Input: s = "dart", k = 3
Output: "tdar"
Explanation:
* For `i = 0`, the 3rd character after `'d'` is `'t'`.
* For `i = 1`, the 3rd character after `'a'` is `'d'`.
* For `i = 2`, the 3rd character after `'r'` is `'a'`.
* For `i = 3`, the 3rd 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
Method 1 – Cyclic Indexing
Intuition
To encrypt the string, for each character at index i, we replace it with the character at index (i + k) % n, where n is the length of the string. This wraps around the string in a cyclic manner.
Approach
- Let n be the length of the string s.
- For each index i from 0 to n-1:
- The encrypted character at position i is s[(i + k) % n].
- Build the encrypted string by collecting these characters in order.
- Return the encrypted string.
Code
C++
class Solution {
public:
string encryptString(string s, int k) {
int n = s.size();
string ans(n, ' ');
for (int i = 0; i < n; ++i) {
ans[i] = s[(i + k) % n];
}
return ans;
}
};
Go
func encryptString(s string, k int) string {
n := len(s)
ans := make([]byte, n)
for i := 0; i < n; i++ {
ans[i] = s[(i+k)%n]
}
return string(ans)
}
Java
class Solution {
public String encryptString(String s, int k) {
int n = s.length();
char[] ans = new char[n];
for (int i = 0; i < n; ++i) {
ans[i] = s.charAt((i + k) % n);
}
return new String(ans);
}
}
Kotlin
class Solution {
fun encryptString(s: String, k: Int): String {
val n = s.length
val ans = CharArray(n)
for (i in 0 until n) {
ans[i] = s[(i + k) % n]
}
return String(ans)
}
}
Python
class Solution:
def encryptString(self, s: str, k: int) -> str:
n = len(s)
return ''.join(s[(i + k) % n] for i in range(n))
Rust
impl Solution {
pub fn encrypt_string(s: String, k: i32) -> String {
let n = s.len();
let s = s.as_bytes();
let mut ans = vec![0u8; n];
for i in 0..n {
ans[i] = s[(i + k as usize) % n];
}
String::from_utf8(ans).unwrap()
}
}
TypeScript
class Solution {
encryptString(s: string, k: number): string {
const n = s.length;
let ans = '';
for (let i = 0; i < n; ++i) {
ans += s[(i + k) % n];
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n), where n is the length of the string, as we process each character once. - 🧺 Space complexity:
O(n), for the output string.