topskill.dev
CoursesTracks
0
All courses/Data Structures with PythonRemove a participant and keep the ring closed
Doubly linked, circular, and skip lists
8 / 15
← Data Structures with Python
○References and aliases○Object identity without addresses○Shallow copies preserve element references○Choose a nested copy boundary○Count linear work○Count pair work○Count halving work○Compare growth by running counted work○Auxiliary space in a single scan○Model amortized append cost✦Module Quiz
○Base and recursive cases○Trace calls entering and leaving○Recursive sum without slicing○Iterative factorial and its invariant○Recursive factorial and waiting frames○Fibonacci as a branching call tree○Memoize completed Fibonacci subproblems○Iterative Fibonacci with two live values○Tail recursion still uses stack frames○Recursive binary search from sorted halves✦Module Quiz
○Array access and occupied positions○Append with modeled capacity○Insert by shifting from the right○Delete and compact the occupied prefix○Reverse with two inward pointers○Slide a fixed-width sum○Build prefix sums with a leading zero○Answer half-open range-sum queries✦Module Quiz
○Create a node and its link○Walk a chain without changing it○Give the list a consistent empty state○Prepend without losing the old head○Append through the tail reference○Find the first matching node○Insert after a known predecessor○Remove and detach the head○Find the predecessor before removing the tail○Remove only the first matching value○Reverse the links in place○Play and consume the next recording✦Module Quiz
○Store a backward link as well as a forward link○Prepend and repair the reverse link○Append with a link back to the old tail○Remove a known node in both directions○Start a new history branch after going back○Close a circular list after append○Traverse exactly one lap●Remove a participant and keep the ring closed○Represent skip-list towers with forward links○Search top-down for every predecessor○Check the successor after a skip search○Insert one tower at its supplied height○Remove a tower from every participating level○Measure skip-list work without a stopwatch✦Module Quiz
○Choose the top and initialize a stack○Push onto the final position○Peek without consuming the top○Pop in last-in-first-out order○Match brackets in nested order○Evaluate postfix arithmetic with an operand stack○Restore the last saved text state○Remember the minimum at every stack depth✦Module Quiz
○Give a linked queue an empty state○Enqueue at the linked rear○Dequeue the oldest item○Peek without serving○Use both ends of a deque○Represent a fixed ring buffer○Enqueue with wraparound○Dequeue and recycle a ring slot○Schedule work round-robin○Keep a monotonic window deque✦Module Quiz
○Turn a key into a bucket index○Keep colliding keys together○Initialize a chained hash table○Insert or update one key○Look up a colliding key○Delete from a collision bucket○List the stored pairs○Measure the load factor○Rehash stored key/value pairs○Search a linear-probing table○Delete with a tombstone○Build a frequency index✦Module Quiz
○Find the first match in unsorted data○Search records through a key function○Halve a sorted search interval○Respect explicit search boundaries○Find the lower bound○Find the upper bound○Insert after existing equals○Count binary-search comparisons✦Module Quiz
○Swap adjacent○Bubble pass○Bubble sort○Select minimum○Selection sort○Insertion step○Insertion sort○Merge runs○Merge sort○Partition around pivot○Quicksort○Stable key sorting✦Module Quiz
○Binary node○Count nodes○Tree height○Preorder traversal○Inorder traversal○Postorder traversal○Level order traversal○BST search○BST insert○BST minimum○BST delete leaf○BST delete one child○BST delete two children○Validate BST✦Module Quiz
○Heap array indices○Heap order○Sift up○Sift down○Heap push○Heap pop○Bottom up heapify○Max heap○Heap sort○Heapq basics○Stable priority queue○Priority updates○Top k stream○Scheduler project✦Module Quiz
○Represent isolated vertices with adjacency lists○Add a vertex without erasing its neighbors○Add both halves of an undirected edge○Remove an edge without removing its vertices○Remove a vertex and its incident edges○Store directed edges in only one list○Convert adjacency lists to a matrix○Count incoming and outgoing edges✦Module Quiz
○Discover neighbors before adding them to the BFS queue○Process the BFS queue in layers○Count the fewest edges with BFS○Recover a shortest-hop path from parents○Restart BFS to find undirected components○Follow one branch with recursive DFS○Simulate recursive DFS with iterator frames○Ignore the parent edge in undirected cycle checks○Distinguish active and finished vertices in directed DFS○Schedule directed dependencies with topological order✦Module Quiz
○Store directed edges with nonnegative integer costs○Add the weights along a proposed path○Relax one edge when it improves a distance○Settle cheapest distances with scan-based Dijkstra○Use a lazy min-heap for Dijkstra priorities○Read a weighted shortest route from its parents○Keep zero-cost routes distinct from unreachable targets○Build a route planner that reuses one weighted search✦Module Quiz
○Read one bit○Set, clear, or toggle a flag○Count set bits○Recognize a power of two○Choose a fixed-width mask○Compare groups with set algebra○Use an unordered group as a key○Check a permission bundle✦Module Quiz
○Give each trie node its own children○Insert a word by sharing its prefix○Search for a complete word○Search for a prefix path○Collect the words below a prefix○Delete a word without deleting its neighbors○Count words sharing a prefix○Build a bounded autocomplete result✦Module Quiz
○Find the lowest set bit○Allocate one-based Fenwick storage○Propagate a Fenwick point addition○Sum a Fenwick prefix○Subtract prefixes for a range sum○Build a Fenwick tree from values○Lay out a padded segment tree○Build parent summaries from the leaves○Query a half-open segment interval○Replace a value and repair its ancestors○Use minimum as the segment summary○Report changing ranges✦Module Quiz
○Start with separate components○Follow links to a root○Join two components○Compress a parent path○Attach the smaller component○Count remaining components○Find the first redundant edge○Build a minimum spanning forest✦Module Quiz
○Pair independent choices○Double the collection of subsets○Read subsets from bit masks○Choose distinct items without order○Allow repeated choices without order○Arrange distinct items in order○Build words with repeated symbols○Prune choices that exceed a budget✦Module Quiz
○Index the dispatch catalog○Queue pending job IDs○Dispatch by stable priority○Undo the latest completed dispatch○Check directed network reachability○Return a cheapest weighted route○Report completed loads over a day range○Run a scripted dispatch session✦Module Quiz

Remove a participant and keep the ring closed

Removing from a ring combines a bounded search with endpoint repair. Start the predecessor at tail and the cursor at head. This pair is valid even before the first step because tail.next is head. In an ordinary singly linked list, the head had no predecessor; the circular link changes that case.

Search no more than the original size nodes. If no value matches in that lap, return None without change. When a match is found, bypass it through the predecessor. If the match is head, advance head. If it is tail, move tail back to the predecessor. Reestablish tail.next=head before returning.

The singleton case cannot use the ordinary bypass alone: its predecessor and successor are both itself. Removing its only node must instead clear both endpoints and set size to zero. In every successful case, clear the removed node's next so the returned object no longer participates in any ring.

Only the first equal value in head-first order is removed. Keep the other equal-valued nodes and their identities. Decrease size only after a match. Updating it for a failed comparison would corrupt the count even though no node was removed. In a for loop, range(self.size) captures its bound before iteration begins.

After a removal, use the previous one-lap values method to inspect the survivors. Then append again. A stale tail-to-head connection often appears when operations are mixed rather than tested in isolation.

Trace it first

For oak -> pine -> elm -> (oak), removing oak makes pine the head and changes elm.next to pine. Removing elm next makes pine both head and tail with a self-link. Removing pine clears the wrapper and detaches pine.next to None.

Cost

Search takes O(n) worst-case time; the splice is O(1). Auxiliary space is O(1). Missing values require a full lap, not an unbounded walk.

Operation contract

Implement CircularList.remove_first(value) to return the detached first matching node in head-first order, or None if absent, preserving the ring and metadata.

Circular remove. Before: A: 4 → B: 9 → C: 6. After: B: 9 → C: 6. remove_first(4): head = B; tail.next = B; detach A; return node A; size: 3 → 2. Singleton match clears head and tail and breaks the loop. Empty or missing: return None; no changes.

Build it in three checks

The supplied cursor begins at head and its predecessor at tail. Task 1 is just the bounded search: compare the current payload before advancing, and stop on the first match. The loop's else already returns None after a complete lap with no match. At this checkpoint the method returns the matching node but does not remove it yet; do not call values() after a successful search until the later checks are complete.

Next, repair the ring while the old size still records the original number of nodes. For a singleton, clear head and tail. Otherwise point the predecessor past the match, move head or tail if needed, and close the ring through tail.next. The last check decreases size once, clears the removed node's next, and returns that same node. This order lets you inspect link repair separately from the detached result.

Your Task

  1. Stop the supplied search at the first matching node.
  2. Bypass that node and repair the ring's head, tail, and closing link, including the singleton case.
  3. Decrease size and detach the returned node's next link.

Run and check

Edit CircularList.remove_first in main.py; keep the supplied search loop, missing-result else, and final return. Run after each change and Submit for its matching check. The starter Run probe prints None for an unfinished search; after all checks it prints:

text
Ari ['Bo', 'Cy']

Press Submit to check the tasks on additional inputs and boundary cases.

Files
  • ⋄main.py
Loading editor…
Press Run to execute your code.