𝐌𝐲 𝐅𝐚𝐯𝐨𝐫𝐢𝐭𝐞 𝐓𝐨𝐨𝐥 𝐢𝐧 𝐒𝐓𝐋: 𝐦𝐚𝐩 When it comes to solving problems efficiently, one thing I keep coming back to is map in C++ STL. What is map? 𝐦𝐚𝐩 𝐢𝐬 𝐚𝐧 𝐚𝐬𝐬𝐨𝐜𝐢𝐚𝐭𝐢𝐯𝐞 𝐜𝐨𝐧𝐭𝐚𝐢𝐧𝐞𝐫 𝐭𝐡𝐚𝐭 𝐬𝐭𝐨𝐫𝐞𝐬 𝐝𝐚𝐭𝐚 𝐢𝐧 𝐤𝐞𝐲-𝐯𝐚𝐥𝐮𝐞 𝐩𝐚𝐢𝐫𝐬 𝐚𝐧𝐝 𝐤𝐞𝐞𝐩𝐬 𝐤𝐞𝐲𝐬 𝐚𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲 𝐬𝐨𝐫𝐭𝐞𝐝. Example: {key → value} like {1 → 3} means number 1 appears 3 times — here 𝐢𝐭.𝐟𝐢𝐫𝐬𝐭 𝐠𝐢𝐯𝐞𝐬 1 (𝐤𝐞𝐲), 𝐢𝐭.𝐬𝐞𝐜𝐨𝐧𝐝 𝐠𝐢𝐯𝐞𝐬 3 (𝐟𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐲), and it is the iterator. Why? Because it makes life so much easier • 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜 𝐬𝐨𝐫𝐭𝐢𝐧𝐠 𝐨𝐟 𝐤𝐞𝐲𝐬 • 𝐄𝐚𝐬𝐲 𝐟𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐲 𝐜𝐨𝐮𝐧𝐭𝐢𝐧𝐠 • 𝐂𝐥𝐞𝐚𝐧 𝐚𝐧𝐝 𝐫𝐞𝐚𝐝𝐚𝐛𝐥𝐞 𝐜𝐨𝐝𝐞 • 𝐑𝐞𝐝𝐮𝐜𝐞𝐬 𝐜𝐨𝐦𝐩𝐥𝐞𝐱 𝐥𝐨𝐠𝐢𝐜 𝐢𝐧𝐭𝐨 𝐬𝐢𝐦𝐩𝐥𝐞 𝐥𝐢𝐧𝐞𝐬 The best part? Using map, we can solve multiple questions on LeetCode with the same pattern — especially problems based on: • 𝐅𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐲 𝐜𝐨𝐮𝐧𝐭𝐢𝐧𝐠 • 𝐃𝐮𝐩𝐥𝐢𝐜𝐚𝐭𝐞𝐬 / 𝐩𝐚𝐢𝐫𝐬 • 𝐇𝐚𝐬𝐡𝐢𝐧𝐠 𝐜𝐨𝐧𝐜𝐞𝐩𝐭𝐬 Recently, while solving a problem on counting “good pairs”, map helped me: • 𝐒𝐭𝐨𝐫𝐞 𝐟𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐢𝐞𝐬 𝐞𝐟𝐟𝐨𝐫𝐭𝐥𝐞𝐬𝐬𝐥𝐲 • 𝐀𝐩𝐩𝐥𝐲 𝐭𝐡𝐞 𝐬𝐢𝐦𝐩𝐥𝐞 𝐟𝐨𝐫𝐦𝐮𝐥𝐚: 𝐟 * (𝐟 - 1) / 2 • 𝐂𝐨𝐧𝐯𝐞𝐫𝐭 𝐚 𝐛𝐫𝐮𝐭𝐞-𝐟𝐨𝐫𝐜𝐞 𝐎(𝐧²) 𝐬𝐨𝐥𝐮𝐭𝐢𝐨𝐧 𝐢𝐧𝐭𝐨 𝐎(𝐧 𝐥𝐨𝐠 𝐧) Sometimes, it's not about writing complex code… it's about choosing the right data structure. Once you master map, you unlock solutions to many problems with the same approach What’s your go-to STL container? #cpp #stl #coding #datastructures #leetcode #programming #developers
Map in STL: Simplify Your C++ Coding
More Relevant Posts
-
🚀 𝐇𝐚𝐬𝐡𝐢𝐧𝐠 + 𝐏𝐫𝐞𝐟𝐢𝐱/𝐬𝐮𝐟𝐟𝐢𝐱 𝐒𝐮𝐦 𝐏𝐨𝐰𝐞𝐫𝐟𝐮𝐥 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 𝐢𝐧 𝐂𝐨𝐦𝐩𝐞𝐭𝐢𝐭𝐢𝐯𝐞 𝐏𝐫𝐨𝐠𝐫𝐚𝐦𝐦𝐢𝐧𝐠 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐭𝐚𝐭𝐞𝐦𝐞𝐧𝐭: Given an integer array nums and an integer k, return true if there exists a continuous subarray of length at least 2 such that the sum of the subarray is a multiple of k. Example: nums = [23, 2, 6, 4, 7], k = 6 Output: true Because the entire array sum becomes 42 and 42 is divisible by 6. 🔥 𝐎𝐩𝐭𝐢𝐦𝐚𝐥 𝐈𝐝𝐞𝐚: Instead of checking every possible subarray using brute force O(N²), we can use: • Prefix Sum • Modulo Arithmetic • Hash Map 𝐊𝐞𝐲 𝐎𝐛𝐬𝐞𝐫𝐯𝐚𝐭𝐢𝐨𝐧: If two prefix sums give the same remainder when divided by k, then the subarray between them has a sum divisible by k. Suppose: prefixSum[i] % k == prefixSum[j] % k Then: (prefixSum[j] - prefixSum[i]) % k == 0 That means the subarray from i+1 to j is divisible by k. 💡 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: Maintain running prefix sum Compute prefixSum % k Store first occurrence of every remainder in a hash map If same remainder appears again and distance between indices is at least 2, return true Why store only first occurrence? Because we want the maximum possible subarray length and earliest index gives larger distance. ⏱ Time Complexity: O(N) 📦 Space Complexity: O(N) This is one of the most important hashing concepts because the exact same logic is used in: • Count subarrays divisible by k • Longest subarray with equal 0s and 1s • Longest subarray with given sum • Continuous subarray sum problems • Prefix remainder based problems Optimal approach code link: https://lnkd.in/g5u3vPhd #CompetitiveProgramming #DSA #Hashing #PrefixSum #Cpp #Coding #Leetcode #Algorithms #Programmer #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 560 of #750DaysOfCode 🚀 🔍 LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers Today’s problem was a Hard-level DP challenge that really tested optimization and state management 🧠⚡ 💡 Problem Insight: We are typing a word using two fingers on a grid keyboard, and we need to minimize the total movement distance. 👉 Key twist: Both fingers can start anywhere (no initial cost!) At each step, we choose which finger to move ✨ Approach I Used (3D Dynamic Programming): ✔ State: dp[i][j][k] → Minimum cost after typing i characters Finger 1 at letter j Finger 2 at letter k ✔ Transition: Move Finger 1 → cost = distance(j → current char) Move Finger 2 → cost = distance(k → current char) ✔ Take minimum of both choices at every step 💻 Key Optimization: Represent characters as indices (0–25) Use grid math: row = index / 6 col = index % 6 🧠 Learning: This problem is a classic example of: 👉 State compression + decision making at each step 👉 Choosing the optimal path among multiple moving agents ⚡ Complexity: Time: O(n × 26 × 26) Space: O(n × 26 × 26) 💬 Takeaway: When multiple agents (like fingers, robots, etc.) are involved, think in terms of DP states representing positions of each agent. #LeetCode #DSA #DynamicProgramming #Java #CodingJourney #ProblemSolving #Tech #Developers #100DaysOfCode
To view or add a comment, sign in
-
-
🔍 Solved: Search in a 2D Matrix II (LeetCode 240) Today I worked on an interesting problem that looks simple at first but really tests your understanding of matrix properties. Instead of going with brute force or applying binary search on each row, I used the elimination approach to optimize the search. 💡 Key Insight: The matrix is sorted both row-wise and column-wise. So, starting from the bottom-left corner, we can eliminate either: 1. an entire row (if current element > target), or 2. an entire column (if current element < target) This reduces the search space efficiently at every step. ⚡ Approach Highlights: 1. Start from bottom-left 2. Move up if the value is too large 3. Move right if the value is too small ⏱️ Time Complexity: O(m + n) 📦 Space Complexity: O(1) This approach is much more efficient than checking every element and is a great example of how recognizing patterns in sorted data structures can lead to optimal solutions. #DataStructures #Algorithms #DSA #ProblemSolving #CodingInterview #LeetCode #LeetCodeDaily #CodingPractice #SoftwareEngineering #Programming #Coding #Developer #Tech #ComputerScience #CodeNewbie #Cpp #LearningInPublic #100DaysOfCode #CodeEveryday #KeepLearning #TechJourney #SelfImprovement
To view or add a comment, sign in
-
-
I love when a simple function hides something much deeper. 🧩 Look at this: f(n) = n + diff Seems easy, right? But here's the catch — diff isn't fixed. It repeats: 5 → 4 → 3 → 2 → 1 → 0 → 5 → 4 → ... So the real puzzle is: which diff applies to which n? --- Here's what I found when I dug into it: 🔁 One line of code solves everything: diff = [5,4,3,2,1,0][n % 6] 📌 Every 6th number is a FIXED POINT — f(n) = n (the output equals the input) 🔀 Some sequences hide TWO rules taking turns: 2 → 6 → 7 → 21 → 22 → 66 → ? (×3, then +1, then ×3, then +1...) 📈 Some patterns grow in the differences, not the values: 1→2, 2→4, 3→7, 4→11, 5→? (+2, +3, +4, +5... so the answer is 16) --- The moment everything clicked: The % (modulo) operator is the key to unlocking repeating patterns in code. Once you see it, you can't unsee it. --- I've put together the full detailed solutions to all 13 questions in simple, easy-to-read English — attached as a PDF below 👇 If you enjoy this kind of logic puzzle, save this post — and try Q3 in the comments before peeking at the PDF! 😄 #Logic #ProblemSolving #Patterns #Programming #Puzzles #CriticalThinking #Coding #MathIsBeautiful
To view or add a comment, sign in
-
You've nodded along when someone said "that lives on the heap," but never quite understood why memory is split between Stack and Heap? I just published a deep dive that breaks down: ✴️ Why StackOverflowError actually happens ✴️ How Stack frames get pushed and popped ✴️ When value types escape to the Heap ✴️ Why closures force data out of the Stack This isn't theory, it's the foundation behind every memory leak you've debugged and every recursion limit you've hit. #SoftwareEngineering #MemoryManagement #Programming #DeveloperCommunity
To view or add a comment, sign in
-
Day 11/60 Continuing Chapter 2- Flow Control Topic II - Coding Else Statements Great software doesn’t just decide what to do when a condition is True , it also has a back-up plan if the condition is False . For example - making a program that switches the lights on if is_on is True and off if is_on is False . We already know if statements help us execute code if a condition like available is True . 🧩Code available = True if available: print("In stock") 🖥️Output In stock Let's add another if statement that uses the not operator to run a different code block if the condition is False . 🧩Code available = True if available: print ("In stock") if not available print ("Out of stock") 🖥️ Output In stock Now Instead of creating two if statements, we use an if / else statement to achieve the same result. 🧩Code available = False if available: print("1 in stock") else: print("Out of stock") 🖥️ Output Out of stock The else statement of an if / else statement always goes at the end. 🧠Challenge of the day What does this display in the console? 🧩Code is_subscribed = True if is_subscribed: print("Enjoy 10% off!") else: print ("Become a subscriber!") #python #programming #ai #bigtech
To view or add a comment, sign in
-
🧼 Clean Code and 📘 A Philosophy of Software Design are often treated like opposing camps. But if you read them carefully, they agree on more than their fans usually admit. A few shared ideas stand out: 🔹 Naming is design work 🔹 Modules should be deep, not just small 🔹 Duplication is a signal, not always a sin 🔹 The real enemy is complexity In my latest article, I walk through the places these books overlap by using a research notebook as the running example. https://lnkd.in/eNj3Rmty What’s the messiest script, notebook, or prototype you’ve turned into something you were actually proud of? #SoftwareEngineering #CleanCode #SoftwareDesign #Python #CodeQuality
To view or add a comment, sign in
-
The Architecture of Logic: Why Your "Instruction Set" Matters More Than Your Language We’ve become obsessed with the "what" of technology: What framework are you using? What library did you import? What language is the most popular this year? But if you strip away the syntax of Python, Rust, or JavaScript, you are left with the only thing that actually matters: The Algorithm. Programming is not "Coding" Coding is just the act of translating human intent into a format a machine understands. True programming is the architecture of logic. It is the ability to take a complex problem and break it down into a finite, definite set of instructions. The Library Trap Libraries are useful "black boxes." They save time, but they can also create a ceiling for your growth. A Coder knows how to call a function from a library. An Engineer knows how to replicate that function’s logic with a pen and paper. When we rely too heavily on pre-packaged tools, we lose the ability to see the system as a whole. We start solving problems by "finding a tool" instead of "designing a solution." The Universal Blueprint An algorithm is universal. If your logic is sound, it doesn't care about the substrate. It works: As a flow of electrical signals in a CPU. As a set of "If-Then" rules on a whiteboard. As a Standard Operating Procedure (SOP) for a human team. If you can’t verify your logic without a computer, you don't own the logic the library does. Final Thought Don't just be an "expert" in a specific keyword or framework. Be an architect of instructions. Master the ability to move data from State A to State B with such clarity that the language you choose becomes the least interesting part of the project. Are you building systems, or are you just calling functions? #ComputerScience #SystemDesign #SoftwareArchitecture #EngineeringMindset #ProblemSolving #Logic
To view or add a comment, sign in
-
-
Built something I’m genuinely proud of: LogicLock 🚀 In many projects, business rules slowly drift away from the actual code. Everything looks fine — until production breaks. That’s the problem I wanted to solve. LogicLock is a Python CLI tool that validates rule definitions against real implementation code — before things go wrong. It helps catch: • Rule drift between spec and code • Conflicts across rule definitions • Unsafe mismatches before release What I focused on while building it: • AST-based repository scanning for deep logic validation • Faster CI checks using multiprocessing + incremental file-hash caching • CI/CD-friendly outputs (SARIF, JSON, strict exit codes) • Reusable GitHub Action for plug-and-play integration This project pushed me to think beyond coding — into developer tooling, reliability, and shift-left quality automation. Still improving it, and I’d really value feedback from engineers working on static analysis, rule engines, or CI/CD systems. Try it here: --GitHub: https://lnkd.in/gtVTJaZe --PyPI: https://lnkd.in/gWTM7QxU #Python #DevTools #StaticAnalysis #CICD #GitHubActions #SoftwareEngineering #OpenSource
To view or add a comment, sign in
-
-
“How do you even solve LeetCode questions?” 🤔 It’s not easy. Anyone saying it is… is either lying or not doing the hard ones. First, you struggle. You stare at the problem and it makes zero sense. Then you start identifying patterns — sliding window, two pointers, DP, greedy… slowly things begin to connect. After that, dry run. Always. Notebook > brain. ✍️ You manually walk through examples, break the logic, fix the mistakes before even touching the compiler. Then comes coding. And yeah, sometimes you don’t even know the exact syntax — but if your logic is solid, you figure it out. Basics matter more than memorized code. And let’s be honest — AI can help, but blindly copying is useless. If you use it, use it to understand the approach, not to fake progress. Otherwise you’re just cheating yourself. Real improvement = Pattern recognition → Dry run → Logic → Code → Debug → Repeat 🔁 No shortcuts. Just uncomfortable consistency. #LeetCode #DSA #CodingJourney #ProblemSolving #Consistency #LearnToCode
To view or add a comment, sign in
-
Explore related topics
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