<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aurora on Medium]]></title>
        <description><![CDATA[Stories by Aurora on Medium]]></description>
        <link>https://medium.com/@hzpang?source=rss-e0f59fd11985------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PwkkgZ2xeStFw4Pnpp_qLw.jpeg</url>
            <title>Stories by Aurora on Medium</title>
            <link>https://medium.com/@hzpang?source=rss-e0f59fd11985------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:21:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hzpang/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[Graph Algo 7] Shortest Path]]></title>
            <link>https://medium.com/@hzpang/graph-algo-7-shortest-path-3fb6d9d1f5e2?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fb6d9d1f5e2</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 14:24:50 GMT</pubDate>
            <atom:updated>2025-11-13T14:24:50.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dijkstra’s Algorithm</h3><p>Purpose: Finds the shortest path from a source node to all other nodes in a weighted graph (with non-negative weights).</p><p>How it works:</p><ol><li>Initialize distances to all nodes as infinity, except the <strong>start node (0)</strong></li><li>Use a <strong>min-heap to always process the node with smallest distance</strong> first</li><li><strong>For each node, relax (update) distances to its neighbors</strong></li><li>Skip nodes that have already been processed</li><li>Continue until heap is empty</li></ol><p>Time Complexity: O((V + E) log V) where V = vertices, E = edges</p><pre>from heapq import heappush, heappop<br>from typing import List<br>from math import inf<br><br>def shortestPathDijkstra(n: int, edges: List[List[int]], start: int) -&gt; List[int]:<br>    &quot;&quot;&quot;<br>    Find shortest path from start node to all other nodes using Dijkstra&#39;s algorithm.<br>    <br>    Args:<br>        n: Number of nodes<br>        edges: List of [source, destination, weight]<br>        start: Starting node<br>        <br>    Returns:<br>        List of shortest distances from start to each node<br>    &quot;&quot;&quot;<br>    # Build adjacency list representation<br>    g = [[] for _ in range(n)]<br>    for x, y, wt in edges:<br>        g[x].append((y, wt))<br>    <br>    # Initialize distances<br>    dis = [inf] * n<br>    dis[start] = 0  # Distance from start to itself is 0<br>    <br>    # Min-heap: (distance_to_node, node)<br>    h = [(0, start)]<br>    <br>    while h:<br>        dis_x, x = heappop(h)<br>        <br>        # Skip if this node was already processed<br>        if dis_x &gt; dis[x]:<br>            continue<br>        <br>        # Relax edges to neighbors<br>        for y, wt in g[x]:<br>            new_dis_y = dis_x + wt<br>            if new_dis_y &lt; dis[y]:<br>                dis[y] = new_dis_y  # Update shortest distance<br>                heappush(h, (new_dis_y, y))<br>    <br>    return dis</pre><h3>Prim’s Algorithm</h3><p>Purpose: Finds a Minimum Spanning Tree (MST) — connects all nodes with minimum total edge weight.</p><p>How it works:</p><ol><li>Start from any node (usually node 0)</li><li>Mark it as visited and<strong> add all its edges to a min-heap</strong></li><li>Always <strong>pick the smallest edge that connects to an unvisited node</strong></li><li>Mark that new node as visited and add all its edges to unvisited nodes</li><li>Repeat until all nodes are visited</li></ol><p>Time Complexity: O(E log V) where E = edges, V = vertices</p><pre>from heapq import heappush, heappop<br>from typing import List<br>from math import inf<br><br>def primsAlgorithm(n: int, edges: List[List[int]]) -&gt; int:<br>    &quot;&quot;&quot;<br>    Find Minimum Spanning Tree using Prim&#39;s algorithm.<br>    <br>    Args:<br>        n: Number of nodes<br>        edges: List of [node1, node2, weight]<br>        <br>    Returns:<br>        Total weight of MST<br>    &quot;&quot;&quot;<br>    # Build adjacency list<br>    g = [[] for _ in range(n)]<br>    for x, y, wt in edges:<br>        g[x].append((y, wt))<br>        g[y].append((x, wt))  # Undirected graph<br>    <br>    # Track visited nodes<br>    visited = [False] * n<br>    <br>    # Min-heap: (weight, node)<br>    h = [(0, 0)]  # Start from node 0<br>    mst_weight = 0<br>    <br>    while h:<br>        wt, node = heappop(h)<br>        <br>        # Skip if already visited<br>        if visited[node]:<br>            continue<br>        <br>        visited[node] = True<br>        mst_weight += wt<br>        <br>        # Add all edges from current node to unvisited neighbors<br>        for neighbor, edge_wt in g[node]:<br>            if not visited[neighbor]:<br>                heappush(h, (edge_wt, neighbor))<br>    <br>    return mst_weight</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fb6d9d1f5e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Graph Algo 6] Cycle Detection]]></title>
            <link>https://medium.com/@hzpang/graph-algo-series-5-cycle-detection-f25f986ac206?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/f25f986ac206</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 13:46:22 GMT</pubDate>
            <atom:updated>2025-11-12T12:34:40.650Z</atom:updated>
            <content:encoded><![CDATA[<h3>For Undirected Graphs</h3><h3>1. DFS (Depth-First Search)</h3><p>The most common approach — detect a back edge during DFS traversal.</p><pre>def hasCycle_undirected(graph, n):<br>    &quot;&quot;&quot;<br>    Returns True if cycle exists in undirected graph<br>    graph: adjacency list representation<br>    n: number of vertices<br>    &quot;&quot;&quot;<br>    visited = [False] * n<br>    <br>    def dfs(node, parent):<br>        visited[node] = True<br>        <br>        for neighbor in graph[node]:<br>            if not visited[neighbor]:<br>                if dfs(neighbor, node):<br>                    return True<br>            elif neighbor != parent:  # Back edge found<br>                return True<br>        <br>        return False<br>    <br>    # Check all components (graph might be disconnected)<br>    for i in range(n):<br>        if not visited[i]:<br>            if dfs(i, -1):<br>                return True<br>    <br>    return False</pre><pre># Example usage:<br>graph = {<br>    0: [1, 2],<br>    1: [0, 2],<br>    2: [0, 1, 3],<br>    3: [2]<br>}<br>print(hasCycle_undirected(graph, 4))  # Output: True</pre><p>Time Complexity: O(V + E)<br>Space Complexity: O(V)</p><p>Logic: During DFS, if we visit an already-visited node that’s not the parent, it’s a back edge = cycle exists.</p><h3>2. Union-Find (Disjoint Set Union)</h3><p>Efficient for undirected graphs, especially in Kruskal’s algorithm context.</p><pre>class UnionFind:<br>    def __init__(self, n):<br>        self.parent = list(range(n))<br>        self.rank = [0] * n<br>    <br>    def find(self, x):<br>        if self.parent[x] != x:<br>            self.parent[x] = self.find(self.parent[x])  # Path compression<br>        return self.parent[x]<br>    <br>    def union(self, x, y):<br>        root_x, root_y = self.find(x), self.find(y)<br>        <br>        if root_x == root_y:<br>            return False  # Already in same set - cycle detected<br>        <br>        # Union by rank<br>        if self.rank[root_x] &lt; self.rank[root_y]:<br>            self.parent[root_x] = root_y<br>        elif self.rank[root_x] &gt; self.rank[root_y]:<br>            self.parent[root_y] = root_x<br>        else:<br>            self.parent[root_y] = root_x<br>            self.rank[root_x] += 1<br>        <br>        return True</pre><pre>def hasCycle_unionfind(edges, n):<br>    uf = UnionFind(n)<br>    <br>    for u, v in edges:<br>        if not uf.union(u, v):<br>            return True  # Cycle detected<br>    <br>    return False</pre><pre># Example:<br>edges = [(0, 1), (1, 2), (2, 0), (2, 3)]<br>print(hasCycle_unionfind(edges, 4))  # Output: True</pre><p>Time Complexity: O(E × α(n)) where α is inverse Ackermann (nearly constant)<br>Space Complexity: O(V)</p><h3>For Directed Graphs</h3><h3>1. DFS with Color Coding (Most Common)</h3><p>Uses three states: White (unvisited), Gray (in current path), Black (finished).</p><pre>def hasCycle_directed(graph, n):<br>    &quot;&quot;&quot;<br>    Returns True if cycle exists in directed graph<br>    graph: adjacency list representation<br>    n: number of vertices<br>    &quot;&quot;&quot;<br>    # Colors: 0 = white, 1 = gray, 2 = black<br>    color = [0] * n<br>    <br>    def dfs(node):<br>        if color[node] == 1:  # Gray node - back edge found<br>            return True<br>        if color[node] == 2:  # Black node - already processed<br>            return False<br>        <br>        color[node] = 1  # Mark as gray (in current path)<br>        <br>        for neighbor in graph.get(node, []):<br>            if dfs(neighbor):<br>                return True<br>        <br>        color[node] = 2  # Mark as black (finished)<br>        return False<br>    <br>    for i in range(n):<br>        if color[i] == 0:  # Unvisited node<br>            if dfs(i):<br>                return True<br>    <br>    return False</pre><pre># Example:<br>graph = {<br>    0: [1],<br>    1: [2],<br>    2: [0, 3],<br>    3: []<br>}<br>print(hasCycle_directed(graph, 4))  # Output: True (0→1→2→0)</pre><p>Time Complexity: O(V + E)<br>Space Complexity: O(V)</p><p>Logic: If we encounter a gray node, it means we’ve found a back edge (cycle).</p><h3>2. DFS with Recursion Stack</h3><p>Similar to color coding but uses explicit stack tracking.</p><pre>def hasCycle_directed_v2(graph, n):<br>    visited = [False] * n<br>    rec_stack = [False] * n<br>    <br>    def dfs(node):<br>        visited[node] = True<br>        rec_stack[node] = True<br>        <br>        for neighbor in graph.get(node, []):<br>            if not visited[neighbor]:<br>                if dfs(neighbor):<br>                    return True<br>            elif rec_stack[neighbor]:  # Back edge<br>                return True<br>        <br>        rec_stack[node] = False<br>        return False<br>    <br>    for i in range(n):<br>        if not visited[i]:<br>            if dfs(i):<br>                return True<br>    <br>    return False</pre><h3>3. Topological Sort (Kahn’s Algorithm)</h3><p>Uses in-degree counting. If we can’t process all vertices, cycle exists.</p><p>Typical usage: when we need different processing for nodes in the cycle vs nodes outside of the cycle.</p><pre>from collections import deque</pre><pre>def hasCycle_topological(graph, n):<br>    in_degree = [0] * n<br>    adj_list = [[] for _ in range(n)]<br>    <br>    # Build adjacency list and in-degrees<br>    for u in graph:<br>        for v in graph[u]:<br>            adj_list[u].append(v)<br>            in_degree[v] += 1<br>    <br>    queue = deque([i for i in range(n) if in_degree[i] == 0])<br>    processed = 0<br>    <br>    while queue:<br>        node = queue.popleft()<br>        processed += 1<br>        <br>        for neighbor in adj_list[node]:<br>            in_degree[neighbor] -= 1<br>            if in_degree[neighbor] == 0:<br>                queue.append(neighbor)<br>    <br>    return processed != n  # If not all vertices processed, cycle exists</pre><pre># Example:<br>graph = {0: [1], 1: [2], 2: [0]}<br>print(hasCycle_topological(graph, 3))  # Output: True</pre><p>Time Complexity: O(V + E)<br>Space Complexity: O(V)</p><h3>Why the Same `Visited` Approach Doesn’t work for Directed Graph?</h3><pre>Directed Graph:<br>    0 → 1 → 2<br>    ↓<br>    3 → 2<br><br>Adjacency list:<br>{0: [1, 3], 1: [2], 2: [], 3: [2]}</pre><p>If we trace with the simple visit method for undirected graph:</p><pre>DFS(0): visited[0] = True<br>  → DFS(1): visited[1] = True<br>    → DFS(2): visited[2] = True<br>      (no neighbors)<br>    (backtrack to 1)<br>  → neighbor 3: not visited<br>    → DFS(3): visited[3] = True<br>      → neighbor 2: VISITED!<br>      ❌ Returns True (FALSE CYCLE DETECTED!)<br><br>RESULT: Says cycle exists ❌ (WRONG!)</pre><p>But the graph actually has NO cycle! We can traverse: 0→1→2 and 0→3→2. Node 2 is just reachable from multiple paths.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f25f986ac206" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Graph Algo 5] Topological Sort]]></title>
            <link>https://medium.com/@hzpang/graph-algo-5-topological-sort-2e6063cadd4b?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6063cadd4b</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[topological-sort]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 12:04:24 GMT</pubDate>
            <atom:updated>2025-11-09T12:04:24.882Z</atom:updated>
            <content:encoded><![CDATA[<p>Topological Sort is a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge (u, v), vertex ucomes before vertex v in the ordering.</p><pre>Example DAG:<br>    1 → 2<br>    ↓   ↓<br>    3 → 4<br><br>Valid Topological Orders: [1,2,3,4], [1,3,2,4], [1,3,4,2]</pre><ul><li>Graph must be acyclic (no cycles)</li><li>Only defined for directed graphs</li><li>Multiple valid orderings may exist</li></ul><h3>Algorithm 1: Kahn’s Algorithm (BFS-based)</h3><p>Core Concept: Remove nodes with zero in-degree</p><pre>from collections import deque<br><br>def topological_sort_kahn(n: int, edges: List[List[int]]) -&gt; List[int]:<br>    &quot;&quot;&quot;<br>    Kahn&#39;s Algorithm: Iteratively remove nodes with in-degree 0<br>    <br>    Args:<br>        n: Number of nodes (0 to n-1)<br>        edges: List of directed edges [u, v]<br>    <br>    Returns:<br>        Topological order, or empty list if cycle exists<br>    &quot;&quot;&quot;<br>    # Step 1: Build adjacency list and calculate in-degrees<br>    graph = [[] for _ in range(n)]<br>    in_degree = [0] * n<br>    <br>    for u, v in edges:<br>        graph[u].append(v)<br>        in_degree[v] += 1<br>    <br>    # Step 2: Initialize queue with nodes having zero in-degree<br>    queue = deque([i for i in range(n) if in_degree[i] == 0])<br>    topo_order = []<br>    <br>    # Step 3: Process nodes in order<br>    while queue:<br>        node = queue.popleft()<br>        topo_order.append(node)<br>        <br>        # Reduce in-degree of neighbors<br>        for neighbor in graph[node]:<br>            in_degree[neighbor] -= 1<br>            if in_degree[neighbor] == 0:<br>                queue.append(neighbor)<br>    <br>    # Step 4: Check for cycles<br>    if len(topo_order) != n:<br>        return []  # Cycle detected<br>    <br>    return topo_order</pre><p>Time: O(V + E) | Space: O(V + E)</p><h3>Algorithm 2: DFS-based Topological Sort</h3><p>Core Concept: Reversed post order (stack + post order).</p><pre>def topological_sort_dfs(n: int, edges: List[List[int]]) -&gt; List[int]:<br>    &quot;&quot;&quot;<br>    DFS-based: Visit nodes and add to result in reverse finish order<br>    <br>    Args:<br>        n: Number of nodes (0 to n-1)<br>        edges: List of directed edges [u, v]<br>    <br>    Returns:<br>        Topological order, or empty list if cycle exists<br>    &quot;&quot;&quot;<br>    # Build adjacency list<br>    graph = [[] for _ in range(n)]<br>    for u, v in edges:<br>        graph[u].append(v)<br>    <br>    # State: 0=unvisited, 1=visiting, 2=visited<br>    state = [0] * n<br>    topo_order = []<br>    has_cycle = False<br>    <br>    def dfs(node):<br>        nonlocal has_cycle<br>        <br>        if state[node] == 1:  # Back edge (cycle detected)<br>            has_cycle = True<br>            return<br>        <br>        if state[node] == 2:  # Already visited<br>            return<br>        <br>        state[node] = 1  # Mark as visiting<br>        <br>        for neighbor in graph[node]:<br>            dfs(neighbor)<br>            if has_cycle:<br>                return<br>        <br>        state[node] = 2  # Mark as visited<br>        topo_order.append(node)  # Add to result (post-order)<br>    <br>    # Process all nodes<br>    for i in range(n):<br>        if state[i] == 0:<br>            dfs(i)<br>            if has_cycle:<br>                return []<br>    <br>    # Reverse because we added nodes in finish order<br>    return topo_order[::-1]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6063cadd4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Graph Algo Series 4] Connected Components]]></title>
            <link>https://medium.com/@hzpang/graph-algo-series-4-connected-components-a86d1c01dad3?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/a86d1c01dad3</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 04:14:43 GMT</pubDate>
            <atom:updated>2025-11-08T04:14:56.726Z</atom:updated>
            <content:encoded><![CDATA[<p>Problem Statement: A connected component is a maximal set of nodes where every node is reachable from every other node through edges. In an undirected graph, a connected component is a subgraph where all nodes are connected.</p><pre>Example Graph:<br>    0---1        3---4<br>    |   |        |<br>    2---         5<br><br>Connected Components: {0,1,2}, {3,4,5}</pre><h3><strong>Solution 1: DFS</strong></h3><pre>def solve(n: int, edges: List[List[int]]) -&gt; List[int]:<br>    &quot;&quot;&quot;<br>    Find the size of each connected component in an undirected graph.<br>    <br>    Args:<br>        n: Number of nodes (numbered 0 to n-1)<br>        edges: List of edges [x, y]<br>    <br>    Returns:<br>        List containing the size of each connected component<br>    &quot;&quot;&quot;<br>    <br>    # Build adjacency list for undirected graph<br>    graph = [[] for _ in range(n)]<br>    for x, y in edges:<br>        graph[x].append(y)<br>        graph[y].append(x)  # Undirected graph<br>    <br>    visited = [False] * n<br>    <br>    def dfs(node: int) -&gt; int:<br>        &quot;&quot;&quot;<br>        Perform DFS to find the size of the connected component.<br>        <br>        Args:<br>            node: Current node being visited<br>        <br>        Returns:<br>            Size of connected component containing this node<br>        &quot;&quot;&quot;<br>        visited[node] = True<br>        component_size = 1<br>        <br>        # Explore all unvisited neighbors<br>        for neighbor in graph[node]:<br>            if not visited[neighbor]:<br>                component_size += dfs(neighbor)<br>        <br>        return component_size<br>    <br>    # Find all connected components<br>    component_sizes = []<br>    for i in range(n):<br>        if not visited[i]:  # Found unvisited node<br>            size = dfs(i)<br>            component_sizes.append(size)<br>    <br>    return component_sizes</pre><p>Time: O(V + E) | Space: O(V) recursion stack</p><h3><strong>Solution 2: BFS</strong></h3><pre>from collections import deque<br><br>def find_components_bfs(n: int, edges: List[List[int]]) -&gt; List[int]:<br>    graph = [[] for _ in range(n)]<br>    for x, y in edges:<br>        graph[x].append(y)<br>        graph[y].append(x)<br>    <br>    visited = [False] * n<br>    components = []<br>    <br>    def bfs(start):<br>        queue = deque([start])<br>        visited[start] = True<br>        size = 0<br>        <br>        while queue:<br>            node = queue.popleft()<br>            size += 1<br>            for neighbor in graph[node]:<br>                if not visited[neighbor]:<br>                    visited[neighbor] = True<br>                    queue.append(neighbor)<br>        <br>        return size<br>    <br>    for i in range(n):<br>        if not visited[i]:<br>            components.append(bfs(i))<br>    <br>    return components</pre><p>Time: O(V + E) | Space: O(V) queue</p><h3>Solution 3: Union-Find</h3><pre>class UnionFind:<br>    def __init__(self, n):<br>        self.parent = list(range(n))<br>        self.rank = [0] * n<br>        self.size = [1] * n<br>    <br>    def find(self, x):<br>        if self.parent[x] != x:<br>            self.parent[x] = self.find(self.parent[x])  # Path compression<br>        return self.parent[x]<br>    <br>    def union(self, x, y):<br>        root_x, root_y = self.find(x), self.find(y)<br>        if root_x == root_y:<br>            return<br>        <br>        # Union by rank<br>        if self.rank[root_x] &lt; self.rank[root_y]:<br>            root_x, root_y = root_y, root_x<br>        <br>        self.parent[root_y] = root_x<br>        self.size[root_x] += self.size[root_y]<br>        if self.rank[root_x] == self.rank[root_y]:<br>            self.rank[root_x] += 1<br><br>def find_components_uf(n: int, edges: List[List[int]]) -&gt; List[int]:<br>    uf = UnionFind(n)<br>    <br>    for x, y in edges:<br>        uf.union(x, y)<br>    <br>    # Group nodes by their root<br>    components_dict = {}<br>    for i in range(n):<br>        root = uf.find(i)<br>        components_dict[root] = components_dict.get(root, 0) + 1<br>    <br>    return list(components_dict.values())</pre><p>Time: O((V + E)α(V)) ≈ O(V + E) | Space: O(V)</p><h3>Common Variations</h3><p>Variations 1: Count number of components — UF</p><pre>def count_components(n: int, edges: List[List[int]]) -&gt; int:<br>    &quot;&quot;&quot;Return the total number of connected components&quot;&quot;&quot;<br>    uf = UnionFind(n)<br>    for x, y in edges:<br>        uf.union(x, y)<br>    <br>    return len(set(uf.find(i) for i in range(n)))</pre><p>Variations 2: Finding Strongly Connected Components (Directed Graph)</p><pre>def strongly_connected_components(n: int, edges: List[List[int]]) -&gt; List[List[int]]:<br>    &quot;&quot;&quot;Find SCCs using Kosaraju&#39;s algorithm&quot;&quot;&quot;<br>    graph = [[] for _ in range(n)]<br>    reverse_graph = [[] for _ in range(n)]<br>    <br>    for x, y in edges:<br>        graph[x].append(y)<br>        reverse_graph[y].append(x)<br>    <br>    visited = [False] * n<br>    finish_order = []<br>    <br>    # First DFS to get finish order<br>    def dfs1(node):<br>        visited[node] = True<br>        for neighbor in graph[node]:<br>            if not visited[neighbor]:<br>                dfs1(neighbor)<br>        finish_order.append(node)<br>    <br>    for i in range(n):<br>        if not visited[i]:<br>            dfs1(i)<br>    <br>    # Second DFS on reverse graph in reverse finish order<br>    visited = [False] * n<br>    sccs = []<br>    <br>    def dfs2(node, scc):<br>        visited[node] = True<br>        scc.append(node)<br>        for neighbor in reverse_graph[node]:<br>            if not visited[neighbor]:<br>                dfs2(neighbor, scc)<br>    <br>    for node in reversed(finish_order):<br>        if not visited[node]:<br>            scc = []<br>            dfs2(node, scc)<br>            sccs.append(scc)<br>    <br>    return sccs</pre><p>Variations 3: Minimum Edges to add to achieve full connections — UF</p><pre>def min_edges_to_connect(n: int, edges: List[List[int]]) -&gt; int:<br>    &quot;&quot;&quot;<br>    Find minimum edges needed to connect all components.<br>    If there are k components, need k-1 edges.<br>    &quot;&quot;&quot;<br>    uf = UnionFind(n)<br>    for x, y in edges:<br>        uf.union(x, y)<br>    <br>    num_components = len(set(uf.find(i) for i in range(n)))<br>    return num_components - 1</pre><p>Variations 4: # of Redundant Edges — UF</p><pre>def find_redundant_connection(n: int, edges: List[List[int]]) -&gt; List[int]:<br>    &quot;&quot;&quot;<br>    Find an edge that creates a cycle (tree with one extra edge).<br>    Returns the last edge that creates a cycle.<br>    &quot;&quot;&quot;<br>    uf = UnionFind(n)<br>    <br>    for x, y in edges:<br>        if uf.find(x) == uf.find(y):<br>            return [x, y]  # This edge creates a cycle<br>        uf.union(x, y)<br>    <br>    return []</pre><p>Variations 5: Bipartite — DFS</p><pre>def is_bipartite(n: int, edges: List[List[int]]) -&gt; bool:<br>    &quot;&quot;&quot;Check if graph is bipartite (2-colorable)&quot;&quot;&quot;<br>    graph = [[] for _ in range(n)]<br>    for x, y in edges:<br>        graph[x].append(y)<br>        graph[y].append(x)<br>    <br>    color = [-1] * n  # -1: unvisited, 0/1: colors<br>    <br>    def dfs(node, c):<br>        color[node] = c<br>        for neighbor in graph[node]:<br>            if color[neighbor] == -1:<br>                if not dfs(neighbor, 1 - c):<br>                    return False<br>            elif color[neighbor] == c:<br>                return False<br>        return True<br>    <br>    for i in range(n):<br>        if color[i] == -1:<br>            if not dfs(i, 0):<br>                return False<br>    <br>    return True</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a86d1c01dad3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Binary Indexed Tree]]></title>
            <link>https://medium.com/@hzpang/understanding-binary-indexed-tree-724b3ab978df?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/724b3ab978df</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[binary-indexed-tree]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Thu, 23 May 2024 12:39:57 GMT</pubDate>
            <atom:updated>2024-05-23T12:39:57.288Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding All About Binary Indexed Tree</h3><h3>Why BIT?</h3><blockquote>Given an array arr[0 . . . n-1]. <br><strong>Question: </strong>Dynamically calculate the sum of subset of the array. Two operations, sum() and add(). sum(7): get the sum of numbers from index 1 to 7; add(4, 10): increase the number at index 4 by 10 (from -3 to 7).</blockquote><p><strong>O(n) + O(1) Solution</strong><br>[Option 1] <br>sum(): Run a loop from 0 to i-1 and calculate the sum of the elements. O(n)<br>add(): Simply do arr[i] = x. O(1)</p><p>[Option 2] <br>sum(): prefix sum: create an extra array and store the sum of the first i-th elements at the i-th index in this new array. O(1). <br>add(): Updating an element requires propagating the update further down the prefix sum array. O(n)</p><p>When add() is much more frequent, use [Option 1]. When sum() is much more frequent, use [Option 2].</p><p><strong>O(log n)+O(log n) Solution</strong></p><ul><li>Segment tree</li><li>Binary Indexed Tree (BIT). <em>less space and is easier to implement.</em></li></ul><h3>Segment Tree</h3><p>An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index <strong>(2*i+1)</strong>, right child at <strong>(2*i+2)</strong> and the parent is at <strong>(⌊(i — 1) / 2⌋)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*9Krzy-ztPqJqvij0.png" /></figure><h3>BIT</h3><h4>Important Operations</h4><ul><li>To find the children of a parent node, do i -= i &amp; -i;</li><li>To find the parent of a child node, do i += i &amp; -i.</li></ul><h4>(i &amp; -i) → 2&#39;s Complement</h4><ul><li>Step 1: starting with the absolute binary representation of the number, with the leading bit being a sign bit;</li><li>Step 2: inverting (or flipping) all bits — changing every 0 to 1, and every 1 to 0;</li><li>Step 3: adding 1 to the entire inverted number, ignoring any <a href="https://en.wikipedia.org/wiki/Integer_overflow">overflow</a>. Accounting for overflow will produce the wrong value for the result.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7JxeR_OTMPCY47OEankjw.png" /></figure><h4>BIT Application: Sum and Add</h4><p>Note that the two screenshots are of different examples but the same concept.</p><p>Definition of sum(7): get the sum of numbers from index 1 to 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wU1mj65nc7Rs4iHqupoVzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*4ukCBa_fENthRkkY.png" /></figure><p>Definition of add(4, 10): increase the number at index 4 by 10 (from -3 to 7).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLm8RRr7OjFJwYUJoROujA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*DSdjAREmOZbyEcGm.png" /></figure><h3>References</h3><ul><li><a href="https://www.geeksforgeeks.org/segment-tree-sum-of-given-range/">Segment Tree | Sum of given range - GeeksforGeeks</a></li><li><a href="https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/">Binary Indexed Tree or Fenwick Tree - GeeksforGeeks</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuSFzHCZ4E-8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuSFzHCZ4E-8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuSFzHCZ4E-8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b587f25b869f2858575bbf9783440a6f/href">https://medium.com/media/b587f25b869f2858575bbf9783440a6f/href</a></iframe><p><a href="https://en.wikipedia.org/wiki/Two%27s_complement">https://en.wikipedia.org/wiki/Two%27s_complement</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=724b3ab978df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(Union-Find, GCD) LeetCode Practice D40]]></title>
            <link>https://medium.com/@hzpang/union-find-gcd-leetcode-practice-d40-0a332640ab97?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a332640ab97</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[union-find]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[gcd]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Mon, 20 May 2024 14:34:54 GMT</pubDate>
            <atom:updated>2024-05-20T14:34:54.532Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/gcd-sort-of-an-array/description/">Leetcode question</a></p><p>It is obvious that the problem is asking to cluster the numbers in the array, such that numbers in the cluster have at least one gcd &gt; 1 with the other elements. Union-find is the best use case for it.</p><p>A quick recap: for union-find, there are two steps: (1) union, (2) find. Usually we start with an array arr[i] = i to denote each element is its own root (solution 1). Or we start with arr[i] = 0 to denote numbers that haven’t been processed (solution 2).</p><p>Time complexity: O(N²) — to return the fully sorted array, naive. Usually when an algorithm asks for boolean return, but your solution digs into every details (such as elaborating on a per cases basis), then it is considered a brute force solution.</p><pre>class Solution {<br>    public boolean gcdSort(int[] nums) {<br>        Map&lt;Integer, PriorityQueue&lt;Integer&gt;&gt; pqs = new HashMap&lt;Integer, PriorityQueue&lt;Integer&gt;&gt;();<br>        int[] uf = new int[nums.length];<br>        for(int i = 0; i &lt; nums.length; i ++) uf[i] = i;<br>        for(int i = 0; i &lt; nums.length; i ++) {<br>            for(int j = i; j &lt; nums.length; j ++) {<br>                if(gcd(nums[i], nums[j]) &gt; 1) union(uf, i, j);<br>            }<br>        }<br>        uniqueClusterIndex(pqs, uf, nums);<br>        // Arrays.stream(uf).forEach(System.out::println); // debug<br>        int lastPolled = Integer.MIN_VALUE;<br>        for(int i = 0; i &lt; nums.length; i ++) {<br>            int curPolled = pqs.get(uf[i]).poll();<br>            if(curPolled &gt;= lastPolled) lastPolled = curPolled;<br>            else return false;<br>        }<br>        return true;<br>    }<br><br>    private int gcd(int a, int b) {<br>        if(b == 0) return a;<br>        return gcd(b, a % b);<br>    }<br><br>    private void union(int[] uf, int a, int b) {<br>        uf[find(uf, b)] = find(uf, a);<br>    }<br><br>    private int find(int[] uf, int a) {<br>        if(uf[a] == a) return a;<br>        uf[a] = find(uf, uf[a]); // path compression<br>        return uf[a];<br>    }<br><br>    private void uniqueClusterIndex(Map&lt;Integer, PriorityQueue&lt;Integer&gt;&gt; pqs, int[] uf, int[] nums) {<br>        for(int i = 0; i &lt; nums.length; i ++) find(uf, i); // Ensure path compression.<br>        for(int i: Arrays.stream(uf).distinct().toArray()) pqs.put(i, new PriorityQueue());<br>        for(int i = 0; i &lt; nums.length; i ++) pqs.get(uf[i]).offer(nums[i]);<br>    }<br>}</pre><p>Time complexity: O(NlogN) — to return just the boolean result.</p><pre>class Solution {<br>    <br>    public boolean gcdSort(int[] nums) {<br>        for(int x: nums) {<br>            int y = x;<br>            for(int p=2; UF[y]==0 &amp;&amp; p*p&lt;=y; ++p) {<br>                if (y % p == 0) {<br>                    union(x, p);<br>                    while(y % p == 0) y /= p;<br>                }<br>            }<br>            if (y!=1) union(x, y);<br>        }<br>        int[] copy = nums.clone();<br>        Arrays.sort(copy);<br>        for(int i=0; i&lt;nums.length; i++) {<br>            if (find(nums[i])!=find(copy[i])) return false;<br>        }<br>        return true;<br>    }<br>    <br>    private int[] UF = new int[100001];<br>    <br>    private int find(int x) {<br>        if (UF[x]==0) return UF[x]=x;<br>        return UF[x]==x? x: (UF[x]=find(UF[x]));<br>    }<br>    <br>    private void union(int x, int y) {<br>        UF[find(x)] = UF[find(y)];<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a332640ab97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Array] Common Algorithms Summary with Leetcode]]></title>
            <link>https://medium.com/@hzpang/array-common-algorithms-summary-with-leetcode-b476243796c8?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/b476243796c8</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Sun, 19 May 2024 12:09:48 GMT</pubDate>
            <atom:updated>2024-05-20T14:16:12.855Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Array] Common Algorithms Summary with Leetcode Links</h3><ol><li>Binary Search (<a href="https://leetcode.com/problems/binary-search/">leetcode</a>)</li></ol><pre>public int search(int[] nums, int target) {<br>    int left = 0, right = nums.length - 1, mid = (right + left) / 2;<br>    while (left &lt;= right) {<br>        if (nums[mid] == target) return mid;<br>        if (nums[mid] &lt; target) {<br>            left = mid + 1;<br>        } else {<br>            right = mid - 1;<br>        }<br>        mid = (left + right) / 2;<br>    }<br>    return -1;<br>}</pre><p>2. Prefix Sum</p><p>3. Two Pointers (<a href="https://leetcode.com/problems/squares-of-a-sorted-array/description/">leetcode</a>): (1) start from `0` and `arr.length — 1` and (2) start from some point in the middle (3) sliding window.</p><ul><li>Examples: mix of Neg and Pos Numbers, sub array (<a href="https://leetcode.com/problems/minimum-size-subarray-sum/">leetcode</a>)</li></ul><pre>public int minSubArrayLen(int target, int[] nums) {<br>    int[] prefixSum = new int[nums.length + 1];<br>    for(int i = 1; i &lt; nums.length + 1; i ++) {<br>        prefixSum[i] = nums[i - 1] + prefixSum[i - 1];<br>    }<br>    int left = 0, right = 1, minLen = nums.length + 1;<br>    while (right &lt; nums.length + 1) {<br>        if (prefixSum[right] - prefixSum[left] &gt;= target) {<br>            minLen = Math.min(minLen, right - left);<br>            if(minLen == 1) return minLen;<br>            left ++;<br>        } else right ++;<br>    }<br>    return minLen == nums.length + 1 ? 0 : minLen;<br>}</pre><p>4. Sorting: in-place and stable: bucket sort (bit manipulation), merge sort, quick sort, insertion, bubble, selection, heap sort… (<a href="https://www.geeksforgeeks.org/sorting-algorithms/">GfG</a>)</p><p>Default ordering: ascending</p><pre>Arrays.sort(a, Collections.reverseOrder());<br>Arrays.sort(twoDim, Comparator.comparingInt(a -&gt; a[0]).reversed());<br>Arrays.sort(months, (String a, String b) -&gt; a.length() - b.length());</pre><p>5. Error prone</p><ul><li>Index vs arr[index]</li><li>Edge cases: array empty?</li><li>Whenever there is a loop and index delta: always check for 0, length — 1, and i &lt; j (two pointers);</li><li>What if the pointer in the loop didn’t move at all?</li><li>Index checking and manipulation</li></ul><p>Example question: <a href="http://1. index vs arr[index] 2. edge cases: array empty?  3. array index: always check for 0 and length - 1 after update  4. what if the pointer doesn&#39;t move at all">leetcode</a></p><pre>class Solution {<br>    public int removeElement(int[] nums, int val) {<br>        int k = nums.length - 1;<br>        for(int i = 0; i &lt; k; i ++) {<br>            while(nums[i] == val &amp;&amp; k &gt;= 0 &amp;&amp; i &lt; k) exchange(nums, i, k --);<br>        }<br>        if(k &lt; 0) return 0;<br>        return nums[k] == val ? k : k + 1;<br>    }<br><br>    private void exchange(int[] nums, int a, int b) {<br>        int temp = nums[a];<br>        nums[a] = nums[b];<br>        nums[b] = temp;<br>    }<br>}</pre><p>2D array: directions and edge check (<a href="https://leetcode.com/problems/spiral-matrix-ii/description/">leetcode</a>).</p><pre>public int[][] generateMatrix(int n) {<br>    int[][] result = new int[n][n];<br>    int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};<br>    int i = 0, j = -1, num = 1, dir = 0;<br><br>    while(num &lt;= n * n) {<br>        int[] nextDir = directions[dir % 4];<br>        do {<br>            i += nextDir[0];<br>            j += nextDir[1];<br>            result[i][j] = num;<br>            num ++;<br>        } while (i + nextDir[0] &gt;= 0 &amp;&amp; i + nextDir[0] &lt; n &amp;&amp; j + nextDir[1] &gt;= 0 &amp;&amp; j + nextDir[1] &lt; n &amp;&amp; result[i + nextDir[0]][j + nextDir[1]] == 0);<br>        dir ++;<br>    }<br>    return result;<br>}</pre><h3><strong>Slightly More Advanced</strong></h3><p>6. Monoqueue</p><p><a href="https://www.geeksforgeeks.org/meet-in-the-middle/">7. Meet in the Middle</a> (<a href="https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/solutions/1513432/java-bitmask-treeset/">leetcode</a> — with bit manipulation)</p><p>8. Stream Arrays.stream(arr)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b476243796c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[DP, Array] LeetCode Practice D39 (Q53)]]></title>
            <link>https://medium.com/@hzpang/dp-array-leetcode-practice-d39-q53-e0deaa445a94?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0deaa445a94</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 13:41:03 GMT</pubDate>
            <atom:updated>2024-04-24T13:41:03.763Z</atom:updated>
            <content:encoded><![CDATA[<h3>[DP] LeetCode Practice D39 (Q53)</h3><p><a href="https://leetcode.com/problems/maximum-subarray/">Maximum Subarray</a></p><blockquote>Given an integer array nums, find the</blockquote><blockquote>subarray</blockquote><blockquote>with the largest sum, and return <em>its sum</em>.</blockquote><blockquote><strong>Example 1:</strong></blockquote><blockquote>Input: nums = [-2,1,-3,4,-1,2,1,-5,4]<br>Output: 6<br>Explanation: The subarray [4,-1,2,1] has the largest sum 6.</blockquote><blockquote><strong>Example 2:</strong></blockquote><blockquote>Input: nums = [1]<br>Output: 1<br>Explanation: The subarray [1] has the largest sum 1.</blockquote><blockquote><strong>Example 3:</strong></blockquote><blockquote>Input: nums = [5,4,-1,7,8]<br>Output: 23<br>Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.</blockquote><h3>Thinking Process</h3><p>TL;DR of the solution: reset local max when it is ≤ 0, since less than 0 is not useful for max sum at all. Otherwise, it can continue to add on the next elements and grow.</p><p>This problem can ask for 2 things:</p><ol><li>return sum (this is what it is actually asking)</li><li>return start + end point index. E.g. for example 3, return index = 0 and index = 4.</li></ol><p>The 1st usually has a time complexity of O(n), while the second can be more complex. As this question is asking for the 1st, we can already eliminate algorithm such as sorting (O(logn)).</p><p>Thoughts 1: positive and negative numbers can be collapsed, i.e. [5,6,-1,-2] is equivalent to [11, -3].</p><p>Thoughts 2: As long as the sum of numbers before the current index is positive, we can add it up with the number in the current index, as it will always be larger. I.e. [11, -3, 5] -&gt; [8, 5] -&gt; [13].</p><p>Thoughts 3: edge cases? There are several examples we should try:</p><p>[1], [-1], all positive, all negative, mixed positive and negatives.</p><pre>class Solution {<br>    public int maxSubArray(int[] nums) {<br>        int globalMax = nums[0], localMax = nums[0];<br>        for(int i = 1; i &lt; nums.length; i ++) {<br>            if(localMax &lt;= 0) localMax = nums[i];<br>            else localMax += nums[i];   <br>            globalMax = Math.max(localMax, globalMax);<br>        }<br>        return globalMax;<br>    }<br>}</pre><h3>Bonus</h3><p>If the array is all positive or all negative numbers, another algorithm is to do it with prefix sum + finding the max difference between the prefix sum array.</p><p>Thoughts 1: Scan through the array with one pointer. The important thing is to decide on the start and end index of the max sub array. We cannot simply stop when sum + end pointer has a drop, since it may rise again later.</p><p>Thoughts 2: Prefix sum array and use a[i] — a[j] to check what is the best i, j here. O(n²), not good enough -&gt; optimize?</p><p>Thoughts 3: Find min and max of prefix array will help us with finding the maximum difference. But if the index of min is larger than max (i.e. i &lt; j and a[i] &gt; a[j]), it is not useful for the solution.</p><p>Thoughts 4: How to fix the sequence issue? How about having two pointers, one start from left to find min, another one start from right to find max. But in this case, we may miss some cases in the middle as we don’t know when to move the left or the right pointer.</p><p>Thoughts 5: Create two arrays, one is left min, the other one is right max. Get a maxdiff by array A — array B. Though note that there’s edge case of an array only having a single element such as [1].</p><p>End result:</p><pre><br>class Solution {<br>    public int maxSubArray(int[] nums) {<br>        if(nums.length == 0) return 0;<br><br>        int[] sumArray = new int[nums.length];<br>        sumArray[0] = nums[0];<br>        for(int i = 1; i &lt; nums.length; i ++) {<br>            sumArray[i] = sumArray[i - 1] + nums[i];<br>        }<br><br>        int[] minArray = new int[nums.length];<br>        int[] maxArray = new int[nums.length];<br>        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;<br>        for(int i = 0; i &lt; sumArray.length; i ++) {<br>            min = Math.min(min, sumArray[i]);<br>            max = Math.max(max, sumArray[nums.length - 1 - i]);<br>            minArray[i] = min;<br>            maxArray[i] = max;<br>        }<br><br>        int maxDiff = max;<br>        for(int i = 0; i &lt; nums.length; i ++) {<br>            if(maxArray[i] == minArray[i] &amp;&amp; maxArray[i] == nums[i]) {<br>                maxDiff = Math.max(nums[i], maxDiff);<br>            } else {<br>                maxDiff = Math.max(maxArray[i] - minArray[i], maxDiff);<br>            }<br>        }<br>        return maxDiff;<br>    }<br>}</pre><h3>Takeaway</h3><p>Prefix sum + find diff only works for all +ve or all -ve numbers. If it is a mix of +ve and -ve, use DP with resetting local max.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0deaa445a94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Graph, Hamiltonian, DFS, Backtracking] LeetCode Practice D38]]></title>
            <link>https://medium.com/@hzpang/graph-hamiltonian-dfs-backtracking-leetcode-practice-d38-6d714fbbce3f?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d714fbbce3f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 14:34:10 GMT</pubDate>
            <atom:updated>2023-06-13T14:34:10.773Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/unique-paths-iii/solutions/1535158/python-backtracking-easy-to-understand-with-explanation/">Unique Paths III</a> [Hard]</p><p>Problem Statement:</p><blockquote>You are given an m x n integer array grid where grid[i][j] could be:</blockquote><blockquote>1 representing the starting square. There is exactly one starting square.</blockquote><blockquote>2 representing the ending square. There is exactly one ending square.</blockquote><blockquote>0 representing empty squares we can walk over.</blockquote><blockquote>-1 representing obstacles that we cannot walk over.</blockquote><blockquote>Return <em>the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once</em>.</blockquote><blockquote><strong>Example 1:</strong></blockquote><blockquote>Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]<br>Output: 2<br>Explanation: We have the following two paths: <br>1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)<br>2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)</blockquote><blockquote><strong>Constraints:</strong></blockquote><blockquote>m == grid.length</blockquote><blockquote>n == grid[i].length</blockquote><blockquote>1 &lt;= m, n &lt;= 20</blockquote><blockquote>1 &lt;= m * n &lt;= 20</blockquote><blockquote>-1 &lt;= grid[i][j] &lt;= 2</blockquote><blockquote>There is exactly one starting cell and one ending cell.</blockquote><h3>BackTracking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*u8SaT56VpgRCb9Zd4PS3hA.png" /></figure><p><strong>Definition</strong></p><p>Backtracking is a recursive algorithmic technique used to solve problems by gradually constructing a solution, adding one component at a time. It involves removing any solutions that fail to meet the problem’s constraints at any given point in the process. The term “time” in this context refers to the duration elapsed until reaching a specific level in the search tree.</p><p><strong>When to Use</strong></p><ol><li><a href="https://en.wikipedia.org/wiki/Constraint_satisfaction_problem">Constraint satisfaction</a> problems that have explicit and well-defined constraints for finding a valid solution.</li><li>It involves incrementally constructing potential solutions and discarding (“backtracking”) any candidates that are determined to be incapable of forming a valid solution.</li></ol><p>However, many of the problems discussed can also be solved using alternative algorithms such as Dynamic Programming or Greedy Algorithms, with time complexities ranging from logarithmic to linear-logarithmic in relation to the input size.</p><p><strong>Algorithm Pattern</strong></p><p>A typical DFS has two parts: base + recursion.</p><p>Base case refers to the condition that determines when the search should stop and return a result. It typically represents a terminal state or a goal state.</p><p>Recursive case or the general case. In DFS, the recursive case involves exploring adjacent nodes or vertices from the current node and continuing the search recursively until reaching a base case.</p><p>Backtracking algorithms typically have the below base + recursion case:</p><pre>Base: <br>    if it is a solution:<br>        add to list of solutions<br>    if it is not: return; // Disgard<br><br>Recursion (DFS): <br>    Update tracking variables (e.g. visited[][])<br>    DFS(next data point to visit)<br>    Revert the tracking variables</pre><h3>Hamiltonian</h3><p>A Hamiltonian Path is a route within a directed or undirected graph that passes through each vertex exactly once. The problem of determining whether a graph, regardless of its directionality, contains a Hamiltonian Path is classified as NP-complete. Similarly, the task of identifying all the Hamiltonian Paths within a graph is also considered NP-complete (i.e. permutation of all nodes in the graph).</p><h3>Thinking Process</h3><p>The problem-solving approach for this particular problem is fairly simple; I would classify it as a medium-level problem. Initially, I considered using an exhaustive depth-first search (DFS) algorithm, and after reviewing the data size limitations provided in the constraints, I am confident that this is the appropriate approach. Please refer to the code snippet below for implementation details.</p><p>As a potential enhancement to the solution, it is advisable to utilize an integer variable, such as nodeVisited, instead of a two-dimensional array (visited[][]) to keep track of visited nodes. See this <a href="https://leetcode.com/problems/unique-paths-iii/solutions/1535158/python-backtracking-easy-to-understand-with-explanation/">recommended solution</a> in leetCode.</p><p>A similar but harder problem: <a href="https://medium.com/@hzpang/graph-hard-tsp-hamiltonian-leetcode-practice-d37-30877d830d84">find the shortest superstring</a>.</p><pre>class Solution:<br>    def uniquePathsIII(self, grid: List[List[int]]) -&gt; int:<br>        if len(grid) == 0 or len(grid[0]) == 0:<br>            return 0<br>        self.count = 0<br>        start = self.getStartingSquare(grid)<br>        visited = [[False for x in range(len(grid[0]))] for y in range(len(grid))] <br>        visited[start[0]][start[1]] = True<br>        self.dfs(grid, visited, start)<br>        return self.count<br><br>    def getStartingSquare(self, grid: List[List[int]]):<br>        for i in range(len(grid)):<br>            for j in range(len(grid[0])):<br>                if grid[i][j] == 1:<br>                    return (i, j)<br>    <br>    def dfs(self, grid: List[List[int]], visited:List[List[int]], cur: Tuple[int]):<br>        i, j = cur<br>        <br>        if grid[i][j] == 2:<br>            if self.allVisited(visited, grid): <br>                self.count = self.count + 1<br>            return<br><br>        for x, y in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)):<br>            if 0 &lt;= x &lt; len(grid) and 0 &lt;= y &lt; len(grid[0]):<br>                if (not visited[x][y]) and grid[x][y] != -1:<br>                    visited[x][y] = True<br>                    self.dfs(grid, visited, (x, y))<br>                    visited[x][y] = False<br>    <br>    def allVisited(self, visited: List[List[int]], grid: List[List[int]]) -&gt; bool:<br>        for i in range(len(visited)):<br>            for j in range(len(visited[0])):<br>                if visited[i][j] == False and grid[i][j] == 0:<br>                    return False<br>        return True<br><br>        </pre><p>References:</p><p><a href="https://www.geeksforgeeks.org/introduction-to-backtracking-data-structure-and-algorithm-tutorials/">Introduction to Backtracking - Data Structure and Algorithm Tutorials - GeeksforGeeks</a></p><p><a href="https://www.hackerearth.com/practice/algorithms/graphs/hamiltonian-path/tutorial/">https://www.hackerearth.com/practice/algorithms/graphs/hamiltonian-path/tutorial/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d714fbbce3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Graph, Hard, TSP, Hamiltonian] LeetCode Practice D37]]></title>
            <link>https://medium.com/@hzpang/graph-hard-tsp-hamiltonian-leetcode-practice-d37-30877d830d84?source=rss-e0f59fd11985------2</link>
            <guid isPermaLink="false">https://medium.com/p/30877d830d84</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[hamiltonian-path]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Aurora]]></dc:creator>
            <pubDate>Thu, 04 May 2023 15:01:35 GMT</pubDate>
            <atom:updated>2023-05-04T15:01:35.555Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/find-the-shortest-superstring/description/">Find the shortest superstring</a> [Hard]</p><p>Given a set of cities and distances between every pair of cities,</p><ul><li>Hamiltonian cycle: find if there exists a tour that visits every city exactly once;</li><li>Travelling salesman problem (TSP): find the shortest possible route that visits every city exactly once and returns to the starting point (i.e. find the minimum weight hamiltonian cycle).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Ja3w4Nqr5B05TGa2kqdzFg.png" /></figure><p>TSP is a NP-hard problem (no polynomial time solution).</p><p>This problem is a TSP:</p><blockquote>Given an array of strings words, return <em>the smallest string that contains each string in</em> words <em>as a substring</em>. If there are multiple valid strings of the smallest length, return <strong>any of them</strong>.</blockquote><blockquote>You may assume that no string in words is a substring of another string in words.</blockquote><blockquote><strong>Example 1:</strong></blockquote><blockquote>Input: words = [&quot;alex&quot;,&quot;loves&quot;,&quot;leetcode&quot;]<br>Output: &quot;alexlovesleetcode&quot;<br>Explanation: All permutations of &quot;alex&quot;,&quot;loves&quot;,&quot;leetcode&quot; would also be accepted.</blockquote><p><strong>Solution 1: Naive DFS (Time Limit Exceeded)</strong></p><p>A naive solution to get an idea on how the problem can be solved:</p><ol><li>Always convert string operations into integers. Construct a map to count number of overlapped alphabets map[a][b]if the string is connected as a-&gt;b;</li><li>Exhaustively use DFS to loop through all possible permutations of the nodes, and keep track of the shortest path;</li><li>Convert integer path back to String.</li></ol><pre>class Solution {<br>    int minCount = Integer.MAX_VALUE;<br>    List&lt;Integer&gt; resultInt = new ArrayList&lt;Integer&gt;(); <br><br>    public String shortestSuperstring(String[] words) {<br>        int[][] map = new int[words.length][words.length];<br>        for(int i = 0; i &lt; words.length; i ++) {<br>            for(int j = 0; j &lt; words.length; j ++) {<br>                if(i == j) continue;<br>                map[i][j] = getOverlap(words[i], words[j]);<br>            }<br>        }<br><br>        for(int i = 0; i &lt; words.length; i ++) {<br>            dfs(words, map, new boolean[words.length], i, words[i].length(), new ArrayList&lt;Integer&gt;());<br>        }<br><br>        StringBuilder sb = new StringBuilder();<br>        sb.append(words[resultInt.get(0)]);<br>        for(int i = 1; i &lt; words.length; i ++) {<br>            String str = words[resultInt.get(i)];<br>            int startIndex = map[resultInt.get(i - 1)][resultInt.get(i)];<br>            sb.append(str.substring(startIndex, str.length()));<br>        }<br>        <br>        return sb.toString();<br>    }<br><br>    private void dfs(String[] words, int[][] map, boolean[] visited, int cur, int count, ArrayList&lt;Integer&gt; path){<br>        boolean hasNext = false;<br>        path.add(cur);<br>        visited[cur] = true;<br>        for(int i = 0; i &lt; visited.length; i ++) {<br>            if(cur == i || visited[i]) continue;<br>            hasNext = true;<br>            dfs(words, map, visited, i, count + words[i].length() - map[cur][i], path); <br>        }<br><br>        if(!hasNext &amp;&amp; minCount &gt; count) {<br>            minCount = count;<br>            resultInt = (ArrayList&lt;Integer&gt;)path.clone();<br>        }<br>        path.remove(path.size() - 1);<br>        visited[cur] = false;<br>    }<br><br>    // a -&gt; b, count the number of overlapped alphabets.<br>    private int getOverlap(String a, String b) {<br>        int count = 0;<br>        for(int i = 0 ; i &lt; a.length(); i ++) {<br>            if(a.charAt(i) == b.charAt(0)) {<br>                count = a.length() - i;<br>                for(int j = i + 1; j &lt; a.length() &amp;&amp; j - i &lt; b.length(); j ++) {<br>                    if(a.charAt(j) != b.charAt(j - i)) {<br>                        count = 0; break;<br>                    }<br>                }<br>                if(count &gt; 0) break;<br>            }<br>        }<br>        return count;<br>    }<br>}</pre><p>The above algorithm can be improved by storing the count &amp; integer list for the tails to reduce number of recursions. For example, given nodes 1,2,3,4,5 we have permutations:</p><pre>(1) 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5<br>(2) 1 -&gt; 3 -&gt; 2 -&gt; 4 -&gt; 5<br>(3) 2 -&gt; 1 -&gt; 3 -&gt; 4 -&gt; 5<br>(4) 2 -&gt; 3 -&gt; 1 -&gt; 4 -&gt; 5<br>(5) 3 -&gt; 1 -&gt; 2 -&gt; 4 -&gt; 5<br>(6) 3 -&gt; 2 -&gt; 1 -&gt; 4 -&gt; 5</pre><p>One way to optimize this algorithm is to store the count result for 4 -&gt; 5. By doing so, we can avoid dig-ins into the two nodes (2) — (6), which can significantly reduce the time it takes to find the shortest path. This optimization technique becomes even more effective when we’re dealing with a large number of nodes. It’s similar to the idea behind using an insertion sort with a cutoff threshold in quicksort to optimize its time complexity.</p><p><strong>Solution 2: DP and Bit Mask</strong></p><pre>class Solution {<br>    public String shortestSuperstring(String[] A) {<br>        int n = A.length;<br>        int[][] graph = new int[n][n];<br>        // build the graph<br>        for (int i = 0; i &lt; n; i++) {<br>            for (int j = 0; j &lt; n; j++) {<br>                graph[i][j] = calc(A[i], A[j]);<br>                graph[j][i] = calc(A[j], A[i]);<br>            }<br>        }<br>        int[][] dp = new int[1 &lt;&lt; n][n];<br>        int[][] path = new int[1 &lt;&lt; n][n];<br>        int last = -1, min = Integer.MAX_VALUE;<br>  <br>        // start TSP DP<br>        for (int i = 1; i &lt; (1 &lt;&lt; n); i++) { // for all the combinations of the nodes<br>            Arrays.fill(dp[i], Integer.MAX_VALUE);// the length =MAX_VALUE<br>            for (int j = 0; j &lt; n; j++) { //for each node <br>                if ((i &amp; (1 &lt;&lt; j)) &gt; 0) {      // if the node is in the set. Assume i = 10010(18), j = 100(4), then set={1,4}, the node is 2. The node is not in this set<br>                    int prev = i - (1 &lt;&lt; j);      // the set without j. Assume i = 10010, j = 10 then pre = 10000<br>                    if (prev == 0) {            // if j is the only one<br>                        dp[i][j] = A[j].length();  // the entire word<br>                    } else {<br>                        for (int k = 0; k &lt; n; k++) {    //try all the possible nodes before j<br>                            if (dp[prev][k] &lt; Integer.MAX_VALUE &amp;&amp; dp[prev][k] + graph[k][j] &lt; dp[i][j]) { // if k is valid and the length could be reduced<br>                                dp[i][j] = dp[prev][k] + graph[k][j];   //update the result<br>                                path[i][j] = k; // update the node before j<br>                            }<br>                        }<br>                    }<br>                }<br>                if (i == (1 &lt;&lt; n) - 1 &amp;&amp; dp[i][j] &lt; min) {  // if i == 11...1111 means the node set contains all the nodes, and the length is smaller<br>                    min = dp[i][j];  //update the result<br>                    last = j;   //update the last node<br>                }<br>            }<br>        }<br>  <br>        // build the path<br>        StringBuilder sb = new StringBuilder();<br>        int cur = (1 &lt;&lt; n) - 1;<br>        Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();<br>        while (cur &gt; 0) {<br>            stack.push(last);<br>            int temp = cur;<br>            cur -= (1 &lt;&lt; last);<br>            last = path[temp][last];<br>        }<br>  <br>        // build the result<br>        int i = stack.pop();<br>        sb.append(A[i]);<br>        while (!stack.isEmpty()) {<br>            int j = stack.pop();<br>            sb.append(A[j].substring(A[j].length() - graph[i][j]));<br>            i = j;<br>        }<br>        return sb.toString();<br>    }<br><br>    // <br>    private int calc(String a, String b) {<br>        for (int i = 1; i &lt; a.length(); i++) {<br>            if (b.startsWith(a.substring(i))) {<br>                return b.length() - a.length() + i;<br>            }<br>        }<br>        return b.length();<br>    }<br>}</pre><p>Reference: <a href="https://leetcode.com/problems/find-the-shortest-superstring/solutions/194932/travelling-salesman-problem/">leetcode solution</a>.</p><p>More readings on the hamiltonian path:</p><ol><li><a href="https://www.hackerearth.com/practice/algorithms/graphs/hamiltonian-path/tutorial/">https://www.hackerearth.com/practice/algorithms/graphs/hamiltonian-path/tutorial/</a></li><li><a href="https://www.geeksforgeeks.org/travelling-salesman-problem-using-dynamic-programming/">https://www.geeksforgeeks.org/travelling-salesman-problem-using-dynamic-programming/</a></li><li><a href="https://www.geeksforgeeks.org/travelling-salesman-problem-using-dynamic-programming/">https://www.geeksforgeeks.org/traveling-salesman-problem-tsp-implementation/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30877d830d84" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>