Find Last Character
Learn this problemProblem statement
You are given an alphanumeric string S and an integer K. Consider a new string in which S is appended K-1 times.
Now, in this new string, the following operations are performed:-
- Every alternate character starting from the first character is removed.
- Every alternate character starting from the last character is removed.
The above two operations are repeated until one character remains. Your task is to find and return a string representing the last remaining character after performing all the operations.
Note: Here, alphanumeric refers to the string that may contain alphabets (a-z and A-Z), numerals (0-9), and certain special characters such as '$', '#', '&', and '*'
Input Specification:
input1: A string S, representing the alphanumeric string.
input2: An integer value K.
Output Specification:
Return a string representing the last remaining character after performing all the operations mentioned.
Function
findLastCharacter(S: String, K: int) → StringExamples
Example 1
S = "abcd"K = 3return = "b"The following operations can be performed on the string "abcd":
- S = a b c d a b c d a b c d (The string obtained after appending the given string K-1 times)
- S = b d b d b d (The string obtained after removing every alternate character from the beginning)
- S = b b b (The string obtained after removing every alternate character from the end)
- S = b
Since, b is the only character left after performing all the operations. Therefore, b is returned as the output.
Example 2
S = "j#k&h"K = 5return = "&"The following operations can be performed on the string "j#k&h":
- S = j # k & h j # k & h j # k & h j # k & h j # k & h (The string obtained after appending the given string K-1 times)
- S = # & j k h # & j k h # & (The string obtained after removing every alternate character from the beginning)
- S = # j h & k # (The string obtained after removing every alternate character from the end)
- S = j & # (The string obtained after removing every alternate character from the beginning)
- S = &
& is the only character left after performing all the operations. Therefore, & is returned as the output.
Constraints
1 <= S.length <= 10^51 <= K <= 10^9Scontains letters, digits, or the characters$,#,&, and*.S.length * Kfits in a signed 64-bit integer.