Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Is Graph Bipartite? | Leetcode 785 | Easy 2-Color DFS Solution in Python
    Data Structures & Algorithms

    Is Graph Bipartite? | Leetcode 785 | Easy 2-Color DFS Solution in Python

    codeanddebugBy codeanddebug1 June 2025No Comments4 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured Image of a question of is graph bipartite on leetcode
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Learn how to test if an undirected graph is bipartite by coloring it with two colors. Simple DFS idea, commented Python code, dry run, and Big-O analysis.

    Here’s the [Problem Link] to begin with.

    Contents:
     [show]
    • What does the problem ask?
    • Examples
    • Intuition & Approach
    • Code
    • Code explanation (step-by-step)
    • Dry run on the first example
    • Complexity
    • Conclusion

    What does the problem ask?

    You get an undirected graph as an adjacency list graph.
    Your job is to say true if you can color every node using only two colors such that no two connected nodes share the same color.
    If this is impossible, return false.


    Examples

    graph (adjacency list)ResultReason
    [[1,3], [0,2], [1,3], [0,2]]trueYou can color nodes (0,2) with color 0 and (1,3) with color 1.
    [[1,2,3], [0,2], [0,1,3], [0,2]]falseTriangle (0,1,2) forces a conflict, needs 3 colors.
    [[],[]]trueTwo isolated nodes are always bipartite.

    Intuition & Approach

    1. Think in colors.
      Bipartite means we can split nodes into two groups (colors). Adjacent nodes must land in different groups.
    2. Pick a start node → give it color 0.
      Then travel through its neighbors with DFS.
    3. Color neighbors with the opposite color (1 − current).
      • If a neighbor already has a color and it matches ours, we found a clash → graph is not bipartite.
    4. Handle disconnected parts.
      The graph may have many separate components, so repeat the DFS for every still-uncolored node.
    5. If no clashes appear, the graph is bipartite.

    Code

    class Solution:
        # Helper DFS to try coloring one component
        def dfs(self, current_node, visited, graph, color):
            visited[current_node] = color          # paint current node
            for adjNode in graph[current_node]:    # go through all neighbors
                if visited[adjNode] != -1:         # neighbor already colored
                    if visited[adjNode] == color:  # same color → clash!
                        return False
                else:
                    # color neighbor with opposite color (1 - color)
                    ans = self.dfs(adjNode, visited, graph, 1 - color)
                    if ans == False:               # clash found deeper
                        return False
            return True                            # this branch is fine
    
        def isBipartite(self, graph: List[List[int]]) -> bool:
            total_nodes = len(graph)
            visited = [-1] * total_nodes           # -1 means "no color yet"
            for index in range(0, total_nodes):
                if visited[index] == -1:           # unvisited component
                    ans = self.dfs(index, visited, graph, 0)  # start with color 0
                    if ans == False:               # clash in this component
                        return False
            return True                            # all components are okay

    Code explanation (step-by-step)

    1. visited array
      Size = number of nodes
      • -1 → not colored yet
      • 0 or 1 → the chosen color
    2. Main loop goes through every node:
      • If the node is not colored, we launch DFS from it.
    3. DFS routine
      • Colors current node.
      • Checks all neighbors:
        • If neighbor has same color → immediately return False.
        • If neighbor is uncolored → recursively color it with 1 - color.
      • If recursion finishes with no clashes → return True.
    4. If any component returns False, the full graph is not bipartite.
      Otherwise return True.

    Dry run on the first example

    graph = [[1,3], [0,2], [1,3], [0,2]]

    StepActionvisited
    Start at node 0, color 0[0, -1, -1, -1]
    Visit neighbor 1 → color 1[0, 1, -1, -1]
    From node 1 visit neighbor 2 → color 0[0, 1, 0, -1]
    From node 2 visit neighbor 3 → color 1[0, 1, 0, 1]
    All further neighbors already colored with opposite color → no clashfinished
    Loop checks node 1, 2, 3 (already colored)done
    Return True

    Complexity

    MeasureValue
    TimeO(V + E)
    SpaceO(V)

    Explanation

    • We touch every vertex and every edge once during DFS.
    • visited array and recursion stack need up to V entries.

    Conclusion

    A graph is bipartite if you can 2-color it with no clashes.
    Depth-First Search plus an array that stores each node’s color is a quick and clear way to test this. If a conflict appears at any step, we know right away the graph needs more than two colors; otherwise it is bipartite.

    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Graph Medium
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleNumber of Distinct Islands | Simple DFS solution in Python
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Number of Distinct Islands | Simple DFS solution in Python

    1 June 2025
    Data Structures & Algorithms

    Number of Islands | Leetcode 200 | Explained using BFS and DFS

    31 May 2025
    Data Structures & Algorithms

    Word Ladder II | Leetcode 126 | Shortest Transformation Sequences with BFS

    31 May 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (34)
      • Beginner (16)
      • Expert (7)
      • Intermediate (11)
    • Uncategorised (1)
    Recent Posts

    Is Graph Bipartite? | Leetcode 785 | Easy 2-Color DFS Solution in Python

    1 June 2025

    Number of Distinct Islands | Simple DFS solution in Python

    1 June 2025

    Number of Islands | Leetcode 200 | Explained using BFS and DFS

    31 May 2025

    Word Ladder II | Leetcode 126 | Shortest Transformation Sequences with BFS

    31 May 2025

    Bubble Sort Algorithm in Python | Explained in Depth

    29 May 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.