C++ Nit Pick : Lambda Captures Are const Do the below code work? int x = 10; auto lam = [x]() { x++; return x; }; Looks fine 🤔 Nope. there’s a subtle issue. This does not compile. 💡 Why ? By default, a lambda’s operator() is const. So the compiler treats it roughly like: struct { int x; int operator()() const { return x; } }; That const means: You cannot modify captured-by-value members inside the lambda. So x++ is illegal. ✅ The Fix Add mutable keyword to remove the implicit const. 🧠 Why This Exists Making operator() const by default: - Makes lambdas safer - Allows them to work in more contexts - Prevents accidental state mutation as they are often used in algorithms like : std::sort(vec.begin(), vec.end(), [x](inta, intb) { returna<b; }); #cpp #softwareengineering #coding
C++ Lambda Captures: Avoiding Implicit Const
More Relevant Posts
-
Today’s random problem was 3310. Remove Methods From Project The problem asks us to determine which methods can be safely removed from a project without breaking any dependencies. Each method may invoke other methods, and if a method is removed, any method depending on it directly or indirectly may also be affected. Key Insight: Methods form a directed graph where edges represent invocations. A method can only be removed if none of the remaining methods depend on it. Instead of checking dependencies repeatedly, we can precompute the indegree of each method (number of methods calling it) and track all methods reachable from the target method. Problem Is Tricky Because of Dependencies: Reachability: Removing a method affects all methods it calls directly or indirectly. Dependency Awareness: Methods with incoming edges from outside the removable set cannot be removed. Mutation Order: We must traverse the graph carefully to avoid corrupting dependency counts during processing. My Approach: I used a DFS-based solution: First DFS: Traverse the graph starting from the target method. Collect all reachable methods into a set. Reduce indegrees of the methods called by each visited method to simulate “removal.” Decision Step: If any reachable method still has incoming edges after DFS, none of the methods can be removed safely, so we keep all methods. Otherwise, we remove all methods not in the reachable set. Complexity: Time: O(n + m) (each method and each invocation visited once) Space: O(n + m) (graph + recursion stack + reachable set) #LeetCode #CodingChallenge #SoftwareEngineering #Java #DataStructures #Algorithms #Graph #DFS #ProblemSolving #TechInterviewPrep
To view or add a comment, sign in
-
-
Replacing interpreter heavy wrapper layers around local LLM inference with fast, low-level, optimized code is a major systems advantage. In pragmatical deployments, cluster management and inference orchestration can matter almost as much as raw compute capacity. For off grid inference especially, removing frontend interpreter overhead from model routing, scheduling, memory movement, and request handling is critical to achieving predictable latency, higher throughput, and better hardware utilization. Funny how so many local LLM stacks are built like web apps (well i guess that skills are depleated), not inference systems. They pile Python wrappers, generic RPC (RPC aijt free, it can be very costly) layers, dynamic routing glue, and loosely coupled schedulers on top of already expensive inference. That is tolerable in prototypes. It is a liability in serious edge or off grid deployments. What actually matters is minimizing dispatch and scheduling overhead. Than go get your H100 abd beefy PSU.
To view or add a comment, sign in
-
Most people think DSA is about memorizing algorithms. Today's problem proved it's not. It's about patterns. 🚀 Day 85/365 — DSA Challenge Solved: Longest Repeating Character Replacement At first, this problem looked confusing. You can change at most k characters. And you need the longest substring with same letters. Brute force? Too slow. Then the key idea clicked: We don't need to actually replace characters. We just need to know: How many characters in the current window are NOT the most frequent character. If that number is more than k, shrink the window. If it's <= k, expand the window. This becomes a Sliding Window problem. 💡 Core Idea window_size - max_frequency <= k If this condition is true → valid window If false → move left pointer ⏱ Complexity Time: O(n) Space: O(1) Day 85/365 complete. 💻 280 days to go. Code: https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #SlidingWindow #Algorithms #LearningInPublic
To view or add a comment, sign in
-
-
✳️Day 23 of #100DaysOfCode✳️ 🚀Solved Remove Duplicate Letters ✅The goal is to remove duplicate letters so that every letter appears once, ensuring the result is the smallest in lexicographical order among all possible results. 🧠 My Approach & Implementation Steps: To solve this efficiently in O(n) time, I used a Greedy approach supported by a Monotonic Stack: 1️⃣Frequency Map: First, I built a frequency array freq[26] to keep track of the remaining count of each character in the string. This tells the algorithm if a character can be safely removed and re-added later. 2️⃣Visited Tracking: I used a boolean array visited[26] to ensure each character is added to our result only once, maintaining the "unique" constraint. 3️⃣Monotonic Stack Logic: As I iterated through the string: I decremented the character's frequency. If the character was already in the stack, I skipped it. 4️⃣The Crucial Part: While the current character was smaller than the top of the stack AND that top character appeared again later in the string (checked via the frequency map), I popped the stack and marked that character as "not visited." 💯Result Construction: Finally, I pushed the current character onto the stack and built the final string using a StringBuilder. 📊 Results: Runtime: 2 ms (Beats 89.98%) Memory: 43.64 MB (Beats 78.91%) ⚡This problem is a great reminder of how powerful stacks can be when you need to maintain a specific order while processing linear data. Onward to the next challenge! 💻🔥 #LeetCode #Java #DataStructures #Algorithms #CodingLife #ProblemSolving #SoftwareEngineering Anchal Sharma Ikshit ..
To view or add a comment, sign in
-
-
A common misunderstanding about 'this' in C++ Many developers think this is just a keyword used to access member variables. 'this' is actually a hidden pointer that the compiler passes to every non-static member function. For example: class Demo { public: int x; void setX(int x) { this->x = x; } }; Here, this->x refers to the member variable, while x is the function parameter. But internally, when we call: Demo obj; obj.setX(10); The compiler treats it like: setX(&obj, 10); So the function is actually working with the object's address through this. Another important detail: Demo* const this; this is a const pointer, meaning you cannot change what it points to, but you can modify the object through it. In const member functions: void display() const { // this becomes const Demo* const this; } Now the object cannot be modified. Also, static functions: static void show() { // no this pointer here } They don’t have this because they are not associated with any object instance. Understanding 'this' changed how I look at method calls, memory, and object behavior internally. It is a small detail, but it gives a much clearer picture of how C++ actually works under the hood.
To view or add a comment, sign in
-
Day 36 of Daily DSA 🚀 Solved LeetCode 443: String Compression ✅ Problem: Given an array of characters, compress it in-place using run-length encoding. Each group of consecutive repeating characters is replaced by the character followed by its count (if count > 1). The result must be stored back in the input array. Rules: * If a group's length is 1 → append only the character * If a group's length is > 1 → append character + count * Group lengths ≥ 10 are split into multiple characters * Must use only constant extra space * Return the new length of the array Approach: Used a StringBuilder to build the compressed string by tracking consecutive character counts, then wrote the result back into the input array. Steps: 1. Append the first character to StringBuilder 2. Iterate through the array counting consecutive duplicates 3. On a new character → if count > 1, append the count 4. Append the new character and reset count 5. Handle the last group after the loop 6. Write compressed characters back into the input array ⏱ Complexity: • Time: O(n) • Space: O(n) (StringBuilder) 📊 LeetCode Stats: • Runtime: 3 ms (Beats 12.04%) • Memory: 45.58 MB (Beats 42.35%) A great exercise in in-place array manipulation and run-length encoding — fundamentals that show up everywhere in data compression. #DSA #LeetCode #Java #Strings #RunLengthEncoding #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
The bug only happened in production. Locally, everything worked fine. Staging was clean. Tests were passing. But in production: Random 500 errors CPU spikes Database connections exhausted The issue? A background task triggering an API call that triggered another DB-heavy operation inside a transaction. Under real traffic, it created contention and lock waits. The fix wasn’t “more code.” It was: • Breaking the transaction boundary • Making the operation idempotent • Moving heavy logic to async processing • Adding structured logging for traceability That incident changed how I design backend systems. Now, I don’t just ask: “Does this work?” I ask: “What happens under concurrency?” “What happens under failure?” “What happens at scale?” Production teaches you things tutorials never will. #Python #Django #BackendDevelopment #SystemDesign #ProductionEngineering #ScalableSystems #DatabaseOptimization #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🧩 Problem: Complement of Base 10 Integer You are given a non-negative integer n. Your task is to return the complement of its binary representation. The complement means: Flip every bit in the binary representation 1 → 0 0 → 1 Important: The complement is applied only up to the most significant bit of n, not the full 32 bits. 🎯 Goal Convert the number to binary, flip all the bits, and return the decimal value of the complemented binary number. Example: n = 5 Binary representation: 5 → 101 Complement: 010 Result: 2 🧠 Key Intuition To compute the complement correctly: Find the highest set bit in the number. Only flip bits within that range. 🛠 Approach 1️⃣ Handle edge case If n == 0, return 1. 2️⃣ Find the number of significant bits using __builtin_clz(). 3️⃣ Traverse each bit of n: If the bit is 1 → append 0 If the bit is 0 → append 1 4️⃣ Reverse the generated binary string. 5️⃣ Convert the complemented binary string back to decimal. 📈 Complexity Analysis Time Complexity: O(log n) Space Complexity: O(log n) 🔗 Problem https://lnkd.in/d9QWqaKw 💻 Solution https://lnkd.in/d654Dvie #LeetCode #Cpp #DSA #BitManipulation #ProblemSolving #CodingChallenge #Algorithms #LeetCodeDailyChallenge #CompetitiveProgramming #CodingJourney
To view or add a comment, sign in
-
Day 8 #SDE Focused on array manipulation and divide & conquer techniques. Solved: • Count Inversions (using Merge Sort approach) • Segregate Even and Odd Numbers Key Learning: Problems like counting inversions highlight how modifying classic algorithms like Merge Sort can help compute results efficiently in O(n log n) time. Also revisited simple yet important two-pointer techniques for array rearrangement. #LeetCode #DSA #Arrays #MergeSort #Algorithms #Java #SoftwareEngineering
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
mutable is the stuff nightmares are made of