Closed Loops in a Book-Swap Club
Problem
In a book-swap club, every entry in `book_swaps` records one member lending a book of `page_count` pages to exactly one other member. Some of these lending relationships form closed loops: member A lends to B, B lends to C, and C lends back to A, so each member in the loop both gives and receives exactly once. Find every such circular loop and, for each one, report `chain_length` (how many members are in the loop) and `total_pages` (the sum of the page counts around the loop). Each distinct loop must appear exactly once regardless of where you start tracing it. Order by `chain_length` descending, then `total_pages` descending.
Tables
Example rows — the live problem includes the full dataset.
| lender_id | borrower_id | page_count |
|---|---|---|
| 1 | 2 | 220 |
| 2 | 3 | 310 |
| 3 | 1 | 180 |
Expected output
Your answer should return 2 rows with the columns chain_length, total_pages.
Starter code (SQL)
SELECT *
FROM book_swaps;Solve this SQL question free
Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.
Solution & explanation
Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.
Sign up free to unlock