# Find the Encrypted String
**Difficulty:** EASY
[External](https://leetcode.com/problems/find-the-encrypted-string)
Canonical: https://scaleengineer.com/dsa/problems/find-the-encrypted-string
**Data structures:** String
---
## Problem
You are given a string `s` and an integer `k`. Encrypt the string using the following algorithm:

* For each character `c` in `s`, replace `c` with the `kth` character after `c` in 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 <= 100`
* `1 <= k <= 104`
* `s` consists only of lowercase English letters.

# Approaches
## String Slicing and Concatenation
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.
**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`.
**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.
### Explanation
The core idea is to treat the encryption as a string rotation problem, which can be solved efficiently using substring operations.

*   **Algorithm:**
    1.  Let `n` be the length of the input string `s`.
    2.  The rotation is cyclic, so rotating by `k` is identical to rotating by `k % n`. Calculate the effective rotation amount, `rot = k % n`.
    3.  A left rotation by `rot` positions means the substring starting at index `rot` becomes the new prefix of the string.
    4.  This new prefix is `s.substring(rot)`.
    5.  The original prefix of the string, `s.substring(0, rot)`, becomes the new suffix.
    6.  Concatenate these two parts: `s.substring(rot) + s.substring(0, rot)` to get the final encrypted string.

*   **Code Snippet:**
    ```java
    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;
        }
    }
    ```
### Algorithm
*   Let `n` be the length of the input string `s`.
*   The rotation is cyclic, so rotating by `k` is identical to rotating by `k % n`. Calculate the effective rotation amount, `rot = k % n`.
*   A left rotation by `rot` positions means the substring starting at index `rot` becomes 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.

## Direct Construction using StringBuilder
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.
**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.
**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.
### Explanation
This method builds the resulting string character by character, which is often one of the most efficient ways to construct strings in Java.

*   **Algorithm:**
    1.  Get the length of the string, `n = s.length()`.
    2.  Initialize a `StringBuilder` with a capacity of `n` to avoid internal array resizing during appends.
    3.  Loop from `i = 0` to `n - 1`. The variable `i` represents the index in the new encrypted string.
    4.  For each index `i`, the problem states the new character is the `k`-th character *after* the character at index `i`. This means the source character is at index `(i + k)`.
    5.  To handle the cyclic nature, we use the modulo operator: `sourceIndex = (i + k) % n`.
    6.  Get the character from the original string at `sourceIndex`: `s.charAt(sourceIndex)`.
    7.  Append this character to the `StringBuilder`.
    8.  After the loop, convert the `StringBuilder` to a `String` and return it.

*   **Code Snippet:**
    ```java
    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();
        }
    }
    ```
### Algorithm
*   Get the length of the string, `n = s.length()`.
*   Initialize a `StringBuilder` with a capacity of `n` to avoid internal array resizing during appends.
*   Loop from `i = 0` to `n - 1`. The variable `i` represents the index in the new encrypted string.
*   For each index `i`, the problem states the new character is the `k`-th character *after* the character at index `i`. 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 `StringBuilder` to a `String` and return it.

# Solutions
### Java

```java
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);
  }
}

```

### CPP

```cpp
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;
  }
};

```

### Python

```python
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)

```
