Search Blogs

Showing results for "Geometry"

Found 2 results

LeetCode 836: Rectangle Overlap – Java Solution, Explanation & Approach

LeetCode 836: Rectangle Overlap – Java Solution, Explanation & Approach

IntroductionLeetCode 836, Rectangle Overlap, is a simple geometry problem that tests an important idea: how to determine whether two ranges actually intersect.Each rectangle is represented using four coordinates:[x1, y1, x2, y2]where:(x1, y1) → bottom-left corner(x2, y2) → top-right cornerThe rectangles are axis-aligned, so their sides are always parallel to the X and Y axes.The important part is that touching is not considered overlap.For example, if two rectangles share only an edge or a corner, the answer must be false.The solution can be built entirely using coordinate comparisons, without calculating the actual intersection area.Some example testcase with visualized coordinates:-Example 1:Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]Output: trueExample 2:Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]Output: falseExample 3:Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]Output: falseQuestion LinkLeetCode 836 – Rectangle OverlapUnderstanding the IdeaFor two rectangles to have a positive-area overlap, they must overlap in both dimensions:Along the X-axisAlong the Y-axisIf they fail to overlap in either dimension, the rectangles cannot overlap.For example, if one rectangle is completely above another:There is no overlap.The same happens if one rectangle is completely to the left or right of the other.ApproachThe solution first extracts the four important boundaries of both rectangles:Rectangle 1:left = rec1[0]bottom = rec1[1]right = rec1[2]top = rec1[3]Rectangle 2:left = rec2[0]bottom = rec2[1]right = rec2[2]top = rec2[3]Then the solution checks whether the rectangles are separated.Check vertical separationif(rect1h1 >= rect2h2 || rect2h1 >= rect1h2){ return false;}If the bottom of Rectangle 1 is at or above the top of Rectangle 2, they do not overlap.Similarly, if the bottom of Rectangle 2 is at or above the top of Rectangle 1, there is no overlap.The use of >= is important because rectangles that only touch an edge must return false.Check horizontal separationif(rect1l1 >= rect2l2 || rect2l1 >= rect1l2){ return false;}This checks whether one rectangle is completely to the left of the other.Again, >= handles the edge-touching case.After these separation checks pass, the rectangles must overlap with positive width and height.Java Solutionclass Solution { public boolean isRectangleOverlap(int[] rec1, int[] rec2) { boolean leno = false; boolean heio = false; int rect1l1 = rec1[0]; int rect1l2 = rec1[2]; int rect1h1 = rec1[1]; int rect1h2 = rec1[3]; int rect2l1 = rec2[0]; int rect2l2 = rec2[2]; int rect2h1 = rec2[1]; int rect2h2 = rec2[3]; // Check if the rectangles are separated vertically if (rect1h1 >= rect2h2 || rect1l1 >= rect2l2) { return false; } // Check if the rectangles are separated horizontally if (rect2h1 >= rect1h2 || rect2l1 >= rect1l2) { return false; } // There is horizontal overlap if (rect1l2 > rect2l1) { leno = true; } // There is vertical overlap if (leno && rect1h2 <= rect2h2) { heio = true; } if (leno && rect1h2 > rect2h2) { heio = true; } return leno && heio; }}Dry RunConsider:rec1 = [0,0,2,2]rec2 = [1,1,3,3]Rectangle 1:left = 0bottom = 0right = 2top = 2Rectangle 2:left = 1bottom = 1right = 3top = 3Vertical checkrect1 bottom >= rect2 top0 >= 3 → falseandrect2 bottom >= rect1 top1 >= 2 → falseSo they are not vertically separated.Horizontal checkrect1 left >= rect2 right0 >= 3 → falseandrect2 left >= rect1 right1 >= 2 → falseSo they are not horizontally separated either.Therefore, there is a positive-area intersection.Answer = trueThe overlapping region is:x: 1 to 2y: 1 to 2which has positive width and height.Why Edge Touching Returns FalseConsider:rec1 = [0,0,1,1]rec2 = [1,0,2,1]The rectangles touch at x = 1, but there is no positive-width intersection.The condition:rect2l1 >= rect1l2becomes:1 >= 1which is true.Therefore:return false;This is why >= is used instead of simply >.A Useful Way to Think About the ProblemA rectangle overlap problem can be reduced to this simple rule:If the rectangles are separated in X or separated in Y → no overlap. Otherwise → overlap.The four separation cases are:Rectangle 1 is above Rectangle 2Rectangle 2 is above Rectangle 1Rectangle 1 is left of Rectangle 2Rectangle 2 is left of Rectangle 1If none of these situations occurs, the rectangles overlap.Complexity AnalysisThere are only a constant number of coordinate comparisons.Time Complexity: O(1)Space Complexity: O(1)No loops, additional arrays, or data structures are required.Code ImprovementThe current solution works, but the final leno and heio checks are more complicated than necessary.Once all four separation cases have been eliminated, overlap is already guaranteed.The same idea can therefore be written more directly:class Solution { public boolean isRectangleOverlap(int[] rec1, int[] rec2) { // No vertical overlap if (rec1[1] >= rec2[3] || rec2[1] >= rec1[3]) { return false; } // No horizontal overlap if (rec1[0] >= rec2[2] || rec2[0] >= rec1[2]) { return false; } return true; }}This version has exactly the same asymptotic complexity but makes the core geometry easier to recognize.Interview TipFor coordinate and geometry problems, avoid immediately trying to calculate the intersection area.A better first question is:"When can the two objects definitely NOT overlap?"For rectangles, there are only four separation cases. Once those are handled, the remaining case automatically represents a positive-area overlap.This "check the impossible cases first" technique is useful in many interval and geometry problems.ConclusionLeetCode 836 is a good example of how a seemingly geometric problem can be solved using simple comparisons.The key observation is that two rectangles overlap only when they have overlap on both the X-axis and Y-axis. If one rectangle is completely separated from the other in either direction, the answer is false.The important boundary detail is using >=, because merely touching at an edge or corner does not count as an overlap.

LeetCodeJavaRectangle OverlapGeometryArraysCoordinatesMathEasy
LeetCode 1344: Angle Between Hands of a Clock – Java Mathematical Solution Explained

LeetCode 1344: Angle Between Hands of a Clock – Java Mathematical Solution Explained

IntroductionLeetCode 1344, Angle Between Hands of a Clock, is a classic mathematics and geometry problem frequently asked in coding interviews.Unlike many algorithmic problems involving arrays, trees, or dynamic programming, this challenge focuses entirely on understanding how an analog clock works and converting that understanding into a simple mathematical formula.The goal is to determine the smaller angle formed between the hour hand and the minute hand for a given time.This problem is an excellent example of how mathematical observation can transform what appears to be a simulation problem into a constant-time solution.Problem Link - Angle Between Hands of a ClockProblem StatementGiven:An integer hourAn integer minutesReturn the smaller angle formed between:The hour handThe minute handof an analog clock.The answer should be accurate within 10^-5.Example 1Inputhour = 12minutes = 30Output165ExplanationAt 12:30:Minute hand points at 6Hour hand lies halfway between 12 and 1The smaller angle between them is:165°Example 2Inputhour = 3minutes = 30Output75Example 3Inputhour = 3minutes = 15Output7.5Understanding Clock MathematicsTo solve this problem efficiently, we first need to understand how clock hands move.Minute Hand MovementA clock contains:360°and60 minutesTherefore:360 / 60 = 6°The minute hand moves:6° per minuteFormula:Minute Angle = 6 × minutesExample:30 minutes6 × 30 = 180°Hour Hand MovementThe clock has:12 hoursand360°Therefore:360 / 12 = 30°The hour hand moves:30° per hourFormula:Hour Angle = 30 × hourHowever, most beginners miss one important detail.The Hour Hand Never Stays StillAt 3:30, the hour hand is not exactly at 3.It moves continuously as minutes pass.Since:30° per hourand60 minutes per hourthe hour hand moves:30 / 60 = 0.5°per minute.Therefore:Hour Angle =(30 × hour) + (0.5 × minutes)Deriving the Final FormulaMinute hand angle:6 × minutesHour hand angle:30 × hour + 0.5 × minutesDifference:|Hour Angle − Minute Angle|Substituting:|(30 × hour + 0.5 × minutes)− (6 × minutes)|Simplifying:|30 × hour − 5.5 × minutes|This gives one angle.But clocks always form two angles.Choosing the Smaller AngleSuppose:Difference = 250°The other angle would be:360 − 250 = 110°Since the problem asks for the smaller angle:Math.min(diff, 360 - diff)Optimal Java Solutionclass Solution { public double angleClock(int hour, int minutes) { double angle = Math.abs((30 * hour) - (5.5 * minutes)); return angle > 180 ? 360 - angle : angle; }}Dry RunInputhour = 3minutes = 15Hour Hand Angle30 × 3 = 900.5 × 15 = 7.5Total = 97.5°Minute Hand Angle6 × 15 = 90°Difference|97.5 - 90|=7.5°Smaller Angle7.5°Output:7.5Dry Run 2Inputhour = 12minutes = 30Formula|30 × 12 − 5.5 × 30||360 − 165|195°Since:195 > 180Choose:360 − 195=165°Output:165Why This Solution Is OptimalMany beginners attempt to:Simulate clock positionsCreate arraysUse loopsNone of these are required.The entire problem can be solved using a direct mathematical formula.No iteration is needed.No additional data structures are needed.Complexity AnalysisTime ComplexityO(1)Only a few arithmetic operations are performed.Space ComplexityO(1)No extra memory is used.Common Interview MistakesMistake 1Ignoring minute movement of the hour hand.Wrong:Hour Angle = 30 × hourCorrect:Hour Angle =30 × hour + 0.5 × minutesMistake 2Returning the larger angle.The problem asks for:Smaller AngleAlways compare:angleand360 - angleMistake 3Forgetting absolute value.Without:Math.abs()negative angles may occur.Key TakeawaysMinute hand moves 6° every minute.Hour hand moves 30° every hour.Hour hand also moves 0.5° every minute.The formula simplifies to:|30 × hour − 5.5 × minutes|Always return the smaller of the two possible angles.The solution runs in O(1) time and O(1) space.ConclusionLeetCode 1344: Angle Between Hands of a Clock is a beautiful mathematical problem that demonstrates how understanding the underlying mechanics of a clock leads to an elegant constant-time solution.Instead of simulating movement, we directly calculate the positions of both hands using geometry and arithmetic. This results in a clean, interview-friendly solution with optimal performance.Problems like this highlight an important lesson in programming:Sometimes the best algorithm is not an algorithm at all—it is mathematics.

LeetcodeJavaMediumClock AngleMaths
Ai Assistant Kas