Klee's Algorithm (Length Of Union Of Segments of a line)
Last Updated :
22 Feb, 2023
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 take the union of all the line segments,
we cover distances [2, 8] and [9, 12]. Sum of
these two distances is 9 (6 + 3)
Approach:
The algorithm was proposed by Klee in 1977. The time complexity of the algorithm is O (N log N). It has been proven that this algorithm is the fastest (asymptotically) and this problem can not be solved with a better complexity.
Description :
1) Put all the coordinates of all the segments in an auxiliary array points[].
2) Sort it on the value of the coordinates.
3) An additional condition for sorting - if there are equal coordinates, insert the one which is the left coordinate of any segment instead of a right one.
4) Now go through the entire array, with the counter "count" of overlapping segments.
5) If the count is greater than zero, then the result is added to the difference between the points[i] - points[i-1].
6) If the current element belongs to the left end, we increase "count", otherwise reduce it.
Illustration:
Lets take the example :
segment 1 : (2,5)
segment 2 : (4,8)
segment 3 : (9,12)
Counter = result = 0;
n = number of segments = 3;
for i=0, points[0] = {2, false}
points[1] = {5, true}
for i=1, points[2] = {4, false}
points[3] = {8, true}
for i=2, points[4] = {9, false}
points[5] = {12, true}
Therefore :
points = {2, 5, 4, 8, 9, 12}
{f, t, f, t, f, t}
after applying sorting :
points = {2, 4, 5, 8, 9, 12}
{f, f, t, t, f, t}
Now,
for i=0, result = 0;
Counter = 1;
for i=1, result = 2;
Counter = 2;
for i=2, result = 3;
Counter = 1;
for i=3, result = 6;
Counter = 0;
for i=4, result = 6;
Counter = 1;
for i=5, result = 9;
Counter = 0;
Final answer = 9;
C++
// C++ program to implement Klee's algorithm
#include<bits/stdc++.h>
using namespace std;
// Returns sum of lengths covered by union of given
// segments
int segmentUnionLength(const vector<
pair <int,int> > &seg)
{
int n = seg.size();
// Create a vector to store starting and ending
// points
vector <pair <int, bool> > points(n * 2);
for (int i = 0; i < n; i++)
{
points[i*2] = make_pair(seg[i].first, false);
points[i*2 + 1] = make_pair(seg[i].second, true);
}
// Sorting all points by point value
sort(points.begin(), points.end());
int result = 0; // Initialize result
// To keep track of counts of
// current open segments
// (Starting point is processed,
// but ending point
// is not)
int Counter = 0;
// Traverse through all points
for (unsigned i=0; i<n*2; i++)
{
// If there are open points, then we add the
// difference between previous and current point.
// This is interesting as we don't check whether
// current point is opening or closing,
if (Counter)
result += (points[i].first -
points[i-1].first);
// If this is an ending point, reduce, count of
// open points.
(points[i].second)? Counter-- : Counter++;
}
return result;
}
// Driver program for the above code
int main()
{
vector< pair <int,int> > segments;
segments.push_back(make_pair(2, 5));
segments.push_back(make_pair(4, 8));
segments.push_back(make_pair(9, 12));
cout << segmentUnionLength(segments) << endl;
return 0;
}
Java
// Java program to implement Klee's algorithm
import java.io.*;
import java.util.*;
class GFG {
// to use create a pair of segments
static class SegmentPair
{
int x,y;
SegmentPair(int xx, int yy){
this.x = xx;
this.y = yy;
}
}
//to create a pair of points
static class PointPair{
int x;
boolean isEnding;
PointPair(int xx, boolean end){
this.x = xx;
this.isEnding = end;
}
}
// creates the comparator for comparing objects of PointPair class
static class Comp implements Comparator<PointPair>
{
// override the compare() method
public int compare(PointPair p1, PointPair p2)
{
if (p1.x < p2.x) {
return -1;
}
else {
if(p1.x == p2.x){
return 0;
}else{
return 1;
}
}
}
}
public static int segmentUnionLength(List<SegmentPair> segments){
int n = segments.size();
// Create a list to store
// starting and ending points
List<PointPair> points = new ArrayList<>();
for(int i = 0; i < n; i++){
points.add(new PointPair(segments.get(i).x,false));
points.add(new PointPair(segments.get(i).y,true));
}
// Sorting all points by point value
Collections.sort(points, new Comp());
int result = 0; // Initialize result
// To keep track of counts of
// current open segments
// (Starting point is processed,
// but ending point
// is not)
int Counter = 0;
// Traverse through all points
for(int i = 0; i < 2 * n; i++)
{
// If there are open points, then we add the
// difference between previous and current point.
// This is interesting as we don't check whether
// current point is opening or closing,
if (Counter != 0)
{
result += (points.get(i).x - points.get(i-1).x);
}
// If this is an ending point, reduce, count of
// open points.
if(points.get(i).isEnding)
{
Counter--;
}
else
{
Counter++;
}
}
return result;
}
// Driver Code
public static void main (String[] args) {
List<SegmentPair> segments = new ArrayList<>();
segments.add(new SegmentPair(2,5));
segments.add(new SegmentPair(4,8));
segments.add(new SegmentPair(9,12));
System.out.println(segmentUnionLength(segments));
}
}
// This code is contributed by shruti456rawal
Python3
# Python program for the above approach
def segmentUnionLength(segments):
# Size of given segments list
n = len(segments)
# Initialize empty points container
points = [None] * (n * 2)
# Create a vector to store starting
# and ending points
for i in range(n):
points[i * 2] = (segments[i][0], False)
points[i * 2 + 1] = (segments[i][1], True)
# Sorting all points by point value
points = sorted(points, key=lambda x: x[0])
# Initialize result as 0
result = 0
# To keep track of counts of current open segments
# (Starting point is processed, but ending point
# is not)
Counter = 0
# Traverse through all points
for i in range(0, n * 2):
# If there are open points, then we add the
# difference between previous and current point.
if (i > 0) & (points[i][0] > points[i - 1][0]) & (Counter > 0):
result += (points[i][0] - points[i - 1][0])
# If this is an ending point, reduce, count of
# open points.
if points[i][1]:
Counter -= 1
else:
Counter += 1
return result
# Driver code
if __name__ == '__main__':
segments = [(2, 5), (4, 8), (9, 12)]
print(segmentUnionLength(segments))
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
// C# program to implement Klee's algorithm
class HelloWorld {
class GFG : IComparer<KeyValuePair<int, bool>>
{
public int Compare(KeyValuePair<int, bool> x,KeyValuePair<int, bool> y)
{
// CompareTo() method
return x.Key.CompareTo(y.Key);
}
}
// Returns sum of lengths covered by union of given
// segments
public static int segmentUnionLength(List<KeyValuePair<int,int>> seg)
{
int n = seg.Count;
// Create a vector to store starting and ending
// points
List<KeyValuePair<int, bool>> points = new List<KeyValuePair<int, bool>>();
for(int i = 0; i < 2*n; i++){
points.Add(new KeyValuePair<int, bool> (0,true));
}
for (int i = 0; i < n; i++)
{
points[i*2] = new KeyValuePair<int, bool> (seg[i].Key, false);
points[i*2 + 1] = new KeyValuePair<int, bool> (seg[i].Value, true);
}
// Sorting all points by point value
GFG gg = new GFG();
points.Sort(gg);
int result = 0; // Initialize result
// To keep track of counts of
// current open segments
// (Starting point is processed,
// but ending point
// is not)
int Counter = 0;
// Traverse through all points
for (int i=0; i<n*2; i++)
{
// If there are open points, then we add the
// difference between previous and current point.
// This is interesting as we don't check whether
// current point is opening or closing,
if (Counter != 0)
result += (points[i].Key - points[i-1].Key);
// If this is an ending point, reduce, count of
// open points.
if(points[i].Value != false){
Counter--;
}
else{
Counter++;
}
}
return result;
}
static void Main() {
List<KeyValuePair<int,int>> segments = new List<KeyValuePair<int,int>> ();
segments.Add(new KeyValuePair<int,int> (2, 5));
segments.Add(new KeyValuePair<int,int> (4, 8));
segments.Add(new KeyValuePair<int,int> (9, 12));
Console.WriteLine(segmentUnionLength(segments));
}
}
// The code is contributed by Nidhi goel.
JavaScript
// JavaScript program to implement Klee's algorithm
// Returns sum of lengths covered by union of given
// segments
function segmentUnionLength(seg)
{
let n = seg.length;
// Create a vector to store starting and ending
// points
let points = new Array(2*n);
for (let i = 0; i < n; i++)
{
points[i*2] = [seg[i][0], false];
points[i*2 + 1] = [seg[i][1], true];
}
// Sorting all points by point value
points.sort(function(a, b){
return a[0] - b[0];
});
let result = 0; // Initialize result
// To keep track of counts of
// current open segments
// (Starting point is processed,
// but ending point
// is not)
let Counter = 0;
// Traverse through all points
for (let i=0; i<n*2; i++)
{
// If there are open points, then we add the
// difference between previous and current point.
// This is interesting as we don't check whether
// current point is opening or closing,
if (Counter)
result += (points[i][0] - points[i-1][0]);
// If this is an ending point, reduce, count of
// open points.
if(points[i][1]){
Counter = Counter - 1;
}
else{
Counter = Counter + 1;
}
}
return result;
}
let segments = new Array();
segments.push([2, 5]);
segments.push([4, 8]);
segments.push([9, 12]);
console.log(segmentUnionLength(segments));
// The code is contributed by Gautam goel (gautamgoel962)
Time Complexity : O(n * log n)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem