Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Reverse String

Moderate
0/80
profile
Contributed by
14 upvotes
Asked in companies
IndiaMartMyntraAccenture

Problem statement

You are given a string ‘S’. You are also given ‘M’ integers in an array ‘A’. You perform ‘M’ operations on this string. The operations are given in an array ‘A’ of size ‘M’.

You perform the operations in the order they appear in the array ‘A’. In the ‘i’th operation, you reverse the substring of ‘S’ from the position ‘A[i]’ to ‘len(S)’ - ‘A[i]’ - 1 (0 based).

Your task is to find the string after performing all the operations.

Example :
‘S’ = “aabcd”, ‘M’ = 2, ‘A’ = [0, 1]
After 1st operation i.e, reversing from [0, 4], ‘S’ = “dcbaa”.
After 2nd operation i.e, reversing from [1, 3], ‘S’ = “dabca”.
Hence, the answer is “dabca”.
Detailed explanation ( Input/output format, Notes, Images )
Constraints :
1 ≤ T ≤ 10
1 ≤ len(S) ≤ 10^5
1 ≤ M ≤ 10^5
Each ‘A[i]’ is such that the range [‘A[i]’, len(‘S’) - ‘A[i]’ - 1] is non-empty.
It is guaranteed that the sum of lengths of ‘S’ and ‘M’ is ≤ 10^5 for all test cases, respectively.

Time limit: 1 sec
Sample Input 1 :
2
gaagbd
3
2 2 2
dbgd
5
1 1 1 0 0
Sample Output 1 :
gagabd
dgbd
Explanation For Sample Input 1 :
For test case 1:
Here, len(‘S’) = 6. So, we need to reverse the string ‘S’[2, 3] three times.
After 1st reversal: ‘S’ = “gagabd”.
After 2nd reversal: ‘S’ = “gaagbd”.
After 3rd reversal: ‘S’ = “gagabd”.
Hence, the answer is “gagabd”.

For test case 2:
Here, len(‘S’) = 4. We need to reverse the string ‘S’[1, 2], ‘S’[1, 2], ‘S’[1, 2], ‘S’[0, 3], ‘S’[0, 3].
After 1st reversal: ‘S’ = “dgbd”
After 2nd reversal: ‘S’ = “dbgd”
After 3rd reversal: ‘S’ = “dgbd”
After 4th reversal: ‘S’ = “dbgd”
After 5th reversal: ‘S’ = “dgbd”
Hence, the answer is “dgbd”.
Sample Input 2 :
2
cgagbga
4
0 2 1 0
daa
3
1 0 1
Sample Output 2 :
cgagbga
aad
Full screen
Console