Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Geometric Algorithms
  • Basic Geometry
  • Computational Geometry
  • Slope of Line
  • Point of Intersection of Two Lines
  • Closest Pair of Points
  • Convex Hull
  • Pythagorean Quadruple
  • Polygon Triangulation
Open In App
Next Article:
Klee's Algorithm (Length Of Union Of Segments of a line)
Next article icon

Sweep Line Algorithm - Find if any Two Segments Intersect

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given n line segments represented as a 3D vector points[][][], where each line segment i is defined by its endpoints stored in points[i][0] and points[i][1] (each containing 2 integers), your task is to determine if any two of these line segments intersect and find the number of intersection points.

Examples:

Input: points[][][] = [ [ [1, 5], [4, 5] ],
[ [2, 5], [10, 1] ],
[ [3, 2], [10, 3] ],
[ [6, 4], [9, 4] ],
[ [7, 1], [8, 1] ] ]
Output: 2
Explanation: Lines [ [1, 5], [4, 5] ] intersects with [ [2, 5], [10, 1] ] which further intersects with [ [3, 2], [10, 3] ]. Thus there are two intersection points.

[Naive Approach] - Check Every Pair - O(n^2) Time

A naive solution to solve this problem is to check every pair of lines and check if the pair intersects or not. We can check two line segments in O(1) time. Therefore, this approach takes O(n2). 

[Expected Approach] - Sweep Line Algorithm - O(n Log n) Time and O(n) Space

The idea is to use a sweep line method that processes the endpoints of the line segments from left to right, dynamically maintaining a set of segments currently "active" as the sweep line moves. With this approach, we only check for intersections between line segments that are close to each other in the vertical ordering, thus ensuring we handle the problem in a methodical and efficient manner. To manage the active segments, a self-balancing binary search tree (like an AVL or Red-Black Tree) or a similar data structure is used; this allows us to quickly insert new segments, remove segments once their right endpoint is passed, and find the segments immediately above and below a given segment.

Below is given the step-by-step approach to solve the problem:

  • Begin by representing every line segment with its two endpoints and mark each endpoint to indicate whether it is the left or the right end of the segment.
  • Sort all the endpoints according to their x-coordinate values.
  • Initialize an empty self-balancing binary search tree (or min heap for dynamic endpoint processing) to keep track of the active segments along the y-axis.
  • Process each endpoint from left to right:
    • If the current endpoint is a left endpoint, insert its segment into the active set and check for intersections with the immediate neighbors (the segment just above and the one just below) in the active set.
    • If the current endpoint is a right endpoint, remove its segment from the active set and check if the segments that were immediately above and below (now adjacent after removal) intersect with each other.
  • Continue the process until all endpoints have been handled and all potential intersections are checked.

Pseudocode:

C++
function sweepLineIntersection(Points):     // Sort the points according to their x-coordinate.     sort(Points)            // T: self-balancing BST to store active segments ordered by their y-coordinates.     T = new BST()            // Iterate over each point in the sorted array.     for i from 0 to length(Points) - 1:         currentPoint = Points[i]                  if currentPoint.isLeft then:             // Insert the segment corresponding to the left endpoint.             segment = currentPoint.segment             T.insert(segment)                          // Retrieve the immediate neighbor segments.             pred = T.predecessor(segment)             succ = T.successor(segment)                          // Check intersection with the predecessor.             if pred is not null and doIntersect(segment, pred) then                 return true             // Check intersection with the successor.             else if succ is not null and doIntersect(segment, succ) then                 return true         else:  // currentPoint is the right endpoint of its segment.             segment = currentPoint.segment                          // Before removing the segment, get its neighbors.             pred = T.predecessor(segment)             succ = T.successor(segment)                          // Remove the segment from the tree.             T.delete(segment)                          // After removal, if both neighbors exist, check if they intersect.             if pred is not null and succ is not null and doIntersect(pred, succ) then                 return true                      // No intersections found.     return false 

Example:

There are 5 line segments 1, 2, 3, 4 and 5 and the dotted green lines show sweep lines. 

sweepline

Following are steps followed by the algorithm

  • Process the left endpoint of segment 1.
    • Insert segment 1 into the BST.
    • The BST now contains: 1
    • No intersection is found.
  • Process the left endpoint of segment 2
    • Check for intersection between segment 2 and segment 1.
    • Insert segment 2 into the BST.
    • Intersection of 1 and 2 is detected. (In the pseudocode, we would return here, but we continue in this example to find all possible intersections.)
    • The BST now contains: 1, 2
  • Process the left endpoint of segment 3
    • Check for intersection between segment 3 and segment 1.
    • No intersection is found.
    • Insert segment 3 into the BST.
    • The BST now contains: 1, 2, 3
  • Process the right endpoint of segment 1
    • Remove segment 1 from the BST.
    • Check for intersection between segments 2 and 3.
    • Intersection of 2 and 3 is found and reported.
    • The BST now contains: 2, 3
  • Process the left endpoint of segment 4
    • Check for intersections between segment 4 and existing segments (2 and 3).
    • No intersection is found.
    • Insert segment 4 into the BST.
    • The BST now contains: 2, 4, 3
  • Process the left endpoint of segment 5
    • Check for intersection between segment 5 and segment 3.
    • No intersection is found.
    • Insert segment 5 into the BST.
    • The BST now contains: 2, 4, 3, 5
  • Process the right endpoint of segment 5
    • Remove segment 5 from the BST.
    • The BST now contains: 2, 4, 3.
  • Process the right endpoint of segment 4
    • Remove segment 4 from the BST.
    • The BST now contains: 2, 3
    • Check for intersection between segments 2 and 3.
    • Intersection of 2 and 3 is reported again. (Additional logic might be added to avoid duplicating the same intersection.)
    • The BST still contains: 2, 3
  • Process the right endpoints of segments 2 and 3
    • Remove segments 2 and 3 from the BST.
    • The BST becomes empty.

After these steps, all endpoints have been processed, and all intersections have been identified (with duplicates possibly reported depending on the implementation details). 

C++
#include <bits/stdc++.h> using namespace std;  // An event for the sweep line algorithm class Event { public:     int x, y;     bool isLeft;     int index;     Event(int x, int y, bool l, int i) {         this->x = x;         this->y = y;         this->isLeft = l;         this->index = i;     }      // Order events by y-coordinate, then by x-coordinate     bool operator<(const Event &e) const {         if (y == e.y)             return x < e.x;         return y < e.y;     } };  // Given three collinear points p, q, r  // the function checks if point  // q lies on line segment 'pr' bool onSegment(vector<int> p, vector<int> q, vector<int> r) {     if (q[0] <= max(p[0], r[0]) && q[0] >= min(p[0], r[0]) &&         q[1] <= max(p[1], r[1]) && q[1] >= min(p[1], r[1]))         return true;     return false; }  // To find orientation of ordered triplet (p, q, r). // Returns 0 if collinear, 1 if clockwise, 2 if counterclockwise. int orientation(vector<int> p, vector<int> q, vector<int> r) {     int val = (q[1] - p[1]) * (r[0] - q[0]) -               (q[0] - p[0]) * (r[1] - q[1]);       // collinear     if (val == 0)         return 0;          // clock- or counterclockwise     return (val > 0) ? 1 : 2;  }  // to find if two segments intersect bool doIntersect(vector<vector<int>> s1, vector<vector<int>> s2) {     vector<int> p1 = s1[0], q1 = s1[1], p2 = s2[0], q2 = s2[1];      int o1 = orientation(p1, q1, p2);     int o2 = orientation(p1, q1, q2);     int o3 = orientation(p2, q2, p1);     int o4 = orientation(p2, q2, q1);      // General case     if (o1 != o2 && o3 != o4)         return true;      // Special cases     if (o1 == 0 && onSegment(p1, p2, q1)) return true;     if (o2 == 0 && onSegment(p1, q2, q1)) return true;     if (o3 == 0 && onSegment(p2, p1, q2)) return true;     if (o4 == 0 && onSegment(p2, q1, q2)) return true;      return false; }  // Returns the predecessor iterator in set s. set<Event>::iterator pred(set<Event> &s, set<Event>::iterator it) {     return it == s.begin() ? s.end() : --it; }  // Returns the successor iterator in set s. set<Event>::iterator succ(set<Event> &s, set<Event>::iterator it) {     return ++it; }  // Returns the number of intersections found between segments. int isIntersect(vector<vector<vector<int>>> &lines) {      // To avoid duplicate intersection reports.     unordered_map<string, int> mp;        vector<Event> events;     int n = lines.size();     for (int i = 0; i < n; ++i) {          // Create events for the left and right endpoints.         events.push_back(Event(lines[i][0][0], lines[i][0][1], true, i));         events.push_back(Event(lines[i][1][0], lines[i][1][1], false, i));     }      // Sort events according to x-coordinate.     sort(events.begin(), events.end(), [](Event &e1, Event &e2) {         return e1.x < e2.x;     });      // Set for storing active segments.     set<Event> active;     int ans = 0;      // Process all events.     for (int i = 0; i < 2 * n; i++) {         Event curr = events[i];         int index = curr.index;          if (curr.isLeft) {              // For the left endpoint, get neighbors in the active set.             auto next = active.lower_bound(curr);             auto prev = pred(active, next);              // Check for intersection with the next segment.             if (next != active.end() && doIntersect(lines[next->index], lines[index])) {                 string key = to_string(next->index + 1) + " " + to_string(index + 1);                 if (mp.count(key) == 0) {                     mp[key]++;                     ans++;                 }             }              // Check for intersection with the previous segment.             if (prev != active.end() && doIntersect(lines[prev->index], lines[index])) {                 string key = to_string(prev->index + 1) + " " + to_string(index + 1);                 if (mp.count(key) == 0) {                     mp[key]++;                     ans++;                 }             }              // To avoid counting duplicates if the same segment is both neighbor.             if (prev != active.end() && next != active.end() && next->index == prev->index)                 ans--;              active.insert(curr);         }                   else {              // For the right endpoint, find the matching left endpoint in the active set.             auto it = active.find(Event(lines[index][0][0], lines[index][0][1], true, index));             auto next = succ(active, it);             auto prev = pred(active, it);              // If both neighbors exist, check if they intersect.             if (next != active.end() && prev != active.end()) {                 string key1 = to_string(next->index + 1) + " " + to_string(prev->index + 1);                 string key2 = to_string(prev->index + 1) + " " + to_string(next->index + 1);                 if (mp.count(key1) == 0 && mp.count(key2) == 0 && doIntersect(lines[prev->index], lines[next->index]))                     ans++;                 mp[key1]++;             }              // Remove the segment from the active set.             active.erase(it);         }     }      // Report all intersecting pairs.     for (auto &pr : mp) {         cout << "Line: " << pr.first << "\n";     }     return ans; }  int main() {     vector<vector<vector<int>>> lines = {         { {1, 5}, {4, 5} },         { {2, 5}, {10, 1} },         { {3, 2}, {10, 3} },         { {6, 4}, {9, 4} },         { {7, 1}, {8, 1} }     };     cout << isIntersect(lines);     return 0; } 
Java
import java.util.*;  public class GfG {      // An event for the sweep line algorithm     public static class Event implements Comparable<Event> {         public int x, y;         public boolean isLeft;         public int index;         public Event(int x, int y, boolean l, int i) {             this.x = x;             this.y = y;             this.isLeft = l;             this.index = i;         }          // Order events by y-coordinate, then by x-coordinate         public int compareTo(Event e) {             if (this.y == e.y)                 return this.x - e.x;             return this.y - e.y;         }                  public boolean equals(Object o) {             if (this == o)                 return true;             if (!(o instanceof Event))                 return false;             Event e = (Event) o;             return this.x == e.x && this.y == e.y && this.isLeft == e.isLeft && this.index == e.index;         }                  public int hashCode() {             return Objects.hash(x, y, isLeft, index);         }     }      // Given three collinear points p, q, r      // the function checks if point      // q lies on line segment 'pr'     public static boolean onSegment(ArrayList<Integer> p, ArrayList<Integer> q, ArrayList<Integer> r) {         if (q.get(0) <= Math.max(p.get(0), r.get(0)) && q.get(0) >= Math.min(p.get(0), r.get(0)) &&             q.get(1) <= Math.max(p.get(1), r.get(1)) && q.get(1) >= Math.min(p.get(1), r.get(1)))             return true;         return false;     }      // To find orientation of ordered triplet (p, q, r).     // Returns 0 if collinear, 1 if clockwise, 2 if counterclockwise.     public static int orientation(ArrayList<Integer> p, ArrayList<Integer> q, ArrayList<Integer> r) {         int val = (q.get(1) - p.get(1)) * (r.get(0) - q.get(0)) -                   (q.get(0) - p.get(0)) * (r.get(1) - q.get(1));           // collinear         if (val == 0)             return 0;                   // clock- or counterclockwise         return (val > 0) ? 1 : 2;     }      // to fin dif two segments intersect     public static boolean doIntersect(ArrayList<ArrayList<Integer>> s1, ArrayList<ArrayList<Integer>> s2) {         ArrayList<Integer> p1 = s1.get(0), q1 = s1.get(1), p2 = s2.get(0), q2 = s2.get(1);          int o1 = orientation(p1, q1, p2);         int o2 = orientation(p1, q1, q2);         int o3 = orientation(p2, q2, p1);         int o4 = orientation(p2, q2, q1);          // General case         if (o1 != o2 && o3 != o4)             return true;          // Special cases         if (o1 == 0 && onSegment(p1, p2, q1)) return true;         if (o2 == 0 && onSegment(p1, q2, q1)) return true;         if (o3 == 0 && onSegment(p2, p1, q2)) return true;         if (o4 == 0 && onSegment(p2, q1, q2)) return true;          return false;     }      // Returns the predecessor iterator in set s.     public static Event pred(TreeSet<Event> s, Event e) {         return s.lower(e);     }      // Returns the successor iterator in set s.     public static Event succ(TreeSet<Event> s, Event e) {         return s.higher(e);     }      // Returns the number of intersections found between segments.     public static int isIntersect(ArrayList<ArrayList<ArrayList<Integer>>> lines) {          // To avoid duplicate intersection reports.         HashMap<String, Integer> mp = new HashMap<>();          ArrayList<Event> events = new ArrayList<>();         int n = lines.size();         for (int i = 0; i < n; ++i) {              // Create events for the left and right endpoints.             events.add(new Event(lines.get(i).get(0).get(0), lines.get(i).get(0).get(1), true, i));             events.add(new Event(lines.get(i).get(1).get(0), lines.get(i).get(1).get(1), false, i));         }          // Sort events according to x-coordinate.         Collections.sort(events, new Comparator<Event>() {             public int compare(Event e1, Event e2) {                 return e1.x - e2.x;             }         });          // Set for storing active segments.         TreeSet<Event> active = new TreeSet<>();         int ans = 0;          // Process all events.         for (int i = 0; i < 2 * n; i++) {             Event curr = events.get(i);             int index = curr.index;              if (curr.isLeft) {                  // For the left endpoint, get neighbors in the active set.                 Event next = active.ceiling(curr);                 Event prev = pred(active, curr);                  // Check for intersection with the next segment.                 if (next != null && doIntersect(lines.get(next.index), lines.get(index))) {                     String key = Integer.toString(next.index + 1) + " " + Integer.toString(index + 1);                     if (!mp.containsKey(key)) {                         mp.put(key, 1);                         ans++;                     }                 }                  // Check for intersection with the previous segment.                 if (prev != null && doIntersect(lines.get(prev.index), lines.get(index))) {                     String key = Integer.toString(prev.index + 1) + " " + Integer.toString(index + 1);                     if (!mp.containsKey(key)) {                         mp.put(key, 1);                         ans++;                     }                 }                  // To avoid counting duplicates if the same segment is both neighbor.                 if (prev != null && next != null && next.index == prev.index)                     ans--;                  active.add(curr);             }              else {                  // For the right endpoint, find the matching left endpoint in the active set.                 Event temp = new Event(lines.get(index).get(0).get(0), lines.get(index).get(0).get(1), true, index);                 Event it = null;                 for (Event e : active) {                     if (e.equals(temp)) {                         it = e;                         break;                     }                 }                 Event next = succ(active, it);                 Event prev = pred(active, it);                  // If both neighbors exist, check if they intersect.                 if (next != null && prev != null) {                     String key1 = Integer.toString(next.index + 1) + " " + Integer.toString(prev.index + 1);                     String key2 = Integer.toString(prev.index + 1) + " " + Integer.toString(next.index + 1);                     if (!mp.containsKey(key1) && !mp.containsKey(key2) && doIntersect(lines.get(prev.index), lines.get(next.index)))                         ans++;                     mp.put(key1, 1);                 }                  // Remove the segment from the active set.                 active.remove(it);             }         }          // Report all intersecting pairs.         for (Map.Entry<String, Integer> pr : mp.entrySet()) {             System.out.println("Line: " + pr.getKey());         }         return ans;     }      public static void main(String[] args) {         ArrayList<ArrayList<ArrayList<Integer>>> lines = new ArrayList<>();         lines.add(new ArrayList<ArrayList<Integer>>(Arrays.asList(new ArrayList<Integer>(Arrays.asList(1, 5)), new ArrayList<Integer>(Arrays.asList(4, 5)))));         lines.add(new ArrayList<ArrayList<Integer>>(Arrays.asList(new ArrayList<Integer>(Arrays.asList(2, 5)), new ArrayList<Integer>(Arrays.asList(10, 1)))));         lines.add(new ArrayList<ArrayList<Integer>>(Arrays.asList(new ArrayList<Integer>(Arrays.asList(3, 2)), new ArrayList<Integer>(Arrays.asList(10, 3)))));         lines.add(new ArrayList<ArrayList<Integer>>(Arrays.asList(new ArrayList<Integer>(Arrays.asList(6, 4)), new ArrayList<Integer>(Arrays.asList(9, 4)))));         lines.add(new ArrayList<ArrayList<Integer>>(Arrays.asList(new ArrayList<Integer>(Arrays.asList(7, 1)), new ArrayList<Integer>(Arrays.asList(8, 1)))));         System.out.println(isIntersect(lines));     } } 
Python
import bisect  # An event for the sweep line algorithm class Event:     def __init__(self, x, y, isLeft, index):         self.x = x         self.y = y         self.isLeft = isLeft         self.index = index      # Order events by y-coordinate, then by x-coordinate     def __lt__(self, e):         if self.y == e.y:             return self.x < e.x         return self.y < e.y      def __eq__(self, other):         return self.x == other.x and self.y == other.y and self.isLeft == other.isLeft and self.index == other.index      def __hash__(self):         return hash((self.x, self.y, self.isLeft, self.index))   # Given three collinear points p, q, r  # the function checks if point  # q lies on line segment 'pr' def onSegment(p, q, r):     if q[0] <= max(p[0], r[0]) and q[0] >= min(p[0], r[0]) and \        q[1] <= max(p[1], r[1]) and q[1] >= min(p[1], r[1]):         return True     return False   # To find orientation of ordered triplet (p, q, r). # Returns 0 if collinear, 1 if clockwise, 2 if counterclockwise. def orientation(p, q, r):     val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])          # collinear     if val == 0:         return 0      # clock- or counterclockwise     return 1 if val > 0 else 2   # to fin dif two segments intersect def doIntersect(s1, s2):     p1, q1 = s1[0], s1[1]     p2, q2 = s2[0], s2[1]      o1 = orientation(p1, q1, p2)     o2 = orientation(p1, q1, q2)     o3 = orientation(p2, q2, p1)     o4 = orientation(p2, q2, q1)      # General case     if o1 != o2 and o3 != o4:         return True      # Special cases     if o1 == 0 and onSegment(p1, p2, q1):         return True     if o2 == 0 and onSegment(p1, q2, q1):         return True     if o3 == 0 and onSegment(p2, p1, q2):         return True     if o4 == 0 and onSegment(p2, q1, q2):         return True      return False   # Returns the predecessor element in list s given index pos. def pred(s, pos):     return s[pos - 1] if pos > 0 else None   # Returns the successor element in list s given index pos. def succ(s, pos):     return s[pos + 1] if pos + 1 < len(s) else None   # Returns the number of intersections found between segments. def isIntersect(lines):          # To avoid duplicate intersection reports.     mp = {}      events = []     n = len(lines)     for i in range(n):                  # Create events for the left and right endpoints.         events.append(Event(lines[i][0][0], lines[i][0][1], True, i))         events.append(Event(lines[i][1][0], lines[i][1][1], False, i))      # Sort events according to x-coordinate.     events.sort(key=lambda e: e.x)      # List for storing active segments.     active = []     ans = 0      # Process all events.     for i in range(2 * n):         curr = events[i]         index = curr.index          if curr.isLeft:                          # For the left endpoint, get neighbors in the active set.             pos = bisect.bisect_left(active, curr)             nextElem = active[pos] if pos < len(active) else None             prevElem = pred(active, pos)              # Check for intersection with the next segment.             if nextElem is not None and doIntersect(lines[nextElem.index], lines[index]):                 key = str(nextElem.index + 1) + " " + str(index + 1)                 if key not in mp:                     mp[key] = 1                     ans += 1              # Check for intersection with the previous segment.             if prevElem is not None and doIntersect(lines[prevElem.index], lines[index]):                 key = str(prevElem.index + 1) + " " + str(index + 1)                 if key not in mp:                     mp[key] = 1                     ans += 1              # To avoid counting duplicates if the same segment is both neighbor.             if prevElem is not None and nextElem is not None and nextElem.index == prevElem.index:                 ans -= 1              bisect.insort(active, curr)         else:                          # For the right endpoint, find the matching left endpoint in the active set.             temp = Event(lines[index][0][0], lines[index][0][1], True, index)             pos = 0             for j in range(len(active)):                 if active[j] == temp:                     pos = j                     break             nextElem = succ(active, pos)             prevElem = pred(active, pos)              # If both neighbors exist, check if they intersect.             if nextElem is not None and prevElem is not None:                 key1 = str(nextElem.index + 1) + " " + str(prevElem.index + 1)                 key2 = str(prevElem.index + 1) + " " + str(nextElem.index + 1)                 if key1 not in mp and key2 not in mp and doIntersect(lines[prevElem.index], lines[nextElem.index]):                     ans += 1                 mp[key1] = 1              active.pop(pos)     for pr in mp:         print("Line: " + pr)     return ans  if __name__ == "__main__":     lines = [         [[1, 5], [4, 5]],         [[2, 5], [10, 1]],         [[3, 2], [10, 3]],         [[6, 4], [9, 4]],         [[7, 1], [8, 1]]     ]     print(isIntersect(lines)) 
C#
using System; using System.Collections.Generic;  public class GfG {      // An event for the sweep line algorithm     public class Event : IComparable<Event> {         public int x, y;         public bool isLeft;         public int index;         public Event(int x, int y, bool l, int i) {             this.x = x;             this.y = y;             this.isLeft = l;             this.index = i;         }                  // Order events by y-coordinate, then by x-coordinate         public int CompareTo(Event e) {             if(this.y == e.y)                 return this.x - e.x;             return this.y - e.y;         }                  public override bool Equals(object obj) {             if(obj == null || GetType() != obj.GetType())                 return false;             Event e = (Event)obj;             return this.x == e.x && this.y == e.y && this.isLeft == e.isLeft && this.index == e.index;         }                  public override int GetHashCode() {             return Tuple.Create(x, y, isLeft, index).GetHashCode();         }     }      // Given three collinear points p, q, r      // the function checks if point      // q lies on line segment 'pr'     public static bool onSegment(List<int> p, List<int> q, List<int> r) {         if (q[0] <= Math.Max(p[0], r[0]) && q[0] >= Math.Min(p[0], r[0]) &&             q[1] <= Math.Max(p[1], r[1]) && q[1] >= Math.Min(p[1], r[1]))             return true;         return false;     }      // To find orientation of ordered triplet (p, q, r).     // Returns 0 if collinear, 1 if clockwise, 2 if counterclockwise.     public static int orientation(List<int> p, List<int> q, List<int> r) {         int val = (q[1] - p[1]) * (r[0] - q[0]) -                   (q[0] - p[0]) * (r[1] - q[1]);                   // collinear         if (val == 0)             return 0;                   // clock- or counterclockwise         return (val > 0) ? 1 : 2;     }      // to fin dif two segments intersect     public static bool doIntersect(List<List<int>> s1, List<List<int>> s2) {         List<int> p1 = s1[0], q1 = s1[1], p2 = s2[0], q2 = s2[1];          int o1 = orientation(p1, q1, p2);         int o2 = orientation(p1, q1, q2);         int o3 = orientation(p2, q2, p1);         int o4 = orientation(p2, q2, q1);          // General case         if (o1 != o2 && o3 != o4)             return true;          // Special cases         if (o1 == 0 && onSegment(p1, p2, q1)) return true;         if (o2 == 0 && onSegment(p1, q2, q1)) return true;         if (o3 == 0 && onSegment(p2, p1, q2)) return true;         if (o4 == 0 && onSegment(p2, q1, q2)) return true;          return false;     }      // Returns the predecessor iterator in set s.     public static Event pred(SortedSet<Event> s, Event e) {         Event result = null;         foreach (var item in s) {             if (item.CompareTo(e) < 0)                 result = item;             else                 break;         }         return result;     }      // Returns the successor iterator in set s.     public static Event succ(SortedSet<Event> s, Event e) {         bool found = false;         foreach (var item in s) {             if (found)                 return item;             if (item.Equals(e))                 found = true;         }         return null;     }      // Returns the number of intersections found between segments.     public static int isIntersect(List<List<List<int>>> lines) {          // To avoid duplicate intersection reports.         Dictionary<string, int> mp = new Dictionary<string, int>();          List<Event> events = new List<Event>();         int n = lines.Count;         for (int i = 0; i < n; ++i) {              // Create events for the left and right endpoints.             events.Add(new Event(lines[i][0][0], lines[i][0][1], true, i));             events.Add(new Event(lines[i][1][0], lines[i][1][1], false, i));         }          // Sort events according to x-coordinate.         events.Sort((e1, e2) => e1.x - e2.x);          // Set for storing active segments.         SortedSet<Event> active = new SortedSet<Event>();         int ans = 0;          // Process all events.         for (int i = 0; i < 2 * n; i++) {             Event curr = events[i];             int index = curr.index;              if (curr.isLeft) {                  // For the left endpoint, get neighbors in the active set.                 Event next = null;                 foreach(var ev in active)                 {                     if(ev.CompareTo(curr) >= 0) { next = ev; break; }                 }                 Event prev = pred(active, curr);                  // Check for intersection with the next segment.                 if (next != null && doIntersect(lines[next.index], lines[index])) {                     string key = (next.index + 1).ToString() + " " + (index + 1).ToString();                     if (!mp.ContainsKey(key)) {                         mp[key] = 1;                         ans++;                     }                 }                  // Check for intersection with the previous segment.                 if (prev != null && doIntersect(lines[prev.index], lines[index])) {                     string key = (prev.index + 1).ToString() + " " + (index + 1).ToString();                     if (!mp.ContainsKey(key)) {                         mp[key] = 1;                         ans++;                     }                 }                  // To avoid counting duplicates if the same segment is both neighbor.                 if (prev != null && next != null && next.index == prev.index)                     ans--;                  active.Add(curr);             }              else {                  // For the right endpoint, find the matching left endpoint in the active set.                 Event temp = new Event(lines[index][0][0], lines[index][0][1], true, index);                 Event it = null;                 foreach (var ev in active) {                     if (ev.Equals(temp)) {                         it = ev;                         break;                     }                 }                 Event next = succ(active, it);                 Event prev = pred(active, it);                  // If both neighbors exist, check if they intersect.                 if (next != null && prev != null) {                     string key1 = (next.index + 1).ToString() + " " + (prev.index + 1).ToString();                     string key2 = (prev.index + 1).ToString() + " " + (next.index + 1).ToString();                     if (!mp.ContainsKey(key1) && !mp.ContainsKey(key2) && doIntersect(lines[prev.index], lines[next.index]))                         ans++;                     mp[key1] = 1;                 }                  // Remove the segment from the active set.                 active.Remove(it);             }         }          // Report all intersecting pairs.         foreach (var pr in mp) {             Console.WriteLine("Line: " + pr.Key);         }         return ans;     }      public static void Main(string[] args) {         List<List<List<int>>> lines = new List<List<List<int>>>();         lines.Add(new List<List<int>>{ new List<int>{1, 5}, new List<int>{4, 5} });         lines.Add(new List<List<int>>{ new List<int>{2, 5}, new List<int>{10, 1} });         lines.Add(new List<List<int>>{ new List<int>{3, 2}, new List<int>{10, 3} });         lines.Add(new List<List<int>>{ new List<int>{6, 4}, new List<int>{9, 4} });         lines.Add(new List<List<int>>{ new List<int>{7, 1}, new List<int>{8, 1} });         Console.WriteLine(isIntersect(lines));     } } 
JavaScript
class Event {     constructor(x, y, isLeft, index) {         this.x = x;         this.y = y;         this.isLeft = isLeft;         this.index = index;     }          // Order events by y-coordinate, then by x-coordinate     compareTo(e) {         if (this.y === e.y)             return this.x - e.x;         return this.y - e.y;     } }  function onSegment(p, q, r) {          // Given three collinear points p, q, r      // the function checks if point      // q lies on line segment 'pr'     if (q[0] <= Math.max(p[0], r[0]) && q[0] >= Math.min(p[0], r[0]) &&         q[1] <= Math.max(p[1], r[1]) && q[1] >= Math.min(p[1], r[1]))         return true;     return false; }  function orientation(p, q, r) {          // To find orientation of ordered triplet (p, q, r).     // Returns 0 if collinear, 1 if clockwise, 2 if counterclockwise.     let val = (q[1] - p[1]) * (r[0] - q[0]) -               (q[0] - p[0]) * (r[1] - q[1]);          // collinear     if (val === 0)         return 0;          // clock- or counterclockwise     return (val > 0) ? 1 : 2; }  function doIntersect(s1, s2) {          // to fin dif two segments intersect     let p1 = s1[0], q1 = s1[1], p2 = s2[0], q2 = s2[1];          let o1 = orientation(p1, q1, p2);     let o2 = orientation(p1, q1, q2);     let o3 = orientation(p2, q2, p1);     let o4 = orientation(p2, q2, q1);          // General case     if (o1 !== o2 && o3 !== o4)         return true;          // Special cases     if (o1 === 0 && onSegment(p1, p2, q1)) return true;     if (o2 === 0 && onSegment(p1, q2, q1)) return true;     if (o3 === 0 && onSegment(p2, p1, q2)) return true;     if (o4 === 0 && onSegment(p2, q1, q2)) return true;          return false; }  function pred(arr, pos) {          // Returns the predecessor iterator in set s.     return pos > 0 ? arr[pos - 1] : null; }  function succ(arr, pos) {          // Returns the successor iterator in set s.     return (pos + 1 < arr.length) ? arr[pos + 1] : null; }  function lowerBound(arr, elem) {          // Binary search to find the first element not less than elem.     let low = 0, high = arr.length;     while (low < high) {         let mid = Math.floor((low + high) / 2);         if (arr[mid].compareTo(elem) < 0)             low = mid + 1;         else             high = mid;     }     return low; }  function findIndex(arr, elem) {          // Finds index of elem in arr.     for (let i = 0; i < arr.length; i++) {         if (arr[i].x === elem.x && arr[i].y === elem.y && arr[i].isLeft === elem.isLeft && arr[i].index === elem.index)             return i;     }     return -1; }  function isIntersect(lines) {          // Returns the number of intersections found between segments.     // To avoid duplicate intersection reports.     let mp = {};          let events = [];     let n = lines.length;     for (let i = 0; i < n; ++i) {                  // Create events for the left and right endpoints.         events.push(new Event(lines[i][0][0], lines[i][0][1], true, i));         events.push(new Event(lines[i][1][0], lines[i][1][1], false, i));     }          // Sort events according to x-coordinate.     events.sort((e1, e2) => e1.x - e2.x);          // Set for storing active segments.     let active = [];     let ans = 0;          // Process all events.     for (let i = 0; i < 2 * n; i++) {         let curr = events[i];         let index = curr.index;                  if (curr.isLeft) {                          // For the left endpoint, get neighbors in the active set.             let pos = lowerBound(active, curr);             let next = pos < active.length ? active[pos] : null;             let prev = pred(active, pos);                          // Check for intersection with the next segment.             if (next !== null && doIntersect(lines[next.index], lines[index])) {                 let key = (next.index + 1).toString() + " " + (index + 1).toString();                 if (!(key in mp)) {                     mp[key] = 1;                     ans++;                 }             }                          // Check for intersection with the previous segment.             if (prev !== null && doIntersect(lines[prev.index], lines[index])) {                 let key = (prev.index + 1).toString() + " " + (index + 1).toString();                 if (!(key in mp)) {                     mp[key] = 1;                     ans++;                 }             }                          // To avoid counting duplicates if the same segment is both neighbor.             if (prev !== null && next !== null && next.index === prev.index)                 ans--;                          active.splice(lowerBound(active, curr), 0, curr);         }          else {                          // For the right endpoint, find the matching left endpoint in the active set.             let temp = new Event(lines[index][0][0], lines[index][0][1], true, index);             let pos = findIndex(active, temp);             let next = succ(active, pos);             let prev = pred(active, pos);                          // If both neighbors exist, check if they intersect.             if (next !== null && prev !== null) {                 let key1 = (next.index + 1).toString() + " " + (prev.index + 1).toString();                 let key2 = (prev.index + 1).toString() + " " + (next.index + 1).toString();                 if (!(key1 in mp) && !(key2 in mp) && doIntersect(lines[prev.index], lines[next.index]))                     ans++;                 mp[key1] = 1;             }                          active.splice(pos, 1);         }     }     for (let key in mp) {         console.log("Line: " + key);     }     return ans; }  let lines = [     [ [1, 5], [4, 5] ],     [ [2, 5], [10, 1] ],     [ [3, 2], [10, 3] ],     [ [6, 4], [9, 4] ],     [ [7, 1], [8, 1] ] ]; console.log(isIntersect(lines)); 

Output
Line: 2 3 Line: 1 2 2


Note: The above code does not handle cases when segments share end points (Same starting points or same ending points or same starting and ending points) because we handle all points in the same way without considering the line segment number. We have done that way to keep the code simple. The Event class currently compares events based only on y and x, and does not distinguish between segments with the same start point. To handle the common end points, we need to differentiate events more clearly in the comparator to avoid ambiguity between events with the same coordinates.

Time Complexity: O(n * log n), initially, sorting the points requires O(n log n) time. Next, each point is processed in O(log n) time, so processing all 2n points takes O(2n log n) time. This simplifies to an overall time complexity of O(n log n).
Space Complexity: O(n)


Next Article
Klee's Algorithm (Length Of Union Of Segments of a line)

K

kartik
Improve
Article Tags :
  • Geometric
  • DSA
  • Geometric-Lines
Practice Tags :
  • Geometric

Similar Reads

    Geometric Algorithms
    Geometric algorithms are a type of algorithm that deal with solving problems related to geometry. These algorithms are used to solve various geometric problems such as computing the area of a polygon, finding the intersection of geometric shapes, determining the convex hull of a set of points, and m
    4 min read

    Problems based on Pattern Printing

    Print lower triangle with alternate '*' and '#'
    Given a number N which denotes the number of rows, the task is to follow the below pattern to print the first N rows of it. Pattern: **#*#**#*#*#*#* Examples: Input: N = 2Output:**# Input: N = 6Output: **#*#**#*#*#*#**#*#*# Approach: Follow the below steps to implement the above pattern: Initialize
    4 min read
    Print the pattern 1*2*5*6 --3*4
    Given integer N, the task is to print an upside-down triangle where the left half is made of elements in the range [1, N*(N+1)/2] and the right half is made of elements in the range [N*(N+1)/2 + 1, N*(N+1)]. Examples: Input: N = 3 Output: 1*2*3*10*11*12 4*5*8*9 6*7 Input: n = 4Output:1*2*3*4*17*18*1
    6 min read
    Python Program to print the pattern 'G'
    In this article, we will learn how to print the pattern G using stars and white-spaces. Given a number n, we will write a program to print the pattern G over n lines or rows.Examples: Input : 7Output : *** * * * *** * * * * *** Input : 9Output : ***** * * * * *** * * * * * * ***** In this program, w
    2 min read
    Program to Print Pascal's Triangle
    Given an integer n, the task is to find the first n rows of Pascal's triangle. Pascal's triangle is a triangular array of binomial coefficients.Examples: Example1: The below image shows the Pascal's Triangle for n=4 Example2: The below image shows the Pascal's Triangle for n = 6 Table of Content[Nai
    15 min read
    Program to print pyramid pattern
    Write to program to print the pyramid pattern formed of stars Example : Input: n = 6 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * We strongly recommend you to minimize your browser and try this yourself first.The idea is to use two for loops for every part of the p
    5 min read
    Program to print the Diamond Shape
    Given a number n, write a program to print a diamond shape with 2n rows.Examples : C++ // C++ program to print diamond shape // with 2n rows #include <bits/stdc++.h> using namespace std; // Prints diamond pattern with 2n rows void printDiamond(int n) { int space = n - 1; // run loop (parent lo
    11 min read
    Hour-glass Pattern
    Given positive integer n, print numeric pattern in form of an hourglass.Examples : Input : rows_no = 7 Output : 1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 6 7 5 6 7 4 5 6 7 3 4 5 6 7 2 3 4 5 6 7 1 2 3 4 5 6 7 C++ // CPP code for hour glass // pattern. #include <iostream> using nam
    7 min read
    Program to print V and inverted-V pattern
    Inverted V pattern: Given the value of n, print the inverted V pattern.Examples : Input : n = 5 Output : E D D C C B B A A Input : n = 7 Output : G F F E E D D C C B B A A Below is the program to print the above pattern C++ // C++ Implementation to print the pattern #include <bits/stdc++.h> us
    8 min read
    Program to print hollow pyramid, diamond pattern and their modifications
    For Prerequisite : Loops, If Else Statement1. Hollow pyramid/triangle pattern The pattern is similar to pyramid pattern. The only difference is, we will replace all internal '#' or '*' characters by space character and we will print 2*N-1 (N = number of rows in pattern) '#' or '*' characters in last
    15+ min read
    Code to Generate the Map of India (With Explanation)
    Given an obfuscated code that generates the map of India, explain its working. The following code when executed generates the map of India. An obfuscated code is a code that has been deliberately made difficult to understand or difficult to read, typically for the purpose of hiding its logic or maki
    8 min read

    Problems based on Lines

    How to check if two given line segments intersect?
    Given two line segments represented as a 3D vector points[][][], where each line segment i is defined by its endpoints stored in points[i][0] and points[i][1] (each containing 2 integers), your task is to determine if these two line segments intersect with each other.Examples:Input: points[][][] = [
    10 min read
    Sweep Line Algorithm - Find if any Two Segments Intersect
    Given n line segments represented as a 3D vector points[][][], where each line segment i is defined by its endpoints stored in points[i][0] and points[i][1] (each containing 2 integers), your task is to determine if any two of these line segments intersect and find the number of intersection points.
    15+ min read
    Klee's Algorithm (Length Of Union Of Segments of a line)
    Given starting and ending positions of segments on a line, the task is to take the union of all given segments and find length covered by these segments.Examples: Input : segments[] = {{2, 5}, {4, 8}, {9, 12}} Output : 9 Explanation: segment 1 = {2, 5} segment 2 = {4, 8} segment 3 = {9, 12} If we ta
    9 min read
    Count maximum points on same line
    Given N point on a 2D plane as pair of (x, y) co-ordinates, we need to find maximum number of point which lie on the same line. Examples: Input : points[] = {-1, 1}, {0, 0}, {1, 1}, {2, 2}, {3, 3}, {3, 4} Output : 4 Then maximum number of point which lie on same line are 4, those point are {0, 0}, {
    10 min read
    Minimum lines to cover all points
    Given N points in 2-dimensional space, we need to print the count of the minimum number of lines which traverse through all these N points and which go through a specific (xO, yO) point also.Examples: If given points are (-1, 3), (4, 3), (2, 1), (-1, -2), (3, -3) and (xO, yO) point is (1, 0) i.e. ev
    9 min read
    Represent a given set of points by the best possible straight line
    Find the value of m and c such that a straight line y = mx + c, best represents the equation of a given set of points (x_1 , y_1 ), (x_2 , y_2 ), (x_3 , y_3 ), ......., (x_n , y_n ), given n >=2. Examples: Input : n = 5 x_1 = 1, x_2 = 2, x_3 = 3, x_4 = 4, x_5 = 5y_1 = 14, y_2 = 27, y_3 = 40, y_4
    10 min read
    Program to find line passing through 2 Points
    Given two points P and Q in the coordinate plane, find the equation of the line passing through both points.This kind of conversion is very useful in many geometric algorithms like intersection of lines, finding the circumcenter of a triangle, finding the incenter of a triangle and many more... Exam
    6 min read
    Reflection of a point about a line in C++
    Let’s first consider a general case where the line is nothing but the X-Axis. We can now definitely say that the conjugate of a point is the reflection of the point about X-Axis.Now, using the methods of translation and rotation of coordinate axes we will find out the reflection of a point about the
    4 min read
    Program to find the mid-point of a line
    Given two coordinates of a line starting is (x1,y1) and ending is (x2,y2) find out the mid-point of a line. Examples : Input : x1 = –1, y1 = 2, x2 = 3, y2 = –6 Output : 1,–2 Input : x1 = 6.4, y1 = 3 x2 = –10.7, y2 = 4 Output : –2.15, 3.5 The Midpoint Formula: The midpoint of two points, (x1, y2) and
    3 min read
    Sum of Manhattan distances between all pairs of points
    Given n integer coordinates. The task is to find the sum of the Manhattan distance between all pairs of coordinates. Manhattan Distance between (x1, y1) and (x2, y2) is: |x1 - x2| + |y1 - y2|Examples : Input : n = 4, p1 = { -1, 5 }, p2 = { 1, 6 }, p3 = { 3, 5 }, p4 = { 2, 3 }Output : 22Explanation :
    9 min read
    Program to check if three points are collinear
    Given three points, check whether they lie on a straight (collinear) or notExamples : Input : (1, 1), (1, 4), (1, 5) Output : Yes The points lie on a straight line Input : (1, 5), (2, 5), (4, 6) Output : No The points do not lie on a straight line First approach Three points lie on the straight line
    9 min read

    Problems based on Triangles

    Check whether a given point lies inside a triangle or not
    Given three corner points of a triangle, and one more point P. Write a function to check whether P lies within the triangle or not. Example: Input: A = (0, 0), B = (10, 30), C = (20, 0), P(10, 15)Output: InsideExplanation: B(10,30) / \ / \ / \ / P \ P' / \ A(0,0) ----------- C(20,0) Input: A = (0, 0
    15+ min read
    Program to find area of a triangle
    Given the sides of a triangle, the task is to find the area of this triangle. Examples : Input : a = 5, b = 7, c = 8 Output : Area of a triangle is 17.320508 Input : a = 3, b = 4, c = 5 Output : Area of a triangle is 6.000000Recommended PracticeArea of a triangleTry It! Approach: The area of a trian
    10 min read
    Count Integral points inside a Triangle
    Given three non-collinear integral points in XY plane, find the number of integral points inside the triangle formed by the three points. (A point in XY plane is said to be integral/lattice point if both its co-ordinates are integral). Example: Input: p = (0, 0), q = (0, 5) and r = (5,0) Output: 6Ex
    8 min read
    Maximum number of 2x2 squares that can be fit inside a right isosceles triangle
    What is the maximum number of squares of size 2x2 units that can be fit in a right-angled isosceles triangle of a given base (in units). A side of the square must be parallel to the base of the triangle. Examples: Input : 8Output : 6Explanation: We get total 6 squares ( 1 + 2 + 3). Please refer the
    3 min read
    Find all angles of a given triangle
    Given coordinates of all three vertices of the triangle in the 2D plane, the task is to find all three angles.Example: Input : A = (0, 0), B = (0, 1), C = (1, 0) Output : 90, 45, 45 To solve this problem we use below Law of cosines. c^2 = a^2 + b^2 - 2(a)(b)(cos beta) After re-arranging beta = acos(
    7 min read
    Check if right triangle possible from given area and hypotenuse
    Given area and hypotenuse, the aim is to print all sides if right triangle can exist, else print -1. We need to print all sides in ascending order. Examples: Input : 6 5 Output : 3 4 5 Input : 10 6 Output : -1 We have discussed a solution of this problem in below post. Find all sides of a right angl
    6 min read
    Number of Triangles that can be formed given a set of lines in Euclidean Plane
    Given a set L = {l1, l2, ……..., ln} of ‘n’ distinct lines on the Euclidean Plane. The ith line is given by an equation in the form aix + biy = ci. Find the number of triangles that can be formed using the lines in the set L. Note that no two pairs of lines intersect at the same point. Note: This pro
    13 min read
    Program to calculate area of Circumcircle of an Equilateral Triangle
    Given the length of sides of an equilateral triangle. We need to write a program to find the area of Circumcircle of the given equilateral triangle.Examples: Input : side = 6 Output : Area of circumscribed circle is: 37.69 Input : side = 9 Output : Area of circumscribed circle is: 84.82 All three si
    4 min read
    Program to calculate area and perimeter of equilateral triangle
    An equilateral triangle is a triangle in which all three sides and angles are equal. All three internal angles of equilateral triangle measures 60 degree. If we know the length of each sides of equilateral triangle, then we can use below mentioned formula to calculate area of equilateral triangle.Ar
    4 min read
    Minimum height of a triangle with given base and area
    Given two integers a and b, find the smallest possible height such that a triangle of at least area "a" and base "b" can be formed.Examples: Input : a = 2, b = 2Output : Minimum height of triangle is 2Explanation: Input : a = 8, b = 4Output : Minimum height of triangle is 4Minimum height of Triangle
    5 min read

    Problems based on Rectangle, Square and Circle

    Find if two rectangles overlap
    Given two rectangles, find if the given two rectangles overlap or not.Note that a rectangle can be represented by two coordinates, top left and bottom right. So mainly we are given following four coordinates. l1: Top Left coordinate of first rectangle. r1: Bottom Right coordinate of first rectangle.
    5 min read
    Check if four segments form a rectangle
    We are given four segments as a pair of coordinates of their end points. We need to tell whether those four line segments make a rectangle or not. Examples: Input : segments[] = [(4, 2), (7, 5), (2, 4), (4, 2), (2, 4), (5, 7), (5, 7), (7, 5)] Output : Yes Given these segment make a rectangle of leng
    9 min read
    Minimum Perimeter of n blocks
    We are given n blocks of size 1 x 1, we need to find the minimum perimeter of the grid made by these blocks.Examples : Input : n = 4Output : 8Minimum possible perimeter with 4 blocksis 8. See below explanation.Input : n = 11Output : 14The square grid of above examples would be as Let us take an exam
    5 min read
    Number of rectangles in N*M grid
    We are given a N*M grid, print the number of rectangles in it.Examples: Input : N = 2, M = 2Output : 9There are 4 rectangles of size 1 x 1.There are 2 rectangles of size 1 x 2There are 2 rectangles of size 2 x 1There is one rectangle of size 2 x 2.Input : N = 5, M = 4Output : 150Input : N = 4, M = 3
    7 min read
    Coordinates of rectangle with given points lie inside
    Given two arrays X[] and Y[] with n-elements, where (Xi, Yi) represent a point on coordinate system, find the smallest rectangle such that all points from given input lie inside that rectangle and sides of rectangle must be parallel to Coordinate axis. Print all four coordinates of an obtained recta
    6 min read
    Program for Area Of Square
    A square is a flat shape, in one plane, defined by four points at the four corners. A square has four sides all of equal length, and four corners, all right angles (90 degree angles). A square is a kind of rectangle. Examples : Input : 4 Output :16 Input :8 Output :64 Formula Area = side*side C++ //
    2 min read
    Circle and Lattice Points
    Given a circle of radius r in 2-D with origin or (0, 0) as center. The task is to find the total lattice points on circumference. Lattice Points are points with coordinates as integers in 2-D space.Example: Input : r = 5.Output : 12Below are lattice points on a circle withradius 5 and origin as (0,
    6 min read
    Pizza cut problem (Or Circle Division by Lines)
    Given number of cuts, find the maximum number of possible pieces.Examples: Input : 2 Output : 4 Input : 3 Output : 7 This problem is nothing but The Lazy Caterer’s Problem and has below formula.Maximum number of pieces = 1 + n*(n+1)/2Refer this for proof. C++ // C++ program to find maximum no of pie
    2 min read
    Angular Sweep (Maximum points that can be enclosed in a circle of given radius)
    Given ‘n’ points on the 2-D plane, find the maximum number of points that can be enclosed by a fixed-radius circle of radius ‘R’. Note: The point is considered to be inside the circle even when it lies on the circumference. Examples:  Input: R = 1 points[] = {(6.47634, 7.69628), (5.16828 4.79915), (
    15 min read
    Check if a line touches or intersects a circle
    Given coordinate of the center and radius > 1 of a circle and the equation of a line. The task is to check if the given line collides with the circle or not. There are three possibilities : Line intersects the circle.Line touches the circle.Line is outside the circle Note: General equation of a l
    6 min read
    Area of a Circumscribed Circle of a Square
    Given the side of a square then find the area of a Circumscribed circle around it.Examples: Input : a = 6 Output : Area of a circumscribed circle is : 56.55 Input : a = 4 Output : Area of a circumscribed circle is : 25.13 All four sides of a square are of equal length and all four angles are 90 degr
    3 min read
    Area of square Circumscribed by Circle
    Given the radius(r) of circle then find the area of square which is Circumscribed by circle.Examples: Input : r = 3Output :Area of square = 18Input :r = 6Output :Area of square = 72 All four sides of a square are of equal length and all four angles are 90 degree. The circle is circumscribed on a giv
    4 min read
    Program to find area of a Circular Segment
    In a circle, if a chord is drawn then that chord divides the whole circle into two parts. These two parts of the circle are called segments of the circle. The smaller area is known as the Minor segment and the larger area is called as the Major segment.In the figure below, the chord AB divides the c
    6 min read
    Arc length from given Angle
    An angle is a geometrical figure when two rays meet at a common point on a plane. These rays form the sides of the angle and the meeting point is referred as the vertex of the angle. There is something that we need to keep in mind that the plane that forms an angle doesn't need to be a Euclidean pla
    4 min read
    Program to find Circumference of a Circle
    Given radius of a circle, write a program to find its circumference.Examples : Input : 2 Output : Circumference = 12.566 Input : 8 Output : Circumference = 50.264 In a circle, points lie in the boundary of a circle are at same distance from its center. This distance is called radius. Circumference o
    3 min read
    Check if two given circles touch or intersect each other
    There are two circles A and B with their centres C1(x1, y1) and C2(x2, y2) and radius R1 and R2. The task is to check both circles A and B touch each other or not. Examples : Input : C1 = (3, 4) C2 = (14, 18) R1 = 5, R2 = 8Output : Circles do not touch each other. Input : C1 = (2, 3) C2 = (15, 28) R
    5 min read

    Problems based on 3D Objects

    Find the perimeter of a cylinder
    Given diameter and height, find the perimeter of a cylinder.Perimeter is the length of the outline of a two - dimensional shape. A cylinder is a three - dimensional shape. So, technically we cannot find the perimeter of a cylinder but we can find the perimeter of the cross-section of the cylinder. T
    3 min read
    Find the Surface area of a 3D figure
    Given a N*M matrix A[][] representing a 3D figure. The height of the building at (i, j) is A[i][j] . Find the surface area of the figure. Examples : Input : N = 1, M = 1 A[][] = { {1} } Output : 6 Explanation : The total surface area is 6 i.e 6 side of the figure and each are of height 1. Input : N
    11 min read
    Calculate Volume of Dodecahedron
    Given the edge of the dodecahedron calculate its Volume. Volume is the amount of the space which the shapes takes up. A dodecahedron is a 3-dimensional figure made up of 12 faces, or flat sides. All of the faces are pentagons of the same size.The word 'dodecahedron' comes from the Greek words dodeca
    3 min read
    Program to calculate volume of Octahedron
    Given the side of the Octahedron then calculate the volume of Octahedron. Examples: Input : 3 Output : 12.7279 Input : 7 Output : 161.692 Approach: The volume of an octahedron is given by the formula: Volume = √2/3 × a3 where a is the side of Octahedron Below is the implementation to calculate volum
    2 min read
    Program to calculate Volume and Surface area of Hemisphere
    Calculate volume and surface area of a hemisphere. Hemisphere : In geometry, it is an exact half of a sphere. We can find many of the real life examples of the hemispheres such as our planet Earth can be divided into two hemisphere the southern & northern hemispheres.   Volume of Hemisphere : Vo
    4 min read
    Program for volume of Pyramid
    A pyramid is a 3-dimensional geometric shape formed by connecting all the corners of a polygon to a central apex. There are many types of pyramids. Most often, they are named after the type of base they have. Let's look at some common types of pyramids below. Volume of a square pyramid [base of Pyra
    7 min read
    Program to calculate volume of Ellipsoid
    Ellipsoid, closed surface of which all plane cross sections are either ellipses or circles. An ellipsoid is symmetrical about three mutually perpendicular axes that intersect at the center. It is a three-dimensional, closed geometric shape, all planar sections of which are ellipses or circles. An el
    4 min read
    Program for Volume and Surface Area of Cube
    Cube is a 3-dimensional box-like figure represented in the 3-dimensional plane. Cube has 6 squared-shape equal faces. Each face meet another face at 90 degree each. Three sides of cube meet at same vertex. Examples: Input : Side of a cube = 2 Output : Area = 8 Total surface area = 24 Input : Side of
    3 min read

    Problems based on Quadrilateral

    Number of parallelograms when n horizontal parallel lines intersect m vertical parallel lines
    Given two positive integers n and m. The task is to count number of parallelogram that can be formed of any size when n horizontal parallel lines intersect with m vertical parallel lines. Examples: Input : n = 3, m = 2Output : 32 parallelograms of size 1x1 and 1 parallelogram of size 2x1.Input : n =
    8 min read
    Program for Circumference of a Parallelogram
    Given the sides of Parallelogram then calculate the circumference.Examples : Input: a = 10, b = 8 Output: 36.00 Input: a = 25.12, b = 20.4 Output: 91.04 The opposite sides of a parallelogram are of equal length and parallel. The angles are pairwise equal but not necessarily 90 degree. The circumfere
    3 min read
    Program to calculate area and perimeter of Trapezium
    A trapezium is a quadrilateral with at least one pair of parallel sides, other two sides may not be parallel. The parallel sides are called the bases of the trapezium and the other two sides are called it's legs. The perpendicular distance between parallel sides is called height of trapezium. Formul
    5 min read
    Program to find area of a Trapezoid
    Definition of Trapezoid : A Trapezoid is a convex quadrilateral with at least one pair of parallel sides. The parallel sides are called the bases of the trapezoid and the other two sides which are not parallel are referred to as the legs. There can also be two pairs of bases. In the above figure CD
    4 min read
    Find all possible coordinates of parallelogram
    Find all the possible coordinates from the three coordinates to make a parallelogram of a non-zero area.Let's call A, B, and C are the three given points. We can have only the three possible situations:  (1) AB and AC are sides, and BC a diagonal(2) AB and BC are sides, and AC a diagonal (3) BC and
    5 min read
    Maximum area of quadrilateral
    Given four sides of quadrilateral a, b, c, d, find the maximum area of the quadrilateral possible from the given sides .Examples:  Input : 1 2 1 2Output : 2.00It is optimal to construct a rectangle for maximum area .  According to Bretschneider's formula, the area of a general quadrilateral is given
    5 min read
    Check whether four points make a parallelogram
    Given four points in a 2-dimensional space we need to find out whether they make a parallelogram or not. A parallelogram has four sides. Two opposite sides are parallel and are of same lengths. Examples:Points = [(0, 0), (4, 0), (1, 3), (5, 3)]Above points make a parallelogram.Points = [(0, 0), (2,
    15+ min read
    Find the Missing Point of Parallelogram
    Given three coordinate points A, B and C, find the missing point D such that ABCD can be a parallelogram.Examples : Input : A = (1, 0) B = (1, 1) C = (0, 1) Output : 0, 0 Explanation: The three input points form a unit square with the point (0, 0) Input : A = (5, 0) B = (1, 1) C = (2, 5) Output : 6,
    13 min read

    Problems based on Polygon and Convex Hull

    How to check if a given point lies inside or outside a polygon?
    Given a polygon and a point 'p', find if 'p' lies inside the polygon or not. The points lying on the border are considered inside. Examples: Recommended ProblemPlease solve it on PRACTICE first, before moving on to the solution Solve ProblemApproach: The idea to solve this problem is based on How to
    9 min read
    Area of a polygon with given n ordered vertices
    Given ordered coordinates of a polygon with n vertices. Find the area of the polygon. Here ordered means that the coordinates are given either in a clockwise manner or anticlockwise from the first vertex to last.Examples : Input : X[] = {0, 4, 4, 0}, Y[] = {0, 0, 4, 4}; Output : 16 Input : X[] = {0,
    6 min read
    Tangents between two Convex Polygons
    Given two convex polygons, we aim to identify the lower and upper tangents connecting them. As shown in the figure below, TRL and TLR represent the upper and lower tangents, respectively. Examples: Input: First Polygon : [[2, 2], [3, 3], [5, 2], [4, 0], [3, 1]] Second Polygon : [[-1, 0], [0, 1], [1,
    15 min read
    Find number of diagonals in n sided convex polygon
    Given n > 3, find number of diagonals in n sided convex polygon.According to Wikipedia, In geometry, a diagonal is a line segment joining two vertices of a polygon or polyhedron, when those vertices are not on the same edge. Informally, any sloping line is called diagonal.Examples : Input : 5Outp
    3 min read
    Convex Hull using Jarvis' Algorithm or Wrapping
    Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it.We strongly recommend to see the following post first. How to check if two given line segments intersect?The idea of Jarvis's Algorithm is simple, we start from the leftmo
    13 min read
    Convex Hull using Graham Scan
    A convex hull is the smallest convex polygon that contains a given set of points. It is a useful concept in computational geometry and has applications in various fields such as computer graphics, image processing, and collision detection.A convex polygon is a polygon in which all interior angles ar
    15+ min read
    Dynamic Convex hull | Adding Points to an Existing Convex Hull
    Given a convex hull, we need to add a given number of points to the convex hull and print the convex hull after every point addition. The points should be in anti-clockwise order after addition of every point. Examples: Input : Convex Hull : (0, 0), (3, -1), (4, 5), (-1, 4) Point to add : (100, 100)
    15 min read
    Deleting points from Convex Hull
    Given a fixed set of points. We need to find convex hull of given set. We also need to find convex hull when a point is removed from the set. Example: Initial Set of Points: (-2, 8) (-1, 2) (0, 1) (1, 0) (-3, 0) (-1, -9) (2, -6) (3, 0) (5, 3) (2, 5) Initial convex hull:- (-2, 8) (-3, 0) (-1, -9) (2,
    15+ min read
    Minimum area of a Polygon with three points given
    Given three points of a regular polygon(n > 3), find the minimum area of a regular polygon (all sides same) possible with the points given.Examples: Input : 0.00 0.00 1.00 1.00 0.00 1.00 Output : 1.00 By taking point (1.00, 0.00) square is formed of side 1.0 so area = 1.00 . One thing to note in
    13 min read
    Find Simple Closed Path for a given set of points
    Given a set of points, connect the dots without crossing. Example: Input: points[] = {(0, 3), (1, 1), (2, 2), (4, 4), (0, 0), (1, 2), (3, 1}, {3, 3}}; Output: Connecting points in following order would not cause any crossing {(0, 0), (3, 1), (1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (0, 3)} We strongl
    11 min read
    Minimum Distance between Two Points
    You are given an array arr[] of n distinct points in a 2D plane, where each point is represented by its (x, y) coordinates. Find the minimum Euclidean distance between two distinct points.Note: For two points A(px,qx) and B(py,qy) the distance Euclidean between them is:Distance = \sqrt{(p_{x}-q_{x})
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences