Find the Encrypted String
EasyPrompt
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.
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 <= 104sconsists only of lowercase English letters.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach recognizes that the described encryption algorithm is equivalent to a left circular shift (or rotation) of the string. The encrypted string can be constructed by splitting the original string at the k-th position (cyclically) and concatenating the two resulting parts in reverse order.
Algorithm
- Let
nbe the length of the input strings. - The rotation is cyclic, so rotating by
kis identical to rotating byk % n. Calculate the effective rotation amount,rot = k % n. - A left rotation by
rotpositions means the substring starting at indexrotbecomes the new prefix of the string. - This new prefix is
s.substring(rot). - The original prefix of the string,
s.substring(0, rot), becomes the new suffix. - Concatenate these two parts:
s.substring(rot) + s.substring(0, rot)to get the final encrypted string.
Walkthrough
The core idea is to treat the encryption as a string rotation problem, which can be solved efficiently using substring operations.
-
Algorithm:
- Let
nbe the length of the input strings. - The rotation is cyclic, so rotating by
kis identical to rotating byk % n. Calculate the effective rotation amount,rot = k % n. - A left rotation by
rotpositions means the substring starting at indexrotbecomes the new prefix of the string. - This new prefix is
s.substring(rot). - The original prefix of the string,
s.substring(0, rot), becomes the new suffix. - Concatenate these two parts:
s.substring(rot) + s.substring(0, rot)to get the final encrypted string.
- Let
-
Code Snippet:
class Solution { public String getEncryptedString(String s, int k) { int n = s.length(); int rot = k % n; String rightPart = s.substring(rot); String leftPart = s.substring(0, rot); return rightPart + leftPart; }}
Complexity
Time
O(n), where `n` is the length of the string `s`. In Java, `substring()` and string concatenation operations each create new strings and copy characters, taking time proportional to the string length.
Space
O(n). This approach creates intermediate substrings and a final result string, all of which require space proportional to `n`.
Trade-offs
Pros
Code is very concise and easy to understand.
Effectively uses high-level, built-in string manipulation functions.
Cons
Can be slightly less performant than manual construction. It involves creating at least two intermediate string objects before the final result, leading to extra memory allocations and character copying.
This approach directly implements the logic described in the problem statement. It iterates through each index of the target encrypted string and calculates the corresponding character from the source string using the cyclic shift formula. A StringBuilder is used for efficient string creation.
Algorithm
- Get the length of the string,
n = s.length(). - Initialize a
StringBuilderwith a capacity ofnto avoid internal array resizing during appends. - Loop from
i = 0ton - 1. The variableirepresents the index in the new encrypted string. - For each index
i, the problem states the new character is thek-th character after the character at indexi. This means the source character is at index(i + k). - To handle the cyclic nature, we use the modulo operator:
sourceIndex = (i + k) % n. - Get the character from the original string at
sourceIndex:s.charAt(sourceIndex). - Append this character to the
StringBuilder. - After the loop, convert the
StringBuilderto aStringand return it.
Walkthrough
This method builds the resulting string character by character, which is often one of the most efficient ways to construct strings in Java.
-
Algorithm:
- Get the length of the string,
n = s.length(). - Initialize a
StringBuilderwith a capacity ofnto avoid internal array resizing during appends. - Loop from
i = 0ton - 1. The variableirepresents the index in the new encrypted string. - For each index
i, the problem states the new character is thek-th character after the character at indexi. This means the source character is at index(i + k). - To handle the cyclic nature, we use the modulo operator:
sourceIndex = (i + k) % n. - Get the character from the original string at
sourceIndex:s.charAt(sourceIndex). - Append this character to the
StringBuilder. - After the loop, convert the
StringBuilderto aStringand return it.
- Get the length of the string,
-
Code Snippet:
class Solution { public String getEncryptedString(String s, int k) { int n = s.length(); StringBuilder result = new StringBuilder(n); for (int i = 0; i < n; i++) { int sourceIndex = (i + k) % n; result.append(s.charAt(sourceIndex)); } return result.toString(); }}
Complexity
Time
O(n), where `n` is the length of the string `s`. The code iterates through the string once. Operations inside the loop (`%`, `charAt`, `append`) are constant time (amortized for `append`).
Space
O(n). A `StringBuilder` is used, which internally allocates a character array of size `n` to build the result string.
Trade-offs
Pros
Generally more performant and memory-efficient as it avoids creating intermediate string objects.
Builds the final string in a single pass over the input data.
Cons
The code is slightly more verbose compared to the string slicing approach.
Solutions
Solution
class Solution {public String getEncryptedString(String s, int k) { char[] cs = s.toCharArray(); int n = cs.length; for (int i = 0; i < n; ++i) { cs[i] = s.charAt((i + k) % n); } return new String(cs); }}class Solution {public: string getEncryptedString(string s, int k) { int n = s.length(); string cs(n, ' '); for (int i = 0; i < n; ++i) { cs[i] = s[(i + k) % n]; } return cs; }};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)Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.