Tasks Details
hard
Compute the total length covered by 1-dimensional segments.
Task Score
100%
Correctness
100%
Performance
Not assessed
You are given a table segments with the following structure:
create table segments ( l integer not null, r integer not null, check(l <= r), unique(l,r) );Each record in this table represents a contiguous segment of a line, from l to r inclusive. Its length equals r − l.
Consider the parts of a line covered by the segments. Write an SQL query that returns the total length of all the parts of the line covered by the segments specified in the table segments. Please note that any parts of the line that are covered by several overlapping segments should be counted only once.
For example, given:
l | r --+-- 1 | 5 2 | 3 4 | 6your query should return 5, as the segments cover the part of the line from 1 to 6.
Copyright 2009–2024 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Solution
Programming language used SQL (SQLite)
Time spent on task 1 minutes
Notes
not defined yet
Task timeline
Code: 09:41:12 UTC,
sql,
verify,
result: Passed
SELECT Ifnull(SUM(r - l), 0)
FROM ( SELECT DISTINCT
r ,
( SELECT MAX(x)
FROM ( SELECT l AS x
FROM segments
UNION
SELECT r AS x
FROM segments
) AS pois
WHERE x < r
) AS l
FROM ( SELECT x AS r
FROM segments
JOIN ( SELECT l AS x
FROM segments
UNION
SELECT r AS x
FROM segments
) AS pois ON x > l
AND x <= r
) AS rights
) AS chopped_segments
Analysis
Code: 09:41:18 UTC,
sql,
verify,
result: Passed
SELECT Ifnull(SUM(r - l), 0)
FROM ( SELECT DISTINCT
r ,
( SELECT MAX(x)
FROM ( SELECT l AS x
FROM segments
UNION
SELECT r AS x
FROM segments
) AS pois
WHERE x < r
) AS l
FROM ( SELECT x AS r
FROM segments
JOIN ( SELECT l AS x
FROM segments
UNION
SELECT r AS x
FROM segments
) AS pois ON x > l
AND x <= r
) AS rights
) AS chopped_segments
Analysis
Code: 09:41:20 UTC,
sql,
final,
score: 
100
SELECT Ifnull(SUM(r - l), 0)
FROM ( SELECT DISTINCT
r ,
( SELECT MAX(x)
FROM ( SELECT l AS x
FROM segments
UNION
SELECT r AS x
FROM segments
) AS pois
WHERE x < r
) AS l
FROM ( SELECT x AS r
FROM segments
JOIN ( SELECT l AS x
FROM segments
UNION
SELECT r AS x
FROM segments
) AS pois ON x > l
AND x <= r
) AS rights
) AS chopped_segments
Analysis summary
The solution obtained perfect score.
Analysis
expand all
Correctness tests
1.
0.224 s
OK
1.
0.223 s
OK
1.
0.225 s
OK
1.
0.226 s
OK
1.
0.225 s
OK
2.
0.224 s
OK
1.
0.223 s
OK
2.
0.224 s
OK
1.
0.225 s
OK
1.
0.224 s
OK
1.
0.224 s
OK
1.
0.222 s
OK
1.
0.225 s
OK
1.
2.303 s
OK
1.
6.122 s
OK
1.
1.270 s
OK
1.
0.315 s
OK