Find the Encrypted String — Easy Problem & Solution
Encrypt s by replacing every character with the character k places after it, wrapping around to the start of the string when you run off the end.
- Difficulty: Easy
- Topics: Strings, Simulation
- Asked at: Amazon, Google, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Encrypt s by replacing every character with the character k places after it, wrapping around to the start of the string when you run off the end.
Return the encrypted string.
Example 1
Input: s = "codekairo", k = 3
Output: ekairocod
Explanation: Position 0 takes the character at position 3, and so on around the ring.
Example 2
Input: s = "dart", k = 3
Output: tdar
Example 3
Input: s = "aaa", k = 1
Output: aaa
Explanation: Every character is the same, so rotating changes nothing.
Constraints
1 <= s.length <= 1001 <= k <= 10^4s consists only of lowercase English letters.
How to solve Find the Encrypted String
The answer at index i is s[(i + k) mod n] — a left rotation by k mod n. Build the result index by index.
Approach
- For each
ifrom 0 ton - 1, appends[(i + k) mod n]. - Return the accumulated string.
Why it works
The modulo is doing all the work: k can be a hundred times the string's length, and taking it modulo n collapses every one of those wraps into the single rotation they amount to. Rotating one character at a time in a loop would be O(n · k) and needlessly slow for large k.
Complexity
- Time —
O(n) - Space —
O(n) for the output
Pitfalls
- Shifting is on positions, not on the letters themselves — this is not a Caesar cipher.
kmay be far larger than the string; reduce it withmod n.- The direction is forward: position
ireads fromi + k, noti - k.
Reference solution
Python
def getEncryptedString(s: str, k: int) -> str:
n = len(s)
return "".join(s[(i + k) % n] for i in range(n))JavaScript
var getEncryptedString = function(s, k) {
var n = s.length, out = "";
for (var i = 0; i < n; i++) out += s.charAt((i + k) % n);
return out;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.