3210. Find the Encrypted String

Dare2Solve

Dare2Solve

3210. Find the Encrypted String
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Intuition

The problem requires encrypting a string s by shifting each character k positions forward in a cyclic manner. This means if the shift goes beyond the end of the string, it wraps around to the beginning.

Approach

  1. Handle Edge Cases: If s is empty or k is 0, return s directly since no encryption is needed.

  2. Calculate Effective Shift: Compute the effective shift as k % len(s) to handle cases where k is larger than the length of s.

  3. Construct the Encrypted String:

    • Iterate through each character c in the string s.
    • Compute the new position for c using (current_position + effective_shift) % len(s).
    • Append the shifted character to the result string.
  4. Return the Result: Once all characters are shifted, return the encrypted string.

Example

Given s = "abcdef" and k = 3:

Complexity

Code

C++

class Solution {
public:
    string getEncryptedString(string s, int k) {
        k %= s.length();
        return s.substr(k) + s.substr(0, k);
    }
};

Python

class Solution:
    def getEncryptedString(self, s: str, k: int) -> str:
        k %= len(s)
        return s[k:] + s[:k]

Java

class Solution {
    public String getEncryptedString(String s, int k) {
        k %= s.length();
        return s.substring(k) + s.substring(0, k);
    }
}

JavaScript

/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var getEncryptedString = function (s, k) {
  k %= s.length;
  return s.substring(k) + s.substring(0, k);
};