We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Encrypted String

Number: 3468

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a string s and an integer k, create a new encrypted string where for each character in s, you replace it with the kth character after it in s (wrapping around to the beginning of s if necessary).


Key Insights

  • The string is treated as a circular array.
  • Instead of shifting letters based on the alphabet, we shift positions within the string.
  • For each index i, the new character is at the index (i + k) mod n, where n is the length of s.
  • A simple iteration over the string with modular arithmetic solves the problem in linear time.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string
Space Complexity: O(n), to store the resulting encrypted string


Solution

The idea is to use the given integer k to compute a new index for each character in the string. By taking each index i and adding k (then applying modulo n, where n is the string length), we can retrieve the character at the corresponding position in a cyclic manner. This directly constructs the encrypted string. The algorithm uses a simple loop and modular arithmetic, making it efficient and straightforward.


Code Solutions

# Function to encrypt the string by rotating based on the given integer k
def encryptString(s, k):
    n = len(s)  # length of the input string
    encrypted_chars = []  # list to store encrypted characters
    # Loop through each index in the string
    for i in range(n):
        # Calculate new index using modular arithmetic for cyclic rotation
        new_index = (i + k) % n
        # Append the character at the new index to the encrypted_chars list
        encrypted_chars.append(s[new_index])
    # Join the list to form the final encrypted string
    return ''.join(encrypted_chars)

# Example usage:
print(encryptString("dart", 3))  # expected output: "tdar"
print(encryptString("aaa", 1))   # expected output: "aaa"
← Back to All Questions