hon9g / algorithms

TIL: to keep practice on algorithms
6 stars 2 forks source link

cpps2: Queue and Stack #17

Closed hon9g closed 4 years ago

hon9g commented 4 years ago

Click ✔️ to go to each solution. The Link to each problem🌐 is at the top of each solution.

# title my solution
1 Largest Rectangle in Histogram ✔️
2 Binary Search Tree Iterator ✔️
3 Asteroid Collision ✔️
4 Daily Temperatures ✔️
5 Design Circular Queue ✔️

+

Problems selected by LeetCode for the topic Queue and Stack 🌐

🔗 Queue : First-in First-out Data Structure

# title my solution
1 Design Circular Queue ✔️

🔗 Queue and BFS

# title my solution
1 Number of Islands ✔️
2 Open the Lock ✔️
3 Perfect Squares ✔️

🔗 Stack : Last-in First-out Data Structure

# title my solution
1 Min Stack ✔️
2 Valid Parentheses ✔️
3 Daily Temperatures ✔️
4 Evaluate Reverse Polish Notation ✔️

🔗 Stack and DFS

# title my solution
1 Number of Islands ✔️
2 Clone Graph ✔️
3 Target Sum ✔️
4 Binary Tree Inorder Traversal ✔️

🔗 Stack and Queue

# title my solution
1
hon9g commented 4 years ago

Q5. Design Circular Queue

Circular Queue by Array

Circular Queue by Linked List

class Node:
    def __init__(self, x: int):
        self.val = x
        self.next = None

class MyCircularQueue:

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the queue to be k.
        """
        self.capacity, self.count = k, 0
        self.head = self.tail  = None

    def enQueue(self, value: int) -> bool:
        """
        Insert an element into the circular queue. Return true if the operation is successful.
        """
        if self.isFull():
            return False
        elif self.isEmpty():
            self.head = self.tail = Node(value)
        else:
            self.tail.next = Node(value)
            self.tail = self.tail.next
        self.count += 1
        return True

    def deQueue(self) -> bool:
        """
        Delete an element from the circular queue. Return true if the operation is successful.
        """
        if self.isEmpty():
            return False
        elif self.head == self.tail:
            self.head = self.tail = None
        else:
            self.head = self.head.next
        self.count -= 1
        return True

    def Front(self) -> int:
        """
        Get the front item from the queue.
        """
        return self.head.val if not self.isEmpty() else -1

    def Rear(self) -> int:
        """
        Get the last item from the queue.
        """
        return self.tail.val if not self.isEmpty() else -1

    def isEmpty(self) -> bool:
        """
        Checks whether the circular queue is empty or not.
        """
        return self.count == 0

    def isFull(self) -> bool:
        """
        Checks whether the circular queue is full or not.
        """
        return self.capacity <= self.count
hon9g commented 4 years ago

Number of Islands

hon9g commented 4 years ago

Open the Lock

🔗 Queue and BFS

hon9g commented 4 years ago

Perfect Squares

hon9g commented 4 years ago

Min Stack

Stack min values

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self._stack = []

    def push(self, x: int) -> None:
        if not self._stack:
            self._stack.append((x, x))
        else:
            self._stack.append((x, min(self._stack[-1][1], x)))

    def pop(self) -> None:
        return self._stack.pop()

    def top(self) -> int:
        return self._stack[-1][0] if self._stack else None

    def getMin(self) -> int:
        return self._stack[-1][1] if self._stack else None

Sort the stack to get a min value

hon9g commented 4 years ago

Valid Parentheses

🔗 Stack : Last-in First-out Data Structure

hon9g commented 4 years ago

Q4. Daily Temperatures

🔗 Stack : iterate over every day of future (TLE)

🔗 Stack : iterate over warmer days of future

hon9g commented 4 years ago

Evaluate Reverse Polish Notation

🔗 Stack the numbers

hon9g commented 4 years ago

Clone Graph

🔗 Stack and DFS

class Solution(object): def init(self): self.visited = {}

def cloneGraph(self, node):
    if not node: return node
    if node in self.visited: return self.visited[node]

    self.visited[node] = Node(node.val, [])

    if node.neighbors:
        self.visited[node].neighbors = [self.cloneGraph(n) for n in node.neighbors]

    return self.visited[node]
hon9g commented 4 years ago

Target Sum

🔗 DFS

🔗 DFS with memorization

class Solution:
    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        self.memo = {}

        def targetSumWay(idx: int, s: int):
            if idx < len(nums):
                if (idx, s) in self.memo.keys():
                    return self.memo[(idx, s)]
                a = targetSumWay(idx + 1, nums[idx] * -1 + s)
                b = targetSumWay(idx + 1, nums[idx] + s)
                self.memo[(idx, s)] = a + b
                return self.memo[(idx, s)]
            else:
                return 1 if S == s else 0
        return targetSumWay(0, 0)
class Solution:
    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        self.memo = {}

        def targetSumWay(idx: int, s: int):
            if idx < len(nums):
                v1, v2 = nums[idx] * -1 + s, nums[idx] + s
                a = self.memo[(idx + 1, v1)] if (idx + 1, v1) in self.memo.keys() else targetSumWay(idx + 1, v1)
                b = self.memo[(idx + 1, v2)] if (idx + 1, v2) in self.memo.keys() else targetSumWay(idx + 1, v2)
                self.memo[(idx, s)] = a + b
                return self.memo[(idx, s)]
            else:
                return 1 if S == s else 0

        return targetSumWay(0, 0)
hon9g commented 4 years ago

Binary Tree Inorder Traversal

Recursive DFS

hon9g commented 4 years ago

Q1. Largest Rectangle in Histogram

hon9g commented 4 years ago

Q2. Binary Search Tree Iterator

hon9g commented 4 years ago

Q3. Asteroid Collision

hon9g commented 4 years ago

hon9g commented 4 years ago

hon9g commented 4 years ago