AnalystPath

Closed Loops in a Book-Swap Club

PandasHardSenior level~10 min

Problem

You are given one DataFrame `book_swaps` with columns `lender_id`, `borrower_id`, and `page_count`. Each row records one member lending a book of `page_count` pages to exactly one other member.

Some lending relationships form closed loops: 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, report `chain_length` (how many members are in the loop) and `total_pages` (the sum of page counts around the loop). Each distinct loop must appear exactly once regardless of where tracing starts. A member who lends to themselves forms a loop of length 1.

Return columns `chain_length` and `total_pages`, ordered by `chain_length` descending, then `total_pages` descending.

Input data

Example rows — the live problem includes the full dataset.

book_swaps
lender_idborrower_idpage_count
12220
23310
31180
4590
54410

Expected output

Your answer should return 2 rows with the columns chain_length, total_pages.

Starter code (Pandas (Python))

import pandas as pd

def closed_swap_loops(book_swaps) -> pd.DataFrame:
    # Your code here
    return book_swaps

Solve this Pandas question free

Write Pandas (Python) 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

Related Pandas questions