Home Blog Coding Problem Practice

Recursively remove all adjacent duplicates

Published:


problem url http://www.geeksforgeeks.org/recursively-remove-adjacent-duplicates-given-string/


Input:  azxxzy
Output: ay
First "azxxzy" is reduced to "azzy".
The string "azzy" contains duplicates,
so it is further reduced to "ay".

Input: geeksforgeeg
Output: gksfor
First "geeksforgeeg" is reduced to
"gksforgg". The string "gksforgg"
contains duplicates, so it is further
reduced to "gksfor".

Input: caaabbbaacdddd
Output: Empty String

Input: acaaabbbacdddd
Output: acac



def removeAdjoints(ipx, start, end):
    if(len(ipx) == 0):
        print("blank")
    else:
        print(ipx)

    if len(ipx) > 0 and end < len(ipx):
        if ipx[start] == ipx[end]:
            if end + 1 < len(ipx):
                removeAdjoints(ipx, start, end + 1)
            elif start < end:
                ipx = ipx[0:start]
                if len(ipx) > 0:
                    removeAdjoints(ipx, 0, 1)
        elif start + 1 < end:
            ipx = ipx[0:start] + ipx[end:len(ipx)]
            removeAdjoints(ipx, 0, 1)
        else:
            if end + 1 < len(ipx):
                removeAdjoints(ipx, start + 1, end + 1)


removeAdjoints("azxxzy", 0, 1)
print("----")
removeAdjoints("geeksforgeeg", 0, 1)
print("----")
removeAdjoints("gksforgg", 0, 1)
print("----")
removeAdjoints("caaabbbaacdddd", 0, 1)
print("----")
removeAdjoints("dddd", 0, 1)
print("----")
Comment