LeetCode 3454: Separate Squares II Solution

Hello Everyone, Day 14 / #100DaysOfCode LeetCode 3454 — Separate Squares II (Hard) This problem was on a completely different level. Unlike Separate Squares I, overlapping areas here must be counted only once, which immediately rules out simple area accumulation or binary search tricks. Approach: Scan Line + Segment Tree (Adapted from the editorial and inspired by LeetCode 850 — Rectangle Area II) Core idea: - Sweep a horizontal scan line from bottom to top - Convert each square into two events: - Bottom edge → +1 coverage - Top edge → -1 coverage - Maintain active horizontal coverage using a segment tree with lazy propagation - At any vertical slice: - covered area = width × height - Width is the total x-length where coverage > 0 What the segment tree tracks: - Coverage count for each x-interval - Total covered length when count > 0 Using this, we compute the total covered area. Then, during the same scan, we locate the smallest y such that: area_below(y) = totalArea / 2 Since coverage stays constant between two scan events, the exact y can be computed analytically inside that interval. Complexity: - Time: O(n log n) - Space: O(n) Honest takeaway: I couldn’t crack this one independently and relied heavily on the editorial. Problems like this genuinely feel Extra Hard — combining geometry, sweep-line algorithms, discretization, and segment trees in one go. LeetCode has definitely raised the bar. #LeetCode #HardProblems #DSA #Java

  • text

To view or add a comment, sign in

Explore content categories