Find the Encrypted String - Problem

You are given a string s and an integer k. Your task is to encrypt the string using the following algorithm:

For each character c in s, replace c with the k-th character after c in the string (in a cyclic manner).

Example: If s = "abc" and k = 1, then 'a' is replaced by 'b' (1 position after 'a'), 'b' is replaced by 'c' (1 position after 'b'), and 'c' is replaced by 'a' (1 position after 'c' cyclically).

Return the encrypted string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abc", k = 1
Output: "bca"
💡 Note: For each character, replace with the next character: 'a' → 'b' (1 step), 'b' → 'c' (1 step), 'c' → 'a' (1 step, wrapping around)
Example 2 — Larger Step
$ Input: s = "abcdef", k = 2
Output: "cdefab"
💡 Note: Each character moves 2 positions forward: 'a'→'c', 'b'→'d', 'c'→'e', 'd'→'f', 'e'→'a', 'f'→'b'
Example 3 — Single Character
$ Input: s = "x", k = 1
Output: "x"
💡 Note: With only one character, moving k positions always returns to the same character

Constraints

  • 1 ≤ s.length ≤ 100
  • 1 ≤ k ≤ 104
  • s consists of lowercase English letters

Visualization

Tap to expand
Find the Encrypted String INPUT String s = "abc" a i=0 b i=1 c i=2 k = 1 Cyclic Rotation: a b c ALGORITHM STEPS 1 Get string length n = len(s) = 3 2 Apply modular formula new_i = (i + k) % n 3 Calculate each position i=0: (0+1)%3 = 1 s[1]='b' i=1: (1+1)%3 = 2 s[2]='c' i=2: (2+1)%3 = 0 s[0]='a' Result: "bca" 4 Build encrypted string Concatenate all new chars Time: O(n) | Space: O(n) FINAL RESULT Original String: a b c Encrypted String: b c a Output: "bca" OK - Encrypted! Key Insight: Using modular arithmetic (i + k) % n handles the cyclic wrap-around automatically. When the index exceeds string length, the modulo operation wraps it back to the beginning. This eliminates the need for conditional checks and makes the solution elegant and efficient. TutorialsPoint - Find the Encrypted String | Optimized with Modular Arithmetic
Asked in
Google 15 Amazon 12 Microsoft 8
33.2K Views
Medium Frequency
~10 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen