• + 1 comment

    Python3

    def biggerIsGreater(w):
        # i is the index of the element on the right hand-side
        index = None
        for i in range(len(w)-1, -1, -1): 
            w_list = sorted(list(w[i:]))
            w_list.reverse()
            sorted_w = ""
            for char in w_list:
                sorted_w += char
            if sorted_w != w[i:]:
                index = i
                break
        
        if index is None:
            return "no answer"
        
        smallest_bigger = None
        for i in w[index:]:
            if i > w[index] and (smallest_bigger is None or i < smallest_bigger):
                smallest_bigger = i
        w_list = list(w[index + 1:])
        w_list.remove(smallest_bigger)
        w_list.append(w[index])
        w_list.sort()
        sorted_w = ""
        for char in w_list:
            sorted_w += char
        w = w[:index] + smallest_bigger + sorted_w
        return w