#3210

Find the Encrypted String

Easy
StringCyclic ArrayString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the fact that we can directly compute the new character's position without needing to iterate through the string multiple times. This reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty result string.
  2. 2Step 2: For each character in the input string, calculate its new position using (i + k) % length of the string.
  3. 3Step 3: Append the character at the new position to the result string.
  4. 4Step 4: Return the result string.
solution.py8 lines
1def encrypt_string(s, k):
2    n = len(s)
3    k = k % n  # Handle cases where k > n
4    result = ''
5    for i in range(n):
6        new_index = (i + k) % n
7        result += s[new_index]
8    return result

Complexity note: The time complexity is O(n) because we only iterate through the string once, and the space complexity is O(n) due to the storage of the result string.

  • 1Cyclic nature of the problem allows for modulo operations.
  • 2Handling cases where k is larger than the string length is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.