Example #1
0
    def solve(self):
        """Solve the problem

        Note:

        Args:

        Returns:
            integer

        Raises:
            None
        """
        print("Solving {} problem ...".format(self.PROBLEM_NAME))

        notation_stack = Stack()
        for i in range(len(self.input_list)):
            if self.input_list[i] not in self.OPERATORS:
                notation_stack.push(self.input_list[i])
            else:
                operand2 = int(notation_stack.pop())
                operand1 = int(notation_stack.pop())

                result = self.evaluate(operand1, operand2, self.input_list[i])

                notation_stack.push(result)

        return notation_stack.pop()
Example #2
0
    def __init__(self):
        """Min Stack

        Args:

        Returns:
            None

        Raises:
            None
        """
        super().__init__(self.PROBLEM_NAME)
        self.input_stack = Stack()
        self.min_stack = Stack()
    def solve(self):
        """Solve the problem

        Note: O(n) (runtime) since every bar is pushed and popped only once.

        Args:

        Returns:
            integer

        Raises:
            None
        """
        # stack to store the indices
        stack = Stack()

        max_area = 0
        index = 0

        while index < len(self.input_list):
            # If this bar is higher than the bar on top stack, push it to stack
            if len(stack) == 0 or self.input_list[
                    stack.peek()] <= self.input_list[index]:
                stack.push(index)
                index = index + 1

            # If this bar is lower than top of stack, then calculate area of rectangle with
            # stack top as the smallest (or minimum # height) bar.'i' is 'right index' for
            # the top and element before top in stack is 'left index'
            else:
                top_index = stack.pop()

                # Calculate the area with histogram[top_of_stack] stack as smallest bar
                area = (self.input_list[top_index] *
                        ((index - stack.peek() - 1) if stack else index))

                max_area = max(area, max_area)

        # Now pop the remaining bars from  stack and calculate area with
        # every popped bar as the smallest bar
        while stack:
            # pop the top
            top_index = stack.pop()

            # Calculate the area with
            # histogram[top_of_stack]
            # stack as smallest bar
            area = (self.input_list[top_index] *
                    ((index - stack.peek() - 1) if stack else index))

            # update max area, if needed
            max_area = max(max_area, area)

        return max_area
Example #4
0
    def solve(self):
        """Solve the problem

        Note: O(n logn) (runtime) and O(n) (Space) works by using a stack to store the elements in the order.
        Then, when the right subtree element is reached, it will pop the left subtree elements and then the root is
        set.

        Args:

        Returns:
            boolean

        Raises:
            None
        """
        print("Solving {} problem ...".format(self.PROBLEM_NAME))

        value_stack = Stack()

        root = -sys.maxsize

        for value in self.input_list:
            # If we find a node which is on the right side
            # and smaller than root, return False
            if value < root:
                return False

            while len(value_stack) > 0 and value_stack.peek() < value:
                root = value_stack.pop()

            # If we find a node who is on the right side
            # and greater than root, add to the stack
            value_stack.push(value)

        return True
Example #5
0
    def test_stack(self):
        """Test for get_orientation

        Args:
            self: TestStack

        Returns:
            None

        Raises:
            None
        """
        # Given
        n = 4
        stack = Stack()
        for i in range(n):
            stack.push(i)

        # Then
        self.assertEqual(len(stack), n)
        for i in reversed(range(len(stack))):
            self.assertEqual(stack.pop(), i)
Example #6
0
    def solve(self):
        """Solve the problem

        Note:

        Args:

        Returns:
            boolean

        Raises:
            None
        """
        parantheses_stack = Stack()

        for c in self.input_string:
            if c in self.PARANTHESES_MAP:
                parantheses_stack.push(c)
            elif len(parantheses_stack) == 0 or self.PARANTHESES_MAP[
                    parantheses_stack.pop()] != c:
                return False

        return len(parantheses_stack) == 0
Example #7
0
    def solve(self):
        """Solve the problem

        Note: O(n) (runtime) and O(n) (space) solution uses the depth  first traversal to traverse nodes and copy node neighbors.

        Args:

        Returns:
            GraphNode

        Raises:
            None
        """
        print("Solving {} problem ...".format(self.PROBLEM_NAME))
        # Create a stack for DFS
        nodes_stack = Stack()
        nodes_stack.push(self.input_graph_node)

        # Root node to return for the cloned graph
        cloned_graph_node = GraphNode(self.input_graph_node.data)

        # Bookkeeping visited nodes -- contains the cloned nodes
        visited_dict = {self.input_graph_node: cloned_graph_node}

        while len(nodes_stack) > 0:
            current_node = nodes_stack.pop()
            copied_node = visited_dict[current_node]

            # iterate current node's neighbors
            for node in current_node.neighbors:
                # if the node is already not visited
                if node not in visited_dict:
                    # append the node to queue
                    nodes_stack.push(node)

                    # create a copy node for the neighbor
                    neighbor_node = GraphNode(node.data)

                    # add neighbor and update visited
                    copied_node.add_neighbor(neighbor_node)
                    visited_dict[node] = neighbor_node
                else:
                    # if the node is already visited
                    neighbor_node = visited_dict[node]

                    # Add the neighbor node to the copied node's neighbors if it's not added
                    if neighbor_node not in copied_node.neighbors:
                        copied_node.add_neighbor(neighbor_node)

        return cloned_graph_node
    def solve(self):
        """Solve the problem

        Note: O(n) solution works by using the depth first search to color nodes.
        If the node color and the neighbor's color are the same, it's not a bipartite.

        Args:

        Returns:
            Boolean

        Raises:
            None
        """
        print("Solving {} problem ...".format(self.PROBLEM_NAME))

        nodes_stack = Stack()
        nodes_stack.push(self.input_graph_node)

        visited_vertex_list = []
        visited_node_color_dict = {self.input_graph_node: self.NODE_COLOR_RED}

        # iterate through the node stack and check for visited nodes and add the non-visited nodes.
        while len(nodes_stack) > 0:
            node = nodes_stack.pop()
            node_color = visited_node_color_dict[node]
            neighbor_color = (self.NODE_COLORS - {node_color}).pop()

            if node not in visited_vertex_list:
                visited_vertex_list.append(node)

                for neighbor_node in node.neighbors:
                    nodes_stack.push(neighbor_node)

                    if neighbor_node not in visited_node_color_dict:
                        visited_node_color_dict[neighbor_node] = neighbor_color
                    else:
                        actual_neighbor_color = visited_node_color_dict[
                            neighbor_node]

                        if actual_neighbor_color != neighbor_color:
                            return False

        return True
Example #9
0
    def depth_first_traversal(graph_node, vertex_list):
        """Depth First Traversal of a Graph. Complexity is O(V+E).

        Args:
            graph_node: Starting node of the graph
            vertex_list: List of vertices traversed

        Returns:
            None

        Raises:
            None
        """
        nodes_stack = Stack()
        nodes_stack.push(graph_node)

        while len(nodes_stack) > 0:
            node = nodes_stack.pop()

            if node.data not in vertex_list:
                vertex_list.append(node.data)

                for neighbor_node in node.neighbors:
                    nodes_stack.push(neighbor_node)
Example #10
0
    def solve(self):
        """Solve the problem

        Note:

        Args:

        Returns:
            list

        Raises:
            None
        """
        print("Solving {} problem ...".format(self.PROBLEM_NAME))

        current_node = self.input_linked_list.head
        previous_node = None

        count = 0
        group_stack = Stack()

        # append the nodes to the stack till the required group size
        while current_node is not None and count < self.group_size:
            group_stack.push(current_node)
            current_node = current_node.next_node
            count = count + 1

        # pop nodes from the stack and re-point the head
        while len(group_stack) > 0:
            if previous_node is None:
                previous_node = group_stack.pop()
                self.input_linked_list.head = previous_node
            else:
                previous_node.next_node = group_stack.pop()
                previous_node = previous_node.next_node

        previous_node.next_node = current_node

        return self.input_linked_list.output_list()
Example #11
0
class MinStack(Problem):
    """
    Min Stack
    """
    PROBLEM_NAME = "MinStack"

    def __init__(self):
        """Min Stack

        Args:

        Returns:
            None

        Raises:
            None
        """
        super().__init__(self.PROBLEM_NAME)
        self.input_stack = Stack()
        self.min_stack = Stack()

    def solve(self):
        """Solve the problem

        Args:

        Returns:
            None

        Raises:
            None
        """
        pass

    def push(self, data):
        """Push an element to the stack

        Args:

        Returns:
            None

        Raises:
            None
        """
        self.input_stack.push(data)

        if self.min_stack.peek() is None or data < self.min_stack.peek():
            self.min_stack.push(data)

    def pop(self):
        """Pops the element from the stack

        Args:

        Returns:
            data

        Raises:
            None
        """
        data = self.input_stack.pop()

        if data == self.min_stack.peek():
            self.min_stack.pop()

        return data

    def top(self):
        """Return the top element from the input stack

        Args:

        Returns:
            data

        Raises:
            None
        """
        return self.input_stack.peek()

    def get_min(self):
        """Return the min element from the min stack

        Args:

        Returns:
            data

        Raises:
            None
        """
        return self.min_stack.peek()