Graph Coloring Problem

You are given a graph with 'N' vertices numbered from '1' to 'N' and 'M' edges. Your task is to color this graph using two colors, such as blue and red, in a way that no two adjacent vertices (connected by an edge) share the same color.

Input:

The first line of the input contains two integers 'V' and 'E', separated by a space, representing the number of vertices and the number of edges respectively.
The next 'E' lines each contain two integers 'u' and 'v', separated by a space, indicating an edge between vertex 'u' and vertex 'v'.

Output:

Output either "YES" if it is possible to color the graph as described, or "NO" if it is not possible.

Example:

If you are given a graph with vertices and edges as follows:

5 4
1 2
1 3
2 4
3 5

The output should be:

YES

Constraints:

  • 1 <= E <= 105
  • 1 <= V <= 106
  • Time Limit: 1 second
Note:

The given graph may have connected components.

AnswerBot
4mo

The task is to color a graph with two colors in a way that no two adjacent vertices share the same color.

  • Check if the graph can be colored using two colors without any adjacent vertices sharing the sa...read more

Help your peers!
Select
Add answer anonymously...

CodeNation Software Developer Intern interview questions & answers

A Software Developer Intern was asked Q. Rat in a Maze Problem Statement You need to determine all possible paths for a r...read more
A Software Developer Intern was asked Q. Kth Largest Number Problem Statement You are given a continuous stream of number...read more
A Software Developer Intern was asked Q. Count Inversions Problem Statement Given an integer array ARR of size N, your ta...read more

Popular interview questions of Software Developer Intern

A Software Developer Intern was asked Q1. Rat in a Maze Problem Statement You need to determine all possible paths for a r...read more
A Software Developer Intern was asked Q2. Kth Largest Number Problem Statement You are given a continuous stream of number...read more
A Software Developer Intern was asked Q3. Count Inversions Problem Statement Given an integer array ARR of size N, your ta...read more
CodeNation Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits