Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sorting
Intervals
Widest Possible Fence

Find the maximum width of a fence segment that can be formed from a set of line segments or posts after aligning and combining compatible parts.

Acceptance 0%
Problem Statement

Given a collection of fence pieces represented by positions or intervals on a line, determine the widest continuous fence that can be formed by joining pieces that touch or overlap. The goal is to compute the maximum possible span of any valid merged fence section.

A valid fence section is continuous: if two pieces overlap or meet at an endpoint, they can be treated as part of the same fence. Your task is to identify the widest such section across all pieces.

Input Format

  • An array of intervals or fence pieces, where each piece is described by two endpoints.
  • Each endpoint is an integer position on a number line.
  • Intervals may be unsorted and may overlap or touch.

Output Format

  • Return a single integer: the maximum width among all continuous merged fence sections.
  • If no valid section exists, return 0.

Constraints

  • 1≤n1 \le n is reasonably large for interview settings.
  • Each segment endpoint fits in a 32-bit signed integer.
  • Intervals may be unsorted.
  • Touching endpoints are considered connectable when forming a continuous fence.
Examples
Sample cases returned by the problem API.

Example 1

Input

[[1,3],[2,6],[8,10],[9,12]]

Output

4

Explanation

The intervals [1,3] and [2,6] merge into [1,6], which has width 5 if measured as end-start, or 4 if the problem defines width by covered unit count. The widest merged continuous fence section is formed by the last two intervals as [8,12].

Example 2

Input

[[5,7],[1,2],[3,4]]

Output

2

Explanation

No intervals overlap or touch, so the widest fence section is just the widest individual segment.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.