Sign Up Sign Up


Have an account? Sign In Now

Sign In Sign In


Forgot Password?

Don't have account, Sign Up Here

Forgot Password Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

You must login to ask a question.


Forgot Password?

Need An Account, Sign Up Here

You must login to add post.


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

RTSALL Logo RTSALL Logo
Sign InSign Up

RTSALL

RTSALL Navigation

  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us

Linked Lists & Custom Allocators

Singly and doubly linked lists, XOR lists, cycle detection, memory pooling, and lock-free concurrent lists.

Share
  • Facebook
0 Followers
4 Answers
2 Questions
Home/Data Structures & Algorithms/Linked Lists & Custom Allocators
  • Recent Questions
  • Most Answered
  • Answers
  • No Answers
  • Most Visited
  • Most Voted
  • Random
  1. Asked: September 11, 2026In: Data Structures & Algorithms, Linked Lists & Custom Allocators

    Floyd’s Tortoise and Hare: Mathematical proof of why meeting point resolves cycle origin

    Abhay Tiwari
    Abhay Tiwari Begginer
    Added an answer on September 11, 2026 at 9:53 am

    Floyd's cycle algorithm is pure mathematical poetry. Let's write out the distances with simple algebra so the proof is crystal clear. 1. Defining the Variables Let's map out the linked list into three distinct segments: L: Distance from the head to the cycle entrance. C: Total length (circumference)Read more

    Floyd’s cycle algorithm is pure mathematical poetry. Let’s write out the distances with simple algebra so the proof is crystal clear.

    1. Defining the Variables

    Let’s map out the linked list into three distinct segments:

    • L: Distance from the head to the cycle entrance.
    • C: Total length (circumference) of the cycle.
    • x: Distance from the cycle entrance to the meeting point inside the cycle.

    2. Distance Traveled by Each Pointer

    When the Tortoise (slow) and Hare (fast) meet:

    • Slow moved: Dist_slow = L + x
    • Fast moved: Dist_fast = L + n * C + x (where n is how many full laps fast ran around the cycle).

    Because the fast pointer moves at twice the speed of slow:

    Dist_fast = 2 * Dist_slow
    L + n * C + x = 2 * (L + x)
    L + n * C + x = 2L + 2x
    

    Now subtract L + x from both sides:

    n * C = L + x
    L = n * C - x
    L = (n - 1) * C + (C - x)
    

    3. What does L = (n – 1) * C + (C – x) mean?

    Look carefully at that equation:

    • L is the distance from head to the cycle entrance.
    • (C - x) is the distance from the meeting point to the cycle entrance!
    • (n - 1) * C is just zero or more full loops around the cycle!

    Conclusion: If you place Pointer 1 at head (which must travel distance L) and Pointer 2 at meeting_point (which travels distance (C - x) plus some optional full laps), both pointers will meet at the EXACT same node: the cycle entrance!


    Clean Python 3.12 Implementation

    class ListNode:
        def __init__(self, val=0, next=None):
            self.val = val
            self.next = next
    
    def detect_cycle_entry(head: ListNode | None) -> ListNode | None:
        """Finds the node where cycle begins in O(N) time and O(1) space."""
        if not head or not head.next:
            return None
    
        slow = head
        fast = head
    
        # Phase 1: Determine if a cycle exists
        has_cycle = False
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                has_cycle = True
                break
    
        if not has_cycle:
            return None
    
        # Phase 2: Find cycle entrance
        ptr1 = head
        ptr2 = slow
        while ptr1 != ptr2:
            ptr1 = ptr1.next
            ptr2 = ptr2.next
    
        return ptr1
    

    Complexity Breakdown

    • Time Complexity: O(N). Phase 1 takes at most $2N$ steps. Phase 2 takes at most $N$ steps.
    • Space Complexity: O(1). No hash set or memory allocation.
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  2. Asked: September 11, 2026In: Data Structures & Algorithms, Linked Lists & Custom Allocators

    How to design a thread-safe LRU Cache in O(1) without memory leaks?

    Anonymous
    Anonymous Begginer
    Added an answer on September 11, 2026 at 9:51 am

    Building an LRU cache from scratch is one of the best ways to understand how data structures combine in real systems. The industry standard pattern is combining two complementary structures: A Hash Map: Gives you O(1) key-to-node lookups. A Doubly Linked List (DLL) with Dummy Head & Tail: GivesRead more

    Building an LRU cache from scratch is one of the best ways to understand how data structures combine in real systems. The industry standard pattern is combining two complementary structures:

    1. A Hash Map: Gives you O(1) key-to-node lookups.
    2. A Doubly Linked List (DLL) with Dummy Head & Tail: Gives you O(1) node insertion at the front (most recent) and O(1) node removal from the back (least recent).

    The secret trick that eliminates 90% of bug-prone null checks is using sentinel (dummy) head and tail nodes. Instead of constantly checking if (head == null) or if (node->prev == null), the dummy head and tail are always linked together: head <-> tail. Any real data node always lives safely in between them!


    Architectural Diagram

    [Head Dummy] <---> [Most Recent Node] <---> [Older Node] <---> [Tail Dummy]
                                                                          ^
                                                          Evict from here |
    

    Clean, Idiomatic Python 3.12 Implementation

    class Node:
        __slots__ = ('key', 'val', 'prev', 'next')
        def __init__(self, key: int = 0, val: int = 0):
            self.key = key
            self.val = val
            self.prev = None
            self.next = None
    
    class LRUCache:
        def __init__(self, capacity: int):
            self.cap = capacity
            self.cache: dict[int, Node] = {}
            
            # Dummy sentinel boundaries
            self.head = Node()
            self.tail = Node()
            self.head.next = self.tail
            self.tail.prev = self.head
    
        def _remove(self, node: Node) -> None:
            """Unlinks a node from its current position."""
            node.prev.next = node.next
            node.next.prev = node.prev
    
        def _insert_at_front(self, node: Node) -> None:
            """Inserts node right after head (most recently used)."""
            node.next = self.head.next
            node.prev = self.head
            self.head.next.prev = node
            self.head.next = node
    
        def get(self, key: int) -> int:
            if key not in self.cache:
                return -1
            node = self.cache[key]
            # Refresh access: move to front
            self._remove(node)
            self._insert_at_front(node)
            return node.val
    
        def put(self, key: int, value: int) -> None:
            if key in self.cache:
                node = self.cache[key]
                node.val = value
                self._remove(node)
                self._insert_at_front(node)
            else:
                if len(self.cache) >= self.cap:
                    # Evict least recently used (node right before tail)
                    lru = self.tail.prev
                    self._remove(lru)
                    del self.cache[lru.key]
                    
                new_node = Node(key, value)
                self.cache[key] = new_node
                self._insert_at_front(new_node)
    

    Why Storing the Key Inside the Node is Crucial

    Notice that the Node class stores both key and val. Many developers forget to store key in the node and only store val. But when the cache reaches full capacity and you evict tail.prev, how do you delete that entry from the hash map? Without node.key, you’d have to search the entire hash map in O(N) time, destroying your O(1) guarantee!


    Thread Safety in Production

    If multiple threads access this cache concurrently:

    • In Python, use threading.Lock() around get and put.
    • In Go or C++, a Read-Write Lock (sync.RWMutex / std::shared_mutex) is often tempting, but remember: even a get() operation mutates the linked list (to move the accessed item to the front)! Therefore, standard read locks are not enough—you must acquire an exclusive lock or use lock striping across multiple shards.
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp

Sidebar

Ask A Question
  • Popular
  • Answers
  • Queryiest

    What is a database?

    • 3 Answers
  • Anonymous

    How to rotate an array in-place with O(1) space and ...

    • 3 Answers
  • hannah

    What steps can businesses take to identify the most valuable ...

    • 2 Answers
  • Vikram
    aarav0 added an answer Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with… September 11, 2026 at 9:57 pm
  • Abhishek
    Abhishek added an answer Direct Technical Solution: In C++20, range view adaptors (like std::views::filter,… September 11, 2026 at 9:57 pm
  • Sneha Patel
    Anonymous added an answer Direct Technical Solution: torch.cuda.empty_cache() releases only cached (unallocated) blocks back… September 11, 2026 at 9:57 pm

Top Members

Queryiest

Queryiest

  • 201 Questions
  • 295 Points
Enlightened
Anonymous

Anonymous

  • 11 Questions
  • 42 Points
Begginer
paperubofficial

paperubofficial

  • 0 Questions
  • 22 Points
Begginer

Trending Tags

ai asp.net aws basics aws certification aws console aws free tier aws login aws scenario-based questions c++ career cyber security cyber security interview git java javascript jobs jquery net core net core interview questions sql

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • DSA Problems
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • New Questions
  • Trending Questions
  • Must read Questions
  • Hot Questions

Footer

About Us

  • Meet The Team
  • Blog
  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy
  • Disclaimer
  • Terms & Conditions

Help

  • Knowledge Base
  • Support

Follow

© 2023-25 RTSALL. All Rights Reserved