🎨 Try our Free AI Image Generation Feature

3210. Find the Encrypted String

avatar
Dare2Solve

1 year ago

3210. Find the Encrypted String

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:

  • Effective shift is 3 % 6 = 3.
  • Encryption: - 'a' shifts to 'd' - 'b' shifts to 'e' - 'c' shifts to 'f' - 'd' shifts to 'a' - 'e' shifts to 'b' - 'f' shifts to 'c' - Resulting in encrypted string "defabc".

Complexity

  • Time Complexity: O(n), where n is the length of the string s. Each character in s is processed exactly once.
  • Space Complexity: O(n), additional space is used to store the resulting encrypted string.

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