Day 10 of #100DaysOfCode: Optimizing Logic & Cleaning Syntax 🧹 Today was about efficiency. I didn't just write new code; I looked at how to make code run faster and look cleaner. DSA: The Square Root Trick I tackled Prime Number logic. The beginner way is to check every number from 2 to n-1. That’s O(n). But I learned you only actually need to check up to the square root of n. Result: The complexity drops to O(sqrt{n}). Lesson: Math saves computing power. Development: Modern JavaScript I revisited my BMI Calculator (from Day 2) and refactored the whole thing. I swapped out the old function declarations for Arrow Functions. Old: function calculate(weight, height) { ... } New: const calculate = (weight, height) => { ... } It’s a small syntax change, but it makes the code so much more readable and concise. Double digits! 10 days down. 🚀 #JavaScript #DataStructures #Optimization #WebDevelopment #CodingJourney
Optimizing Logic & Cleaning Syntax with JavaScript
More Relevant Posts
-
Day 1 – DSA Journey | Arrays 🚀 Today, I solved two classic array problems on LeetCode and focused more on understanding the logic than just getting accepted solutions. ✅ Problems Solved 📌 Two Sum 📌 Median of Two Sorted Arrays 🔹 Two Sum Approach: I used a HashMap (Map in JavaScript) to store previously seen numbers and their indices. For each element, I calculated the subtarget = target - currentValue and checked if it already existed. Why this works: Instead of checking every pair (O(n²)), hashing lets us find the complement in constant time. What I Learned: ✅ Hashing is powerful for lookup-based problems ✅ Always think about reducing nested loops Complexity: ⏱ Time: O(n) 📦 Space: O(n) 🔹 Median of Two Sorted Arrays Approach: This problem was less about coding and more about clear thinking. I used binary search on the smaller array to find the correct partition such that: Left half contains smaller elements Right half contains larger elements Handled edge cases using -Infinity and Infinity to avoid extra conditions. What I Learned: ✅ Binary search is not just for searching elements ✅ Partition logic + edge cases decide correctness ✅ Understanding the math behind the problem is key Complexity: ⏱ Time: O(log(min(n, m))) 📦 Space: O(1) 🧠 Takeaway Some problems are solved by data structures. Some problems are solved by clear thinking. Both matter. On to Day 2 — staying consistent 🔁🚀 #DSA #Arrays #LeetCode #JavaScript #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Headline: 🧠 Thinking Mathematically: Finding the GCD of Strings The Content: Continuing my JavaScript challenge on LeetCode! Today I tackled the "Greatest Common Divisor of Strings" problem. This one is fascinating because it blends string logic with classic number theory. The Challenge: Given two strings, find the largest string x such that x divides both str1 and str2. My Approach: The Concatenation Test: A brilliant trick for this problem is checking if str1 + str2 === str2 + str1. If they don't match, a common divisor string literally cannot exist. The GCD Logic: If they pass the test, the length of the greatest common divisor string must be the GCD of the lengths of the two strings. The Solution: I implemented a recursive helper function using the Euclidean Algorithm to find the gcdLength, then simply sliced the prefix! Technical Efficiency: Time Complexity: $O(n + m)$ due to string concatenation and comparison. Space Complexity: $O(n + m)$ to store the concatenated strings. Key Reflection: It’s amazing how concepts from basic math (like GCD) find their way into modern software engineering problems. It’s all about finding the pattern before writing the first line of code. Onward to the next challenge! 📈 #LeetCode #JavaScript #CodingChallenge #ProblemSolving #SoftwareEngineering #Algorithms #MathInCode #WebDevelopment
To view or add a comment, sign in
-
-
Day 20: Property Descriptors & The "Sugar" of Classes 🏗️💎 Object-oriented JavaScript isn't just about syntax; it's about control. Today was the final deep-dive into the "Meta" layer of JS objects—understanding why Math.PI is immutable and how to build bulletproof class structures. The "Crack-It Kit" Checklist: Day 20 📑 🔹 Class Hierarchy: Mastering extends and the super() bridge. Understanding why the parent must initialize before the child can exist. 🏛️ 🔹 Static Utilities: Learning to define methods that belong to the "Blueprint" (Class) rather than the "House" (Instance). ⚙️ 🔹 The .bind() Marriage: Locking context permanently. Moving beyond immediate execution to creating reusable, context-safe functions. 🔗 🔹 Under the Hood (Descriptors): Breaking down writable, enumerable, and configurable. Solving the mystery of why built-in JS properties are unchangeable. 💎 🔹 Property Shielding: Using Object.defineProperty to hide data from loops and prevent unauthorized overwrites. 🛡️ 🔹 Object Iteration: Mastering Object.entries() and Factory Functions for cleaner, more modern data handling. 🧪 The foundation is complete. We’ve moved from basic literals to professional meta-programming. 🏗️ #JavaScript #WebDevelopment #CrackItKit #OOP #WebEngineering #CodingJourney #SoftwareArchitecture #TechInterviews #120DayChallenge
To view or add a comment, sign in
-
-
Day 16 of #100DaysOfCode: Goodbye, For-Loops. 👋 Today I forced myself to stop using for loops. I spent the entire session mastering JavaScript's higher-order array methods: map, filter, and reduce. To make sure I actually understood it, I set a rule: Type everything from memory. No copy-pasting. What I built: A statistics script that takes raw data and processes it in a single flow. map to transform data (doubling numbers). filter to clean data (keeping evens). reduce to crunch data (summing & calculating averages). The Aha Moment: The power of Chaining. Instead of writing 10 lines of loop logic, I can do this: JavaScript const result = numbers .filter(n => n % 2 === 0) .map(n => n * 2) .reduce((acc, n) => acc + n, 0); It reads like a sentence. DSA Update: No DSA today. I wanted to drill these array methods until they became muscle memory. #JavaScript #WebDevelopment #CleanCode #FunctionalProgramming #100DaysOfCode
To view or add a comment, sign in
-
🚀 Cracked the 3Sum Problem on LeetCode! Today I solved the classic 3Sum problem on LeetCode — a great test of optimization and pattern recognition. 🧠 Problem: Find all unique triplets in an array that sum to 0. ❌ Brute Force Approach: 3 nested loops Time Complexity: O(n³) Fails for large inputs (TLE) ✅ Optimized Approach (Sorting + Two Pointers): Sort the array Fix one element Use two pointers to find the remaining pair Skip duplicates smartly ⏱ Time Complexity: O(n²) 📦 Space Complexity: O(1) (excluding output) 💡 Key Learning: Sometimes the real challenge isn’t solving the problem — it’s reducing time complexity. Switching from O(n³) ➝ O(n²) makes all the difference in large-scale inputs. 🔥 What I Improved: ✔ Handling duplicates efficiently ✔ Mastering two-pointer technique ✔ Debugging Time Limit Exceeded errors ✔ Writing clean, interview-ready code Problems like 3Sum strengthen core DSA concepts that are frequently asked in technical interviews. What’s your favorite array optimization problem? 👇 #DataStructures #Algorithms #JavaScript #LeetCode #CodingInterview #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Leveling up my JavaScript logic: The Fisher-Yates Shuffle! I spent some time today diving into how online examination systems handle fairness and randomization. To solve the problem of generating unique question orders for every student, I implemented the Fisher-Yates Shuffle Algorithm. 💡 Why this approach? While many might use array.sort(() => Math.random() - 0.5), that method is actually biased and doesn't provide a truly uniform distribution. The Fisher-Yates (or Knuth) Shuffle is the gold standard because: Efficiency: It runs in O(n) time complexity. True Randomness: Every permutation of the array is equally likely. In-place potential: It can be done without extra memory (though I used the spread operator here to keep the original data immutable! 🛡️). 🛠️ The Implementation I wrapped the logic in a Higher-Order Function. This allows me to lock in the "Original Array" and generate a fresh, shuffled version whenever getPaper() is called. Key takeaway for the day: Functional programming isn't just about cleaner code; it’s about creating predictable, reusable tools for complex problems. Check out the snippet in the image below! 👇 #JavaScript #WebDevelopment #CodingLife #Algorithms #ProblemSolving #FisherYates #LearningToCode #SoftwareEngineering How do you handle randomization in your projects?
To view or add a comment, sign in
-
-
Number of steps to reduce ........................ 47 🔥 ✅ Approach 🔹 Initialize: steps = 0 carry = 0 🔹 Traverse the binary string from right to left, ignoring the most significant bit (index 0). 🔹 For each bit: Compute bit + carry 👉 If the result equals 1 (number becomes odd): One step to add 1 One step to divide by 2 Total → 2 steps Set carry = 1 👉 Otherwise (number is even): Only divide by 2 Total → 1 step 🔹 After traversal, if a carry still remains, add it to the total steps. ✅ Return the final number of steps. This problem was a great exercise in understanding: ✔ Binary operations ✔ Carry propagation ✔ Efficient simulation without actual conversions 📌 Example Input: s = "1101" Binary "1101" corresponds to 13 in decimal. Step 1️⃣: 13 is odd → add 1 → 14 Step 2️⃣: 14 is even → divide by 2 → 7 Step 3️⃣: 7 is odd → add 1 → 8 Step 4️⃣: 8 is even → divide by 2 → 4 Step 5️⃣: 4 is even → divide by 2 → 2 Step 6️⃣: 2 is even → divide by 2 → 1 ✅ Output: 6 steps #JavaScript #TypeScript #SoftwareDevelopment #FrontendDeveloper #CodingJourney #DevelopersLife #LearningInPublic #ContinuousLearning #TechLearning #DeveloperGrowth #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 LeetCode: Two Sum II - Input Array Is Sorted The goal is to find two numbers in a 1-indexed sorted array that add up to a specific target sum. Since the array is already sorted, we can find the indices efficiently without extra storage. 🛠️ My Approach 1. Initialization: I used two pointers, i starting at the beginning (index 0) and j at the end of the array. 🔡 2. Sorted Property Leverage: Instead of a nested loop, I compared the sum of elements at i and j to the target. If the sum is too high, I decrement j; if it's too low, I increment i. 🧹 3. Two-Pointer Optimization: By narrowing the window from both sides, I found the exact pair in a single pass. 📍 4. One pointer moves from the start (i), and the other from the end (j). ❌ If the sum matches the target, we return the 1-indexed positions [i + 1, j + 1] and break the loop. 📊 Efficiency Analysis ⏱️ Time Complexity: O(n) 💾 Space Complexity: O(1) #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
🚀 LeetCode: 3Sum The goal is to find all unique triplets in an array that sum up to zero. This is a significant step up from Two Sum, requiring careful handling of duplicates to ensure every triplet in the result is unique. 🛠️ My Approach Sorting for Strategy: I started by sorting the array in ascending order. This is crucial as it allows us to easily skip duplicate values and use a directional two-pointer technique. 🔡 Fixed Element Loop: I iterated through the array, treating each element as a potential first part of a triplet. To optimize, if the current element is greater than zero, I break the loop immediately since no combination of following positive numbers can sum to zero. 🧹 Two-Pointer Optimization: For each fixed element, I used two pointers—one starting just after the fixed element (l) and one at the very end (r). 📍 If the sum is too high, I move the right pointer in. If the sum is too low, I move the left pointer out. When a sum of zero is found, I capture the triplet and then skip any identical adjacent values to avoid duplicate results. ❌ This approach transforms a potential O(n^3) brute-force cubic time complexity into a much more efficient quadratic solution. 📊 Efficiency Analysis ⏱️ Time Complexity: O(n^2) due to the nested two-pointer search inside the main loop. 💾 Space Complexity: O(1) or O(n) depending on the implementation of the sorting algorithm, as we don't use extra data structures for the search itself. Achieving a 91.76% runtime beat on this classic problem! Handling edge cases and duplicates is where the real engineering happens. 🚀👨💻 #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
⚠️ That One-Liner Math.max(...arr) Might Be Slowing You Down We’ve all written this: Math.max(...arr) It’s clean. It’s readable. It feels very JavaScript-y. 😌 But here’s the uncomfortable truth: It’s not always safe in production. What Actually Happens Behind the Scenes? When you use: Math.max(...largeArray) JavaScript doesn’t “loop” the array. It expands every single element into a function argument. If your array has 10 elements → fine. If it has 10,000 → risky. If it has 100,000+ → 💥 you might hit: ❌ Maximum call stack size exceeded ❌ Engine argument limits ❌ Memory spikes ❌ Unexpected crashes Most JS engines have limits on how many arguments a function can accept. And yes — spread turns your array into individual arguments. 🧠 The Safer Alternative Instead of relying on argument expansion: arr.reduce((max, val) => val > max ? val : max, -Infinity) Why this is better: ✔️ No argument explosion ✔️ Handles very large arrays safely ✔️ More predictable performance ✔️ Production-friendly. 🚀 The Real Lesson Modern syntax ≠ Always better. As engineers, especially when building scalable systems, we should ask: What does this do under the hood? How does it behave with large inputs? Will this break at scale? Clean code isn’t just about shorter lines. It’s about understanding trade-offs. If you’ve ever debugged a production issue caused by a “beautiful one-liner,” you know the pain. 😅 What’s another JavaScript shortcut that looks elegant but hides a performance trap? 👇 #JavaScript #WebDevelopment #FrontendDevelopment #Programming #SoftwareEngineering #CleanCode #PerformanceOptimization #TechLeadership #CodingTips #Developers
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