Solution with alternating stacks
114
Jun 03, 2022

This solution holds two alternating stacks of lists. Each character goes into a list O(n).

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        # Handling the edge case of 1 row
        if numRows == 1:
            return s
        # Creating a list of stacks (each stack containing an empty list)
        stacks = [[[] for _ in range(numRows)], []]
        # A pointer to the selected stack
        stack_num = 0
        # Selecting the stack
        stack = stacks[stack_num]
        
        # Adding each character to the relevant stack
        for ch in s:
            # If the selected stack has only one list inside it
            if len(stack) == 1:
                # Selecting the string in the selected stack
                current_list = stack.pop()
                # Adding the character
                current_list.append(ch)
                # Returning back to the same stack if stack has only one string
                stack.append(current_list)
                # Changing the selected stack to the other one
                stack_num = (stack_num + 1) % 2
                stack = stacks[stack_num]
                continue
            # Adding the char to the head string of the selected string and moving the updated
            # string to the other stack
            current_list = stack.pop()
            current_list.append(ch)
            stacks[(stack_num + 1) % 2].append(current_list)
        
        # Putting together all strings in the stacks
        output_str = ''
        for l in stacks[1] + stacks[0][::-1]:
            output_str += ''.join(l)
        return output_str
        
Comments (0)