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 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

Abhay Tiwari

Begginer
Ask Abhay Tiwari
0 Visits
2 Followers
5 Questions
Home/Abhay Tiwari/Answers
  • About
  • Questions
  • Polls
  • Answers
  • Best Answers
  • Followed
  • Favorites
  • Asked Questions
  • Groups
  • Joined Groups
  • Managed Groups
  1. Asked: September 11, 2026In: Data Structures & Algorithms

    Next.js 15: Error: Route used “params” without awaiting it (Asynchronous Page Props Fix)

    Abhay Tiwari
    Abhay Tiwari Begginer
    Added an answer on September 11, 2026 at 9:57 pm

    Direct Technical Solution: In Next.js 15, dynamic route parameters (params) and search parameters (searchParams) transitioned from synchronous plain JavaScript objects to native Promises. This breaking change was implemented to support React 19 Server Components and the new Partial Prerendering (PPRRead more

    Direct Technical Solution: In Next.js 15, dynamic route parameters (params) and search parameters (searchParams) transitioned from synchronous plain JavaScript objects to native Promises. This breaking change was implemented to support React 19 Server Components and the new Partial Prerendering (PPR) model, where the server renders the static page skeleton before dynamic parameters resolve.

    1. Server Component Migration (Async/Await)

    In all Next.js 15 Server Components (the default in the app/ directory), type params as a Promise and explicitly await it before accessing any key:

    // app/blog/[slug]/page.tsx (Next.js 15 Server Component)
    interface PageProps {
      params: Promise<{ slug: string }>;
      searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
    }
    
    export default async function BlogPostPage({ params, searchParams }: PageProps) {
      // Await the asynchronous params promise
      const { slug } = await params;
      const resolvedSearchParams = await searchParams;
    
      return (
        <main style={{ padding: "2rem" }}>
          <h1>Article: {slug}</h1>
          <p>Tracking Tag: {resolvedSearchParams.ref || "Direct Visit"}</p>
        </main>
      );
    }

    2. Client Component Migration (React 19 `use()` Hook)

    If your page file uses "use client", you cannot make the component function async. Instead, unwrap the params Promise using React 19’s native React.use() hook:

    // app/dashboard/[userId]/client-page.tsx
    "use client";
    
    import { use } from "react";
    
    interface ClientPageProps {
      params: Promise<{ userId: string }>;
    }
    
    export default function UserDashboard({ params }: ClientPageProps) {
      // Unwrap the promise synchronously within render
      const { userId } = use(params);
    
      return <div>Active User Session: {userId}</div>;
    }

    3. Comparison: Next.js 14 vs Next.js 15

    FeatureNext.js 14Next.js 15 (React 19)
    Props Type{ slug: string } (Synchronous Object)Promise<{ slug: string }> (Async Promise)
    Server UnwrappingDirect dot-access (params.slug)const { slug } = await params;
    Client UnwrappinguseParams() hookuse(params) or useParams()
    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, Stacks, Queues & Ring Buffers

    Daily Temperatures: How to use an Index-Tracking Monotonic Stack for next warmer day in O(N)

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

    This problem is the cleanest introductory template for the Monotonic Decreasing Stack pattern. Let's look at why storing indices unlocks the distance calculation. 1. The Mental Model Imagine people waiting in line holding temperature tickets. If temperatures are dropping: [73, 71, 69], nobody has foRead more

    This problem is the cleanest introductory template for the Monotonic Decreasing Stack pattern. Let’s look at why storing indices unlocks the distance calculation.

    1. The Mental Model

    Imagine people waiting in line holding temperature tickets. If temperatures are dropping: [73, 71, 69], nobody has found a warmer day yet! So everyone has to stay waiting in line.

    Now, a warm day arrives: 72!

    • The person holding 69 sees 72 > 69. Their wait is over! They step out of line.
    • The person holding 71 sees 72 > 71. Their wait is over! They step out of line.
    • The person holding 73 sees 72 < 73. 72 is not warm enough for them! The person with 73 stays waiting in line, and the day with 72 joins the line behind them.

    2. Why Store Indices Instead of Values?

    If you only push temperature numbers (e.g. 69) onto the stack, when a warmer day 72 pops 69, you know that a warmer day happened, but you don’t know how many days elapsed!

    By pushing the array index prev_day onto the stack:

    days_waited = current_day - prev_day
    answer[prev_day] = days_waited
    

    You calculate the exact time difference in $O(1)$ and write directly to the output array!


    Clean Python 3.12 Implementation

    def daily_temperatures(temperatures: list[int]) -> list[int]:
        """Finds wait time until warmer day in O(N) time and O(N) auxiliary space."""
        n = len(temperatures)
        ans = [0] * n
        stack: list[int] = [] # Stores indices of previous cooler days
    
        for curr_day, temp in enumerate(temperatures):
            # Pop all previous days that are strictly cooler than today
            while stack and temperatures[stack[-1]] < temp:
                prev_day = stack.pop()
                ans[prev_day] = curr_day - prev_day
    
            stack.append(curr_day)
    
        return ans
    

    Complexity Breakdown

    • Time Complexity: O(N). Every index is pushed onto the stack once and popped at most once. Total operations: $le 2N$.
    • Space Complexity: O(N) for the stack in the worst-case of strictly decreasing temperatures (e.g. [100, 90, 80, 70]).
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  3. Asked: September 11, 2026In: Data Structures & Algorithms, Hashing & Collision Resolution

    Subarray Sum Equals K: Why Two Pointers fails with negative numbers and Hash Map is mandatory

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

    This is a classic trap that catches even intermediate developers. Let's see why two pointers collapse and why prefix math is the ultimate solution. 1. Why Two Pointers Fails on Negative Numbers A sliding window relies on a fundamental monotonic invariant: If the current sum is too small, expanding tRead more

    This is a classic trap that catches even intermediate developers. Let’s see why two pointers collapse and why prefix math is the ultimate solution.

    1. Why Two Pointers Fails on Negative Numbers

    A sliding window relies on a fundamental monotonic invariant:

    • If the current sum is too small, expanding the right pointer will increase the sum.
    • If the current sum is too large, contracting the left pointer will decrease the sum.

    The moment you introduce negative numbers, this invariant is destroyed! Expanding the right pointer might add -10, making the sum smaller. Shrinking the left pointer might drop -5, making the sum larger. You can no longer make greedy left/right decisions!


    2. The Prefix Sum Invariant

    Let prefix[i] be the cumulative sum from index 0 to i.

    The sum of any contiguous subarray from index j + 1 to i is given by: sum(j+1 ... i) = prefix[i] - prefix[j].

    We want this subarray sum to equal k:

    prefix[i] - prefix[j] = k
    prefix[j] = prefix[i] - k
    

    The Breakthrough: As you iterate through the array maintaining a running prefix sum curr_sum, you simply ask the hash map: ‘How many times have we already seen a prefix sum equal to curr_sum - k in the past?’

    Every time you find that value in the hash map, you have found a valid subarray that sums exactly to k!


    Clean Python 3.12 Implementation

    from collections import defaultdict
    
    def subarray_sum(nums: list[int], k: int) -> int:
        """Counts subarrays summing to k in O(N) time and O(N) space."""
        # Base case: A prefix sum of 0 has occurred once (an empty prefix)
        prefix_counts: dict[int, int] = defaultdict(int)
        prefix_counts[0] = 1
    
        curr_sum = 0
        total_subarrays = 0
    
        for x in nums:
            curr_sum += x
            target = curr_sum - k
            
            # Add all occurrences of the complementary prefix sum
            if target in prefix_counts:
                total_subarrays += prefix_counts[target]
                
            # Record current prefix sum
            prefix_counts[curr_sum] += 1
    
        return total_subarrays
    

    Why prefix_counts[0] = 1 is Critical

    If you forget prefix_counts[0] = 1, any subarray that starts at index 0 and sums to k (e.g. nums = [3, ...], k = 3) will produce curr_sum = 3, and look for curr_sum - k = 0 in the map. Without the base case, it would fail to count that valid subarray!


    Complexity Breakdown

    • Time Complexity: O(N). Single pass through the array with O(1) hash map lookups.
    • Space Complexity: O(N) to store prefix sum frequencies.
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  4. Asked: September 11, 2026In: Data Structures & Algorithms, Two Pointers & Sliding Window

    Minimum Window Substring: Why an integer frequency array beats HashMap in low-latency parsers

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

    Minimum Window Substring is the crown jewel of sliding window problems. The difference between a junior solution and a staff engineer solution comes down to how window validation is tracked. 1. The Trap: Comparing Two Hash Maps In naive implementations, developers maintain two hash maps: target_counRead more

    Minimum Window Substring is the crown jewel of sliding window problems. The difference between a junior solution and a staff engineer solution comes down to how window validation is tracked.

    1. The Trap: Comparing Two Hash Maps

    In naive implementations, developers maintain two hash maps: target_counts and window_counts. Whenever the window slides, they loop through the keys of target_counts to see if the window is valid. That turns an $O(N)$ algorithm into $O(N cdot |Sigma|)$ with heavy hash table overhead!


    2. The Staff Engineer Pattern: Single Vector + Deficit Counter

    We can optimize this down to bare metal with two simple tricks:

    1. Fixed 128-integer Array: Standard ASCII fits inside 128 indices. An array of 128 integers takes 512 bytes, fitting completely inside an L1 data cache line.
    2. A Single Deficit Counter (required): We set required = len(t). When expanding the window with pointer r, if counts[s[r]] > 0, that character was actively needed, so we decrement required--. When required == 0, the window is 100% valid! We don’t have to check any other variables!

    Clean Python 3.12 Implementation

    def min_window(s: str, t: str) -> str:
        """Finds minimum window substring in strict O(|s| + |t|) time and O(1) space."""
        if not s or not t or len(s) < len(t):
            return ""
    
        # Frequency map using fixed 128 ASCII array
        freq = [0] * 128
        for char in t:
            freq[ord(char)] += 1
    
        required = len(t)
        min_len = float('inf')
        start_idx = 0
        left = 0
    
        for right in range(len(s)):
            r_char = ord(s[right])
            
            # If this character was still needed by t
            if freq[r_char] > 0:
                required -= 1
                
            freq[r_char] -= 1
    
            # While window satisfies all characters in t -> contract left boundary
            while required == 0:
                window_len = right - left + 1
                if window_len < min_len:
                    min_len = window_len
                    start_idx = left
    
                l_char = ord(s[left])
                freq[l_char] += 1
                
                # If removing this character breaks the required quota
                if freq[l_char] > 0:
                    required += 1
                    
                left += 1
    
        return "" if min_len == float('inf') else s[start_idx : start_idx + min_len]
    

    Complexity Breakdown

    • Time Complexity: O(|s| + |t|). The right pointer advances |s| times. The left pointer advances at most |s| times. Total pointer advances = 2|s|.
    • Space Complexity: O(1) auxiliary space. Exactly 128 integers on the stack.
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  5. Asked: September 11, 2026In: Bit Manipulation & Low-Level Computing, Data Structures & Algorithms

    How to find the Single Number when all others appear 3 times using a Digital Logic State Machine?

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

    This problem is a masterpiece of digital circuit design translated into software code. Let's design the state machine from first principles. 1. The Three States of a Bit For any bit position, as we scan numbers in the array, how many times can we see a 1? Seen 0 times → Count = 0 Seen 1 timeRead more

    This problem is a masterpiece of digital circuit design translated into software code. Let’s design the state machine from first principles.

    1. The Three States of a Bit

    For any bit position, as we scan numbers in the array, how many times can we see a 1?

    • Seen 0 times → Count = 0
    • Seen 1 time → Count = 1
    • Seen 2 times → Count = 2
    • Seen 3 times → Resets back to 0!

    To represent 3 distinct states (0, 1, and 2), we need 2 bits of memory! Let’s name them:

    • twos (the high bit)
    • ones (the low bit)

    2. The Truth Table

    When a new bit x arrives from the current number:

    Current State (twos, ones)Input Bit (x)Next State (twos, ones)Explanation
    0, 000, 0Seen 0 times
    0, 010, 1Seen 1 time
    0, 100, 1Unchanged
    0, 111, 0Seen 2 times
    1, 001, 0Unchanged
    1, 010, 0Seen 3 times → RESETS TO 0!

    3. Deriving the Logic Gates

    From the truth table:

    • ones = (ones ^ x) & (~twos)
    • twos = (twos ^ x) & (~ones)

    When the full array has been scanned:

    • Every element that appeared 3 times completed the full cycle $(0 o 1 o 2 o 0)$ and returned both bits to 0.
    • The single element that appeared 1 time transitioned from $0 o 1$. Its bits are left recorded inside ones!

    Clean Python 3.12 Implementation

    def single_number(nums: list[int]) -> int:
        """Finds element appearing once while others appear 3 times in O(N) time and O(1) space."""
        ones = 0
        twos = 0
    
        for x in nums:
            # Update ones: XOR with x, but clear if twos already holds this bit
            ones = (ones ^ x) & ~twos
            # Update twos: XOR with x, but clear if ones now holds this bit
            twos = (twos ^ x) & ~ones
    
        return ones
    

    Complexity Breakdown

    • Time Complexity: O(N). We touch each number once with 4 single-cycle bitwise operations.
    • Space Complexity: O(1). Exactly two integer variables living in registers.
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  6. Asked: September 11, 2026In: Data Structures & Algorithms, System-Scale & Probabilistic Structures

    How does a Fenwick Tree (Binary Indexed Tree) query and update prefix sums in O(log N) using i & (-i)?

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

    The Fenwick Tree (invented by Peter Fenwick in 1994) is one of the most compact data structures ever devised. It gives you the full power of a dynamic segment tree in just one flat array of size N with 10 lines of code. 1. The Secret: Powers of 2 Range Decomposition Any positive integer can be uniquRead more

    The Fenwick Tree (invented by Peter Fenwick in 1994) is one of the most compact data structures ever devised. It gives you the full power of a dynamic segment tree in just one flat array of size N with 10 lines of code.

    1. The Secret: Powers of 2 Range Decomposition

    Any positive integer can be uniquely represented as a sum of powers of 2. For example: 13 = 8 + 4 + 1.

    Fenwick took this idea and applied it to prefix ranges: instead of storing every single element, tree[i] stores the sum of a contiguous range of length equal to its lowest set bit!

    The length of the range responsible by index i is given by: lowbit(i) = i & (-i).

    • If i = 12 (1100_2): lowbit(12) = 4. So tree[12] stores the sum of 4 elements: indices [9, 10, 11, 12]!
    • If i = 8 (1000_2): lowbit(8) = 8. So tree[8] stores the sum of the first 8 elements: [1 ... 8]!

    2. The Two Operations

    A. Prefix Sum Query: `i -= (i & -i)`

    To calculate the prefix sum up to index 13:

    1. Read tree[13] (covers index 13). 13 - lowbit(13) = 13 - 1 = 12.
    2. Read tree[12] (covers indices 9 through 12). 12 - lowbit(12) = 12 - 4 = 8.
    3. Read tree[8] (covers indices 1 through 8). 8 - lowbit(8) = 8 - 8 = 0 (Done!).

    Total reads: only 3 steps to sum 13 numbers! At each step, you strip off one binary bit, taking at most O(log N) operations.

    B. Point Update: `i += (i & -i)`

    When you add delta to element i, which parent ranges need to be updated? Every index whose range covers i! You navigate up the tree simply by adding the lowest set bit: i += (i & -i)!


    Clean C++20 Implementation

    #include <vector>
    #include <cstdint>
    
    class FenwickTree {
        std::vector<int64_t> tree;
        int n;
    
        static inline int lowbit(int x) {
            return x & (-x);
        }
    
    public:
        FenwickTree(int size) : n(size), tree(size + 1, 0) {}
    
        // Adds delta to index i (1-indexed) in O(log N)
        void update(int i, int64_t delta) {
            while (i <= n) {
                tree[i] += delta;
                i += lowbit(i);
            }
        }
    
        // Computes sum of prefix [1 ... i] in O(log N)
        int64_t query(int i) const {
            int64_t sum = 0;
            while (i > 0) {
                sum += tree[i];
                i -= lowbit(i);
            }
            return sum;
        }
    
        // Computes range sum [l ... r] in O(log N)
        int64_t queryRange(int l, int r) const {
            if (l > r) return 0;
            return query(r) - query(l - 1);
        }
    };
    

    Why Fenwick Beats Segment Trees in Production

    MetricSegment TreeFenwick Tree
    Memory Overhead4N (or 2N)Strictly 1N (4x smaller)
    Implementation Size50-80 lines15 lines
    L1 Cache PerformanceModerateBlazing Fast (flat contiguous array)
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  7. 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
  8. Asked: September 11, 2026In: Arrays, Strings & Cache Memory, Data Structures & Algorithms

    How does the Dutch National Flag 3-way partition work in a single pass with zero branch mispredictions?

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

    The Dutch National Flag algorithm (invented by Edsger W. Dijkstra) is the secret weapon that makes 3-way QuickSort resilient against duplicate keys. 1. The 3 Pointer Invariant We divide the array into 4 distinct regions using 3 pointers: low, mid, and high: [ 0 ... low-1 ] -> All elements strictlRead more

    The Dutch National Flag algorithm (invented by Edsger W. Dijkstra) is the secret weapon that makes 3-way QuickSort resilient against duplicate keys.

    1. The 3 Pointer Invariant

    We divide the array into 4 distinct regions using 3 pointers: low, mid, and high:

    [ 0 ... low-1 ]  -> All elements strictly 0
    [ low ... mid-1 ] -> All elements strictly 1
    [ mid ... high ]  -> UNKNOWN (yet to be inspected)
    [ high+1 ... n-1] -> All elements strictly 2
    

    Initially, low = 0, mid = 0, and high = n - 1. The entire array is initially inside the UNKNOWN region.


    2. The 3 State Transitions

    While mid <= high, inspect nums[mid]:

    1. If nums[mid] == 0: Swap nums[low] with nums[mid]. Increment BOTH low++ and mid++.
      Why can we increment mid here? Because whatever was sitting at low was already processed (it was guaranteed to be a 1).
    2. If nums[mid] == 1: It’s already in the right spot! Just increment mid++.
    3. If nums[mid] == 2: Swap nums[mid] with nums[high]. Decrement high--.
      THE CRITICAL CATCH: Do NOT increment mid here! Whatever came from high was unknown—it might be a 0, a 1, or another 2! We must inspect it on the next loop iteration!

    Clean Python 3.12 Implementation

    def sort_colors(nums: list[int]) -> None:
        """In-place 3-way partition in O(N) time and O(1) memory."""
        low = 0
        mid = 0
        high = len(nums) - 1
    
        while mid <= high:
            if nums[mid] == 0:
                nums[low], nums[mid] = nums[mid], nums[low]
                low += 1
                mid += 1
            elif nums[mid] == 1:
                mid += 1
            else: # nums[mid] == 2
                nums[mid], nums[high] = nums[high], nums[mid]
                high -= 1
                # Note: mid is intentionally NOT incremented here!
    

    Complexity Breakdown

    • Time Complexity: O(N). In every single step, either mid increases or high decreases. The unknown window (high - mid) strictly shrinks to zero in at most N steps.
    • Space Complexity: O(1). No extra memory allocated.
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  9. Asked: September 11, 2026In: Data Structures & Algorithms, System-Scale & Probabilistic Structures

    How does a Count-Min Sketch estimate heavy-hitter item frequencies under bounded RAM?

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

    The Count-Min Sketch (CMS) is the gold-standard probabilistic algorithm for tracking frequencies in massive, unconstrained data streams (used extensively in Apache Spark, network switches, and Google search analytics). 1. Architectural Layout A Count-Min Sketch consists of a 2D matrix of integer couRead more

    The Count-Min Sketch (CMS) is the gold-standard probabilistic algorithm for tracking frequencies in massive, unconstrained data streams (used extensively in Apache Spark, network switches, and Google search analytics).

    1. Architectural Layout

    A Count-Min Sketch consists of a 2D matrix of integer counters with d rows (depth) and w columns (width), paired with d independent hash functions:

    Row 0: [0, 0, 0, 0, ..., 0]  <--- Hash Function h_0(x)
    Row 1: [0, 0, 0, 0, ..., 0]  <--- Hash Function h_1(x)
    ...
    Row d: [0, 0, 0, 0, ..., 0]  <--- Hash Function h_d(x)
    

    2. The Operations

    A. Add Item `x` (Increment):

    For each row i from 0 to d - 1, compute column index col = h_i(x) % w, and increment that counter:

    table[i][h_i(x) % w] += 1
    

    B. Query Frequency of `x` (Point Query):

    Because multiple items might collide at the same counter bucket, hash collisions can only increase a counter, never decrease it!

    Therefore, to get the best possible estimate, we take the MINIMUM across all d rows:

    estimated_count = min(table[i][h_i(x) % w] for i in range(d))
    

    The Golden Invariant: A Count-Min Sketch NEVER underestimates the true count! True frequency is always $le$ estimated frequency.


    3. Mathematical Dimensioning Rules

    If you want an error bound within $epsilon cdot N$ with confidence probability $1 – delta$:

    • Width: $w = lceil rac{e}{epsilon}
      ceil pprox lceil rac{2.718}{epsilon}
      ceil$
    • Depth: $d = lceil ln( rac{1}{delta})
      ceil$

    For example, to guarantee $le 0.1%$ error with $99%$ confidence, you need only $w = 2718$ columns and $d = 5$ rows. That’s just 13,590 integer counters (~54 KB of RAM) to monitor billions of events!


    Clean Python 3.12 Implementation

    import math
    import mmh3 # MurmurHash3
    
    class CountMinSketch:
        def __init__(self, epsilon: float = 0.001, delta: float = 0.01):
            self.w = int(math.ceil(math.e / epsilon))
            self.d = int(math.ceil(math.log(1.0 / delta)))
            self.table = [[0] * self.w for _ in range(self.d)]
    
        def add(self, item: str, count: int = 1) -> None:
            """Increments counter for item across all d hash functions."""
            for row in range(self.d):
                col = mmh3.hash(item, row, signed=False) % self.w
                self.table[row][col] += count
    
        def query(self, item: str) -> int:
            """Returns minimum count across all d rows (never underestimates)."""
            return min(
                self.table[row][mmh3.hash(item, row, signed=False) % self.w]
                for row in range(self.d)
            )
    

    Complexity Breakdown

    • Add Time: O(d) — strictly constant time ($5$ hash calculations and memory writes).
    • Query Time: O(d) — strictly constant time ($5$ lookups).
    • Memory Footprint: O(w * d) — strictly fixed in size. Bounded memory that never grows regardless of how many billions of packets arrive!
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  10. Asked: September 11, 2026In: Data Structures & Algorithms, Tries & Prefix Search Engines

    How does a 32-bit Binary Trie find the Maximum XOR of Two Numbers in O(N) time?

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

    The Maximum XOR problem is the ultimate showcase of how bit manipulation and trees blend together. Once you see the greedy nature of binary numbers, the Binary Trie solution becomes second nature. 1. The Greedy Bit Principle In binary numbers, the Most Significant Bit (MSB) has more numerical valueRead more

    The Maximum XOR problem is the ultimate showcase of how bit manipulation and trees blend together. Once you see the greedy nature of binary numbers, the Binary Trie solution becomes second nature.

    1. The Greedy Bit Principle

    In binary numbers, the Most Significant Bit (MSB) has more numerical value than all lower bits combined! For example, bit 30 ($2^{30} pprox 1.07 imes 10^9$) is strictly greater than the sum of all bits from 0 to 29 combined ($2^{30} – 1$).

    Therefore, to maximize an XOR sum, you must be greedy from left to right (MSB down to LSB):

    • If the current bit of number num is 1, you desperately want to pair it with a number whose corresponding bit is 0 (because 1 ^ 0 = 1).
    • If the current bit of num is 0, you want to pair it with a number whose corresponding bit is 1 (because 0 ^ 1 = 1).

    2. Why a Binary Trie?

    A Binary Trie is just a tree where every node has at most two children: 0 (left) and 1 (right).

    1. Insert: You insert each number into the Trie as a 31-bit or 32-bit string of binary digits, from bit 31 down to bit 0.
    2. Query: For each number x, you walk down the Trie. At each bit b, you ask: ‘Does the opposite branch (1 - b) exist?’
      • If YES: Take that branch! That bit in your XOR result becomes 1.
      • If NO: You’re forced to take the same branch (b), so that bit in your XOR result becomes 0.

    Because you made the best possible choice at every single bit position starting from the highest power of 2, the final accumulated number is mathematically guaranteed to be the global maximum XOR!


    Clean Python 3.12 Implementation

    class TrieNode:
        __slots__ = ('children',)
        def __init__(self):
            self.children: list[TrieNode | None] = [None, None]
    
    class Solution:
        def find_maximum_xor(self, nums: list[int]) -> int:
            root = TrieNode()
    
            # Step 1: Insert all numbers into the 31-bit binary trie
            for num in nums:
                curr = root
                for i in range(30, -1, -1):
                    bit = (num >> i) & 1
                    if not curr.children[bit]:
                        curr.children[bit] = TrieNode()
                    curr = curr.children[bit]
    
            # Step 2: Query each number against the trie
            max_xor = 0
            for num in nums:
                curr = root
                current_xor = 0
                for i in range(30, -1, -1):
                    bit = (num >> i) & 1
                    opposite_bit = 1 - bit
                    
                    # Greedily check if the complementary bit exists
                    if curr.children[opposite_bit]:
                        current_xor |= (1 << i)
                        curr = curr.children[opposite_bit]
                    else:
                        curr = curr.children[bit]
                        
                max_xor = max(max_xor, current_xor)
    
            return max_xor
    

    Complexity Breakdown

    • Time Complexity: O(31 * N) = O(N). Inserting N numbers takes 31 * N operations. Querying N numbers takes 31 * N operations. Total time is strictly linear in the number of elements.
    • Space Complexity: O(31 * N) worst-case node allocations. In practice, prefix branches overlap heavily, keeping memory around a few megabytes.
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
1 2

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