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

Abhishek

Begginer
Ask Abhishek
0 Visits
2 Followers
0 Questions
Home/Abhishek/Answers
  • About
  • Questions
  • Polls
  • Answers
  • Best Answers
  • Followed
  • Favorites
  • Asked Questions
  • Groups
  • Joined Groups
  • Managed Groups
  1. Asked: September 11, 2026In: Arrays, Strings & Cache Memory

    Why does std::views::filter on temporary containers trigger undefined behavior and dangling references in C++20?

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

    Direct Technical Solution: In C++20, range view adaptors (like std::views::filter, std::views::transform, and std::views::take) are strictly non-owning view wrappers. They do not duplicate or take ownership of the underlying container; they only store iterators pointing directly into the underlyingRead more

    Direct Technical Solution: In C++20, range view adaptors (like std::views::filter, std::views::transform, and std::views::take) are strictly non-owning view wrappers. They do not duplicate or take ownership of the underlying container; they only store iterators pointing directly into the underlying sequence.

    In your code, getTemperatures() returns a temporary std::vector<int> by value. At the semicolon ending the initialization expression auto warm_days = getTemperatures() | ...;, the temporary vector reaches the end of its full-expression lifetime and is immediately destructed. Consequently, the iterators stored inside warm_days become dangling pointers into deallocated stack/heap memory, causing undefined behavior upon iteration.

    Modern C++20 Fix (Lifetime Preservation)

    #include <iostream>
    #include <vector>
    #include <ranges>
    
    std::vector<int> getTemperatures() {
        return {18, 25, 32, 14, 29, 36};
    }
    
    int main() {
        // Solution 1: Bind the temporary to a named local variable
        // This extends the container lifetime across the entire scope.
        const auto temps = getTemperatures();
        auto warm_days = temps | std::views::filter([](int t) { return t > 20; });
    
        std::cout << "Warm days: ";
        for (int t : warm_days) {
            std::cout << t << " ";
        }
        std::cout << "
    ";
    
        return 0;
    }
    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)

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:27 pm

    Here is the C++20 Monotonic Stack solution for Daily Temperatures. It stores day indices to compute elapsed days in O(1). Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> #include <vector> std::vector<int> dailyRead more

    Here is the C++20 Monotonic Stack solution for Daily Temperatures. It stores day indices to compute elapsed days in O(1).

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    
    std::vector<int> dailyTemperatures(const std::vector<int>& temperatures) {
        const size_t n = temperatures.size();
        std::vector<int> ans(n, 0);
        std::vector<int> stack;
        stack.reserve(n);
    
        for (int curr_day = 0; curr_day < static_cast<int>(n); ++curr_day) {
            while (!stack.empty() && temperatures[stack.back()] < temperatures[curr_day]) {
                int prev_day = stack.back();
                stack.pop_back();
                ans[prev_day] = curr_day - prev_day;
            }
            stack.push_back(curr_day);
        }
        return ans;
    }
    
    int main() {
        std::vector<int> temps = {73, 74, 75, 71, 69, 72, 76, 73};
        auto res = dailyTemperatures(temps);
        std::cout << "Days to wait for warmer temperature: ";
        for (int d : res) std::cout << d << " ";
        std::cout << "n";
        return 0;
    }
    

    Complexity: O(N) time and O(N) space with zero reallocations.

    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

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:27 pm

    Here is the C++20 implementation of Subarray Sum Equals K with negative values using std::unordered_map. Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> #include <vector> #include <unordered_map> #include <cRead more

    Here is the C++20 implementation of Subarray Sum Equals K with negative values using std::unordered_map.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <unordered_map>
    #include <cstdint>
    
    int subarraySum(const std::vector<int>& nums, int k) {
        std::unordered_map<int64_t, int> prefix_counts;
        prefix_counts[0] = 1; // Base case
    
        int64_t curr_sum = 0;
        int total_subarrays = 0;
    
        for (int x : nums) {
            curr_sum += x;
            int64_t target = curr_sum - k;
    
            auto it = prefix_counts.find(target);
            if (it != prefix_counts.end()) {
                total_subarrays += it->second;
            }
            prefix_counts[curr_sum]++;
        }
        return total_subarrays;
    }
    
    int main() {
        std::vector<int> nums = {1, -1, 1, 1, 1, -1};
        int k = 2;
        std::cout << "Subarrays summing to " << k << ": " << subarraySum(nums, k) << "n";
        return 0;
    }
    

    Complexity: O(N) time and O(N) memory.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  4. 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?

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:27 pm

    Here is the C++20 digital logic state machine for finding the unique number when all other numbers appear 3 times. Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> #include <vector> int singleNumber(const std::vectorRead more

    Here is the C++20 digital logic state machine for finding the unique number when all other numbers appear 3 times.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    
    int singleNumber(const std::vector<int>& nums) {
        int ones = 0;
        int twos = 0;
    
        for (int x : nums) {
            // Bit transitions: 0 -> 1 -> 2 -> 0
            ones = (ones ^ x) & (~twos);
            twos = (twos ^ x) & (~ones);
        }
        return ones;
    }
    
    int main() {
        std::vector<int> nums = {0, 1, 0, 1, 0, 1, 99};
        std::cout << "Single Number: " << singleNumber(nums) << "n"; // Expected: 99
        return 0;
    }
    

    Complexity: Strictly O(N) time and O(1) space (2 integer variables).

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  5. Asked: September 11, 2026In: Data Structures & Algorithms, Graphs & Network Topologies

    Topological Sort: Kahn’s Algorithm (BFS) vs Tarjan’s DFS in massive dependency graphs

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:27 pm

    Here is the C++20 implementation of Kahn's Topological Sort (Indegree BFS). It avoids recursive stack overflow on huge dependency graphs and detects cycles automatically. Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> #inRead more

    Here is the C++20 implementation of Kahn’s Topological Sort (Indegree BFS). It avoids recursive stack overflow on huge dependency graphs and detects cycles automatically.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <queue>
    
    std::vector<int> findOrder(int numCourses, const std::vector<std::pair<int, int>>& prerequisites) {
        std::vector<std::vector<int>> adj(numCourses);
        std::vector<int> indegree(numCourses, 0);
    
        for (const auto& [dest, src] : prerequisites) {
            adj[src].push_back(dest);
            indegree[dest]++;
        }
    
        std::queue<int> q;
        for (int i = 0; i < numCourses; ++i) {
            if (indegree[i] == 0) q.push(i);
        }
    
        std::vector<int> order;
        order.reserve(numCourses);
    
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            order.push_back(u);
    
            for (int v : adj[u]) {
                if (--indegree[v] == 0) {
                    q.push(v);
                }
            }
        }
    
        // Cycle detection check
        if (static_cast<int>(order.size()) != numCourses) {
            return {}; // Cycle detected, no valid ordering exists!
        }
        return order;
    }
    
    int main() {
        int numCourses = 4;
        std::vector<std::pair<int, int>> prereqs = {{1, 0}, {2, 0}, {3, 1}, {3, 2}};
        auto schedule = findOrder(numCourses, prereqs);
    
        std::cout << "Course Execution Order: ";
        for (int c : schedule) std::cout << c << " ";
        std::cout << "n";
        return 0;
    }
    

    Complexity: O(V + E) time and O(V + E) space.

    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, Linked Lists & Custom Allocators

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

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:26 pm

    Here is the production C++20 implementation of Floyd's Tortoise and Hare Cycle Origin algorithm with pointer safety checks. Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> struct ListNode { int val; ListNode* next; ListNodRead more

    Here is the production C++20 implementation of Floyd’s Tortoise and Hare Cycle Origin algorithm with pointer safety checks.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    
    struct ListNode {
        int val;
        ListNode* next;
        ListNode(int x) : val(x), next(nullptr) {}
    };
    
    ListNode* detectCycleEntry(ListNode* head) {
        if (!head || !head->next) return nullptr;
    
        ListNode* slow = head;
        ListNode* fast = head;
        bool has_cycle = false;
    
        // Phase 1: Detect meeting point
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                has_cycle = true;
                break;
            }
        }
    
        if (!has_cycle) return nullptr;
    
        // Phase 2: Find cycle entrance
        ListNode* ptr1 = head;
        ListNode* ptr2 = slow;
        while (ptr1 != ptr2) {
            ptr1 = ptr1->next;
            ptr2 = ptr2->next;
        }
        return ptr1;
    }
    
    int main() {
        ListNode* n1 = new ListNode(3);
        ListNode* n2 = new ListNode(2);
        ListNode* n3 = new ListNode(0);
        ListNode* n4 = new ListNode(-4);
    
        n1->next = n2;
        n2->next = n3;
        n3->next = n4;
        n4->next = n2; // Loop back to n2
    
        ListNode* entry = detectCycleEntry(n1);
        if (entry) {
            std::cout << "Cycle detected at node with value: " << entry->val << "n";
        }
        return 0;
    }
    

    Complexity: O(N) time and strictly O(1) auxiliary space.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  7. Asked: September 11, 2026In: Advanced DP: Bitmask & Tree DP, Data Structures & Algorithms

    Traveling Salesperson Problem: How does Bitmask DP reduce (N – 1)! factorial to O(N^2 * 2^N)?

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:26 pm

    Here is the iterative bottom-up C++20 Bitmask DP (Held-Karp) implementation for TSP. Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> #include <vector> #include <algorithm> const int INF = 1e9; int tspHeldKarp(cRead more

    Here is the iterative bottom-up C++20 Bitmask DP (Held-Karp) implementation for TSP.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    const int INF = 1e9;
    
    int tspHeldKarp(const std::vector<std::vector<int>>& dist) {
        int n = dist.size();
        int total_masks = 1 << n;
        // dp[mask][curr_city]
        std::vector<std::vector<int>> dp(total_masks, std::vector<int>(n, INF));
    
        // Base case: start at city 0
        dp[1][0] = 0;
    
        for (int mask = 1; mask < total_masks; ++mask) {
            for (int u = 0; u < n; ++u) {
                if (dp[mask][u] == INF) continue;
    
                // Transition to next unvisited city v
                for (int v = 0; v < n; ++v) {
                    if (!(mask & (1 << v))) {
                        int next_mask = mask | (1 << v);
                        dp[next_mask][v] = std::min(dp[next_mask][v], dp[mask][u] + dist[u][v]);
                    }
                }
            }
        }
    
        // Return to start city 0
        int ans = INF;
        int final_mask = total_masks - 1;
        for (int u = 1; u < n; ++u) {
            ans = std::min(ans, dp[final_mask][u] + dist[u][0]);
        }
        return ans;
    }
    
    int main() {
        std::vector<std::vector<int>> matrix = {
            {0, 10, 15, 20},
            {10, 0, 35, 25},
            {15, 35, 0, 30},
            {20, 25, 30, 0}
        };
        std::cout << "Minimum TSP Tour Distance: " << tspHeldKarp(matrix) << "n";
        return 0;
    }
    

    Complexity: Runs in O(N^2 * 2^N) time, solving N=20 in ~1 second.

    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  8. Asked: September 11, 2026In: Data Structures & Algorithms, Hashing & Collision Resolution

    How to implement Consistent Hashing with Virtual Nodes to eliminate hot spots in distributed caches?

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:26 pm

    Here is a modern C++ implementation of Consistent Hashing with Virtual Nodes using std::map (Red-Black Tree) for logarithmic ring lookups. Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> #include <string> #includeRead more

    Here is a modern C++ implementation of Consistent Hashing with Virtual Nodes using std::map (Red-Black Tree) for logarithmic ring lookups.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <string>
    #include <map>
    #include <functional>
    
    class ConsistentHashRing {
        int replicas;
        std::map<uint32_t, std::string> ring; // Sorted hash ring
        std::hash<std::string> hasher;
    
    public:
        ConsistentHashRing(int r = 100) : replicas(r) {}
    
        void addServer(const std::string& server) {
            for (int i = 0; i < replicas; ++i) {
                std::string vnode = server + "#" + std::to_string(i);
                uint32_t h = static_cast<uint32_t>(hasher(vnode));
                ring[h] = server;
            }
        }
    
        void removeServer(const std::string& server) {
            for (int i = 0; i < replicas; ++i) {
                std::string vnode = server + "#" + std::to_string(i);
                uint32_t h = static_cast<uint32_t>(hasher(vnode));
                ring.erase(h);
            }
        }
    
        std::string getServer(const std::string& key) const {
            if (ring.empty()) return "";
            uint32_t h = static_cast<uint32_t>(hasher(key));
            
            // Find first server with hash >= key's hash
            auto it = ring.lower_bound(h);
            if (it == ring.end()) {
                it = ring.begin(); // Wrap around
            }
            return it->second;
        }
    };
    
    int main() {
        ConsistentHashRing cluster(100);
        cluster.addServer("cache-node-1.prod");
        cluster.addServer("cache-node-2.prod");
        cluster.addServer("cache-node-3.prod");
    
        std::cout << "user_session_4829 -> " << cluster.getServer("user_session_4829") << "n";
        std::cout << "order_item_9102   -> " << cluster.getServer("order_item_9102") << "n";
        return 0;
    }
    

    Complexity: O(log(R * N)) lookup speed via Red-Black tree binary search.

    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, Tries & Prefix Search Engines

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

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:26 pm

    Here is the C++20 Binary Trie implementation. To avoid dynamic heap allocations during tree insertion, we use a flat contiguous node pool. Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> #include <vector> #includeRead more

    Here is the C++20 Binary Trie implementation. To avoid dynamic heap allocations during tree insertion, we use a flat contiguous node pool.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    class BinaryTrie {
        struct Node {
            int next[2] = {-1, -1};
        };
        std::vector<Node> tree;
    
    public:
        BinaryTrie() {
            tree.emplace_back(); // Root node at index 0
        }
    
        void insert(int num) {
            int curr = 0;
            for (int i = 30; i >= 0; --i) {
                int bit = (num >> i) & 1;
                if (tree[curr].next[bit] == -1) {
                    tree[curr].next[bit] = tree.size();
                    tree.emplace_back();
                }
                curr = tree[curr].next[bit];
            }
        }
    
        int queryMaxXOR(int num) const {
            int curr = 0;
            int max_xor = 0;
            for (int i = 30; i >= 0; --i) {
                int bit = (num >> i) & 1;
                int opposite = 1 - bit;
                if (tree[curr].next[opposite] != -1) {
                    max_xor |= (1 << i);
                    curr = tree[curr].next[opposite];
                } else {
                    curr = tree[curr].next[bit];
                }
            }
            return max_xor;
        }
    };
    
    int findMaximumXOR(const std::vector<int>& nums) {
        BinaryTrie trie;
        for (int x : nums) trie.insert(x);
    
        int ans = 0;
        for (int x : nums) {
            ans = std::max(ans, trie.queryMaxXOR(x));
        }
        return ans;
    }
    
    int main() {
        std::vector<int> nums = {3, 10, 5, 25, 2, 8};
        std::cout << "Maximum XOR Pair: " << findMaximumXOR(nums) << "n"; // Expected: 28 (5 ^ 25)
        return 0;
    }
    

    Complexity: Strictly O(31 * N) = O(N) time with flat memory pooling.

    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, Heaps & Task Schedulers

    How to compute Running Median in continuous data streams with O(log N) per tick?

    Abhishek
    Abhishek Begginer
    Added an answer on September 11, 2026 at 9:26 pm

    Here is the clean C++20 Dual-Heap solution using std::priority_queue with std::greater<int> for the min-heap. This provides O(log N) insertion and O(1) median query. Modern C++20 Solution (Fully Runnable) Copy C++ Code ► Compile & Run in Online C++ Runner #include <iostream> #iRead more

    Here is the clean C++20 Dual-Heap solution using std::priority_queue with std::greater<int> for the min-heap. This provides O(log N) insertion and O(1) median query.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <queue>
    
    class MedianFinder {
        // Max-heap stores the smaller half of numbers
        std::priority_queue<int> small;
        // Min-heap stores the larger half of numbers
        std::priority_queue<int, std::vector<int>, std::greater<int>> large;
    
    public:
        void addNum(int num) {
            small.push(num);
    
            // Ensure small <= large
            if (!small.empty() && !large.empty() && small.top() > large.top()) {
                large.push(small.top());
                small.pop();
            }
    
            // Maintain size balance (small can have at most 1 more element)
            if (small.size() > large.size() + 1) {
                large.push(small.top());
                small.pop();
            } else if (large.size() > small.size()) {
                small.push(large.top());
                large.pop();
            }
        }
    
        double findMedian() const {
            if (small.size() > large.size()) {
                return static_cast<double>(small.top());
            }
            return (static_cast<double>(small.top()) + large.top()) / 2.0;
        }
    };
    
    int main() {
        MedianFinder mf;
        mf.addNum(5);
        mf.addNum(15);
        std::cout << "Median after [5, 15]: " << mf.findMedian() << "n"; // 10.0
        mf.addNum(1);
        std::cout << "Median after [5, 15, 1]: " << mf.findMedian() << "n"; // 5.0
        mf.addNum(3);
        std::cout << "Median after [5, 15, 1, 3]: " << mf.findMedian() << "n"; // 4.0
        return 0;
    }
    

    Complexity: O(log N) per tick and O(1) for median queries.

    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