Skip to main content

Command Palette

Search for a command to run...

(17) Array: Special Reverse

Published
2 min readView as Markdown
(17) Array: Special Reverse
M

I am Computer Science Graduate and Web Developer.

Difficulty: Easy

Problem Statement: Given a string and you need to reverse it such that after the reversal position of a special character do not change.

Input: intell#ect, Output: tcelle#tni

Input: h@ello, Output: o@lleh

Input: a#b@c, Output: c#b@a

Approach: We store special characters in res and the character which is not special we store space instead of that.

In newS we store the reverse of string except for a special character. Now we traverse both the list and at any point if there is a special character we store it in the answer else we store the alphabet. At last print the answer.

s = input()
res = []
for i in s:
    if i >= 'a' and i <= 'z': res.append(' ')
    else: res.append(i)
s = s[::-1]
pos = 0
newS = ''
for i in s:
    if i >= 'a' and i <= 'z':
        newS += i

(x, y) = (0, 0)
(n, m) = (len(newS), len(res))
ans = ''
while x < n and y < m:
    if res[y] != ' ':
        ans += res[y]
        y += 1
    else:
        ans += newS[x]
        x += 1
        y += 1
while x < n:
    ans += newS[x]
    x += 1
while y < m:
    if res[y] == ' ':
        y += 1
        continue
    ans += res[y]
    y += 1
print ans

Subscribe to the newsletter so that you never miss any post or update just like this one.

You can follow me on Hashnode for:

  • Daily Data Structure and Algorithm based questions
  • Getting knowledge of various development-related tools, concepts, and practices

    Twitter , GitHub , LinkedIn and Hashnode

More from this blog

Untitled Publication

36 posts