Given a string s
, this is how you encrypt it:
You need to implement a function that returns the encrypted string for the given input string s
.
Input: s = "abc"
Output: "bac"
Input: s = "abcd"
Output: "bacd"
n
falls within the reasonable limit to avoid deep recursion problems, for instance, 1 <= n <= 1000
.s
is empty, return an empty string.n
, the middle character index is (n - 1) // 2
.s[:mid]
) and the right substring (s[mid+1:]
).def find_encrypted_string(s):
if not s:
return ""
def encrypt(s):
if len(s) == 0:
return ""
mid = (len(s) - 1) // 2
return s[mid] + encrypt(s[:mid]) + encrypt(s[mid+1:])
return encrypt(s)
This should efficiently handle the given constraints.
Let’s now consider a few test cases to validate our solution:
print(find_encrypted_string("abc")) # Expected Output: "bac"
print(find_encrypted_string("abcd")) # Expected Output: "bacd"
print(find_encrypted_string("abcdefg")) # Expected Output: "dbaecfg"
print(find_encrypted_string("")) # Expected Output: ""
print(find_encrypted_string("a")) # Expected Output: "a"
By running these tests, you can ensure the function works as expected.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?