✳️Day 13 of #100DaysOfCode✳️ Decoding the Logic: Two Problems, One Core Strategy I recently cleared Climbing Stairs and Fibonacci Number on LeetCode with 0ms runtime. 1️⃣ Climbing Stairs (LeetCode 70) The Problem: You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? The Approach: Recursive Insight: To reach the n^{th} step, you must have come from either the (n-1)^{th} step (by taking 1 step) or the (n-2)^{th} step (by taking 2 steps). Base Cases: * If n = 0 or n = 1, there is only 1 way to be there. The Formula: Ways(n) = Ways(n-1) + Ways(n-2). 2️⃣ Fibonacci Number (LeetCode 509) The Problem: Calculate F(n), where F(n) = F(n-1) + F(n-2) for n > 1, with F(0) = 0 and F(1) = 1. The Approach: Recursive Insight: This is the "pure" mathematical version of the stairs problem. Each number is the sum of the two preceding ones. Base Cases: If n = 0, return 0. If n = 1, return 1. 🚀 Why the 0ms Runtime? In both solutions, I used Top-Down Memoization: The Problem with Simple Recursion: Without optimization, the computer recalculates the same values (like f(5)) dozens of times, leading to an exponential time complexity of O(2^n). The Memoization Fix: I introduced an array dp[]. Before calculating f(n), the code checks: "Have I solved this before?" If dp[n] is not 0, it returns the stored value instantly. If not, it calculates it once, stores it, and moves on. The Result: This simple "memory" trick brings the complexity down to O(n) linear time, making the execution nearly instantaneous. #DataStructures #Algorithms #Java #DP #SoftwareDevelopment #LeetCode
Decoding LeetCode: Climbing Stairs & Fibonacci Number Solutions
More Relevant Posts
-
✳️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
-
-
Reverse Integer – LeetCode Solution 📌 Problem Link Reverse Integer – LeetCode ⸻ 🧩 Problem Statement Given a signed 32-bit integer x, return the integer obtained by reversing its digits. If reversing x causes the value to go outside the signed 32-bit integer range [-2³¹, 2³¹ - 1], return 0. You must solve the problem without using 64-bit integers (long). ⸻ 💡 Approach To solve this problem: 1. Initialize a variable to store the reversed number. 2. Extract the last digit of the number using modulus operation. 3. Append the extracted digit to the reversed number. 4. Remove the last digit from the original number using division. 5. Before appending a digit, check for overflow and underflow conditions. 6. If overflow occurs, return 0. 7. Continue until the original number becomes 0. ⸻ ⚠️ Overflow Handling Since the integer range is limited to: • Minimum: -2147483648 • Maximum: 2147483647 Before multiplying the reversed number by 10 and adding a digit, we must verify: • It does not exceed Integer.MAX_VALUE • It does not go below Integer.MIN_VALUE If it exceeds the range, return 0. ⸻ 📊 Example Input: 123 Output: 321 Input: -123 Output: -321 Input: 1534236469 Output: 0 (Because it exceeds 32-bit integer range after reversing) ⸻ ⏱ Time Complexity O(log₁₀ n) • Because we process each digit once. 💾 Space Complexity O(1) • No extra space is used. ⸻ 🚀 Key Concepts Used • Modulus Operator • Integer Division • Overflow Checking • Looping • Basic Mathematics ⸻ 🏁 Conclusion This problem tests understanding of: • Digit manipulation • Edge case handling • Integer boundary conditions Proper overflow checking is the most important part of this solution. #java #dsa #javaprogram #dsaprogram #array #numbers #solution #leetcode #data #structure #algorithm
To view or add a comment, sign in
-
-
Day 72/100 – LeetCode Challenge ✅ Problem: #7 Reverse Integer Difficulty: Medium Language: Java Approach: Digit Extraction with Overflow Check Time Complexity: O(log₁₀ x) Space Complexity: O(1) Key Insight: Reverse integer by repeatedly extracting last digit and building result. Critical: Check overflow before final cast using long to detect > Integer.MAX_VALUE or < Integer.MIN_VALUE. Solution Brief: Extracted digits using modulo 10. Built reversed number step by step in long to detect overflow. After loop, divided by 10 to remove extra multiplication. Checked if result fits in 32-bit integer range. Handled sign separately at the end. #LeetCode #Day72 #100DaysOfCode #Math #Java #Algorithm #CodingChallenge #ProblemSolving #ReverseInteger #MediumProblem #Overflow #DigitManipulation #DSA
To view or add a comment, sign in
-
-
HI CONNECTIONS I recently tackled LeetCode 166, a problem that requires careful handling of edge cases, integer overflows, and the logic of long division. 🔍 The Challenge Given two integers representing a fraction, return the result in string format. If the fractional part repeats, enclose the repeating digit(s) in parentheses. Example: 1 / 2 = 0.5 The Twist: 2 / 3 = 0.(6) 🛠️ My Approach: Long Division with Memory The key to identifying a repeating decimal is realizing that if you encounter the same remainder twice during the division process, the digits will start to repeat from that point onward. Handle Signs & Edge Cases: Determine the sign of the result and handle the case where the numerator is 0. Use long (in Java/C++) to prevent overflow when taking absolute values (e.g., -2147483648). Integer Part: Calculate the whole number part using numerator / denominator. Fractional Part: * Use a Hash Map to store each remainder and its corresponding index in the result string. Multiply the remainder by 10 and continue the division. The Detection: If the remainder is already in the map, insert ( at the stored index and ) at the end of the string, then break. Terminate: If the remainder becomes 0, the decimal is terminating. 📊 Efficiency Time Complexity: O(\text{Denominator}) — In the worst case, the number of digits in the repeating part is less than the denominator. Space Complexity: O(\text{Denominator}) — To store the remainders in the hash map. 💡 Key Takeaway This problem is a great reminder that data structures like Hash Maps aren't just for searching—they are essential for "remembering" states in a process. Recognizing cycles is a fundamental skill in both algorithm design and system monitoring. #LeetCode #AlgorithmDesign #HashMaps #Mathematics #SoftwareEngineering #ProblemSolving
To view or add a comment, sign in
-
-
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
To view or add a comment, sign in
-
-
🔥 Day-9 — Rotate Array (Array Manipulation + Reversal Trick) 🧩 Problem: Rotate Array 💻 Platform: LeetCode (#189) Given an array, rotate it to the right by k steps. At first, this looks like a simple shifting problem. Brute force idea: Shift elements one by one, k times. Time Complexity → O(n × k). Not scalable. Better idea: Use an extra array and place elements at correct rotated positions. Time → O(n) Space → O(n) But the optimal solution? 🚀 Reverse Technique (In-Place) Steps: 1️⃣ Reverse the entire array 2️⃣ Reverse first k elements 3️⃣ Reverse remaining n − k elements That’s it. Time Complexity: O(n) Space Complexity: O(1) 💡 Why this works: Reversal repositions elements into their final rotated order without needing extra memory. It’s not obvious at first — but once you visualize it, it becomes clean and elegant. Key Takeaways: ✔ Not all array problems require extra space ✔ In-place manipulation is a powerful skill ✔ Sometimes the trick is not shifting — but reordering cleverly Each day I’m realizing: Patterns repeat. Tricks repeat. Only the surface changes. Day-9 complete. Onward 🚀 #30DaysOfCode #LeetCode #DSA #Java #Arrays #Algorithms #ProblemSolving #SoftwareEngineering #Developers
To view or add a comment, sign in
-
-
#PostLog140 🚀 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟴𝟱 – 𝗜𝘀 𝗚𝗿𝗮𝗽𝗵 𝗕𝗶𝗽𝗮𝗿𝘁𝗶𝘁𝗲? ✅ Solved using 𝗕𝗙𝗦 + 𝗚𝗿𝗮𝗽𝗵 𝗖𝗼𝗹𝗼𝗿𝗶𝗻𝗴 (𝗝𝗮𝘃𝗮) 🔎 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 • A graph is bipartite if it can be divided into 𝟮 𝘀𝗲𝘁𝘀 • No two adjacent nodes should belong to the same set • Equivalent to checking if the graph can be colored using only 𝟮 𝗰𝗼𝗹𝗼𝗿𝘀 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: 🔹 Built the graph using an 𝗔𝗱𝗷𝗮𝗰𝗲𝗻𝗰𝘆 𝗟𝗶𝘀𝘁 🔹 Maintained a 𝗰𝗼𝗹𝗼𝗿 𝗮𝗿𝗿𝗮𝘆 𝗶𝗻𝗶𝘁𝗶𝗮𝗹𝗶𝘇𝗲𝗱 𝘄𝗶𝘁𝗵 -𝟭 (unvisited) 🔹 Traversed each component using 𝗕𝗙𝗦 🔹 Assigned opposite color to neighboring nodes 🔹 If a neighbor already has the same color → ❌ Not Bipartite 🔹 Handled disconnected components by iterating through all nodes ⏱️ 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗧𝗶𝗺𝗲: O(V + E) 𝗦𝗽𝗮𝗰𝗲: O(V) This problem reinforces how powerful traversal + state management (coloring) is in graph theory. #LeetCode #DSA #Graphs #BFS #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 517 of #750DaysOfCode 🔥 LeetCode 3666 – Minimum Operations to Equalize Binary String (Hard) Today’s problem was a parity + math-based greedy optimization challenge that looks simple at first glance but requires deep observation. 🧠 Problem Summary You are given: A binary string s An integer k In one operation, you must flip exactly k different indices. Goal: Make the entire string equal to '1' using the minimum number of operations. If impossible → return -1. 💡 Key Observations 1️⃣ Let zero = number of '0' in the string. 2️⃣ Each operation flips exactly k bits. 3️⃣ Flipping changes parity (even/odd behavior becomes important). 4️⃣ We must carefully handle: When k == length When parity of k and number of zeros mismatch When operations must be even or odd This becomes a mathematical bound + parity correction problem, not a brute-force simulation. 🛠️ Approach Used Count total zeros. Handle edge cases: If no zeros → answer = 0 If len == k → only one full flip possible Compute minimum operations for: Odd number of operations Even number of operations Adjust based on parity constraints. Return minimum valid answer. Time Complexity: O(n) Space Complexity: O(1) 🎯 What I Learned ✔️ Hard problems often reduce to mathematical constraints ✔️ Parity (even/odd) reasoning is powerful in bit-flip problems ✔️ Always check feasibility conditions before optimizing ✔️ Avoid brute force when constraints go up to 10⁵ This problem really tested logical thinking beyond implementation. On to Day 518 🚀 #LeetCode #Java #DataStructures #Algorithms #ProblemSolving #HardProblems #CodingJourney #750DaysOfCode
To view or add a comment, sign in
-
-
Collections are powerful. But without type safety, they become risky. That’s why Generics exist. Before generics, collections stored Object. That meant: • You could add anything • You had to cast manually • Runtime errors were common Generics changed that. Example: List<String> names = new ArrayList<>(); names.add("Alice"); // names.add(10); ❌ compile-time error Now the compiler protects you. Generics provide: • Compile-time type safety • Cleaner code (no casting) • Better readability This is not just syntax with angle brackets. It’s a design improvement. It shifts error detection from runtime to compile time. Today was about: • Understanding <T> and type parameters • Why generics improve safety • Writing flexible but safe data structures Strong systems fail early. Generics make failure happen before execution. #Java #Generics #TypeSafety #Collections #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
-
Day 97/100 – LeetCode Challenge ✅ Problem: #105 Construct Binary Tree from Preorder and Inorder Traversal Difficulty: Medium Language: Java Approach: Recursive Construction with HashMap Lookup Time Complexity: O(n) Space Complexity: O(n) for map + recursion stack Key Insight: Preorder: [root, left subtree, right subtree] Inorder: [left subtree, root, right subtree] First element in preorder is always root Root's position in inorder splits left and right subtrees Solution Brief: Built HashMap to map inorder value → index for O(1) lookups. Maintained global index to track current root in preorder. Recursively built tree: Get root value from preorder at current index Find root position in inorder Build left subtree using elements before root Build right subtree using elements after root #LeetCode #Day97 #100DaysOfCode #Tree #BinaryTree #Java #Algorithm #CodingChallenge #ProblemSolving #ConstructBinaryTree #MediumProblem #Recursion #HashMap #DSA
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