KatInterview

Densest Graph Without Triangles: Count and Build

Trees & GraphsAuto-graded · 25 test cases
MediumAuto-gradedTrees & Graphsgraph-theoryconstructionbipartite

Last updated

Find the largest edge count of a triangle-free simple graph on n vertices and output a canonical extremal graph, testing Mantel's theorem and the complete bipartite construction.

Densest Graph Without Triangles

You have n labelled points, numbered 0 to n - 1. You want to join some pairs of them with undirected edges so that the result is a simple graph (no self-loops, no repeated edges) that contains no triangle. A triangle is any three distinct points that are all pairwise joined.

Among all such graphs, find the largest possible number of edges, and also output one specific graph that reaches that number.

Task

Implement densest_triangle_free_graph(n). It must return a two-element list [max_edges, edges]:

  • max_edges is an integer, the maximum number of edges a triangle-free simple graph on n vertices can have.
  • edges is a list of edges, each written as a two-element list [u, v] with u < v.

Required output graph

To make the output unique, edges must describe exactly this graph:

  1. Let h = n // 2 (integer division).
  2. The left group is the vertices 0, 1, ..., h - 1. The right group is the vertices h, h + 1, ..., n - 1.
  3. Include one edge [u, v] for every left vertex u and every right vertex v, and no other edges.
  4. List the edges in increasing order of u, and for equal u in increasing order of v.

max_edges must equal the length of edges, which is h * (n - h).

Constraints

  • 1 <= n <= 1000
  • The graph is simple: no self-loops and no duplicate edges.
  • Building the edge list should take O(n^2) time, and max_edges should be computed in O(1).
  • The output uses O(n^2) space.
  • For n = 1 the result is [0, []].

Examples

Example 1

Input: densest_triangle_free_graph(4)

Output: [4, [[0, 2], [0, 3], [1, 2], [1, 3]]]

Example 2

Input: densest_triangle_free_graph(5)

Output: [6, [[0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4]]]

Example 3

Input: densest_triangle_free_graph(1)

Output: [0, []]

Example 4

Input: densest_triangle_free_graph(2)

Output: [1, [[0, 1]]]

Example 5

Input: densest_triangle_free_graph(3)

Output: [2, [[0, 1], [0, 2]]]

Hints

Hint 1

Think about which graphs obviously contain no triangle: a graph whose vertices split into two groups with edges only between the groups has no odd cycles at all.

Hint 2

If the groups have sizes a and n - a, the number of edges is a * (n - a). Which a maximizes this over integers?

Hint 3

For any edge (u, v) in a triangle-free graph, the neighbourhoods of u and v are disjoint, so deg(u) + deg(v) <= n. Summing over edges and applying Cauchy-Schwarz shows m <= n^2 / 4, which matches the construction.