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: 23:41:54 UTC,
sql,
verify,
result: Passed
SELECT
IFNULL(SUM(r-sub_l),0)
FROM
(
SELECT
DISTINCT r,
(SELECT
MAX(x)
FROM
(SELECT
DISTINCT l AS x
FROM
segments
UNION
SELECT
DISTINCT r AS x
FROM
segments
) AS r2
WHERE
r2.x<r1.r
) AS sub_l
FROM
(SELECT
*
FROM
(SELECT
r1.l AS l,
r2.l AS r
FROM
segments AS r1
JOIN
segments AS r2
ON
r2.l >= r1.l AND r2.l <= r1.r
UNION
SELECT
r1.l AS l,
r2.r AS r
FROM
segments AS r1
JOIN
segments AS r2
ON
r2.r >= r1.l AND r2.r <= r1.r
) AS r1 WHERE l!=r
) AS r1
) AS r1
Analysis
Code: 23:42:01 UTC,
sql,
verify,
result: Passed
SELECT
IFNULL(SUM(r-sub_l),0)
FROM
(
SELECT
DISTINCT r,
(SELECT
MAX(x)
FROM
(SELECT
DISTINCT l AS x
FROM
segments
UNION
SELECT
DISTINCT r AS x
FROM
segments
) AS r2
WHERE
r2.x<r1.r
) AS sub_l
FROM
(SELECT
*
FROM
(SELECT
r1.l AS l,
r2.l AS r
FROM
segments AS r1
JOIN
segments AS r2
ON
r2.l >= r1.l AND r2.l <= r1.r
UNION
SELECT
r1.l AS l,
r2.r AS r
FROM
segments AS r1
JOIN
segments AS r2
ON
r2.r >= r1.l AND r2.r <= r1.r
) AS r1 WHERE l!=r
) AS r1
) AS r1
Analysis
Code: 23:42:03 UTC,
sql,
final,
score: 
100
SELECT
IFNULL(SUM(r-sub_l),0)
FROM
(
SELECT
DISTINCT r,
(SELECT
MAX(x)
FROM
(SELECT
DISTINCT l AS x
FROM
segments
UNION
SELECT
DISTINCT r AS x
FROM
segments
) AS r2
WHERE
r2.x<r1.r
) AS sub_l
FROM
(SELECT
*
FROM
(SELECT
r1.l AS l,
r2.l AS r
FROM
segments AS r1
JOIN
segments AS r2
ON
r2.l >= r1.l AND r2.l <= r1.r
UNION
SELECT
r1.l AS l,
r2.r AS r
FROM
segments AS r1
JOIN
segments AS r2
ON
r2.r >= r1.l AND r2.r <= r1.r
) AS r1 WHERE l!=r
) AS r1
) AS r1
Analysis summary
The solution obtained perfect score.
Analysis
expand all
Correctness tests
1.
0.225 s
OK
1.
0.224 s
OK
1.
0.223 s
OK
1.
0.223 s
OK
1.
0.225 s
OK
2.
0.225 s
OK
1.
0.248 s
OK
2.
0.231 s
OK
1.
0.243 s
OK
1.
0.226 s
OK
1.
0.224 s
OK
1.
0.223 s
OK
1.
0.223 s
OK
1.
2.207 s
OK
1.
6.055 s
OK
1.
1.290 s
OK
1.
0.280 s
OK