LeetCode Problem: Longest Common Prefix What I Learned: • How nested loops simulate 2D comparison (character index vs string index) • Comparing each string character with the first string as a reference • Using the OR operator (||) to handle multiple stopping conditions • Understanding short-circuit evaluation to prevent unnecessary checks • How .slice(0, i) extracts the valid prefix before mismatch • Why return immediately stops the entire function execution • Handling edge cases like complete match or no common prefix • Writing an efficient O(n × m) solution using simple iteration logic Problem Summary: You’re given an array of strings and need to find the longest common prefix among them. The core idea is: Compare each character of the first string With the same position in all other strings. If: • A string becomes shorter • OR characters don’t match → Stop immediately and return the prefix until that index. If no mismatch is found after full iteration → return the entire first string. This problem strengthened my understanding of control flow, string indexing, and early returns in JavaScript. A great example of breaking execution at the right time instead of overcomplicating logic. #100DaysOfLeetCode #leetcode #javascript #problemsolving #codingjourney #DSA #StringManipulation #AlgorithmicThinking Link: https://lnkd.in/gnvmJK-r
Longest Common Prefix LeetCode Problem Solution
More Relevant Posts
-
What is the difference between Expression and Statement?Expression: produces a value. Statement: performs an action. Example: let x = 3 + 4 * 6; ---------- (i) This is one statement and contains three expressions: 4 * 6 = 24 3 + 24 = 27 x = 27 Here, the calculation happens through expressions. How the JS engine works for this equation: 1.Parsing i. Lexical analysis (tokenization) ii. AST (Abstract Syntax Tree) creation 2.Traversal – the engine goes through the AST nodes. 3.Runtime – expressions are evaluated, variables are assigned. 4.Display / Output – the final value is stored and available in memory. Expressions are very important because all calculations in JavaScript happen through them. Concepts like prefix and postfix operators also come from expressions. If you want to know details, you can see this video.
JavaScript Syntax Explained | Variables, Memory Allocation & JS Engine Workflow
https://www.youtube.com/
To view or add a comment, sign in
-
📣 𝗡𝗲𝘅𝘁 𝗕𝗹𝗼𝗴 𝗶𝘀 𝗛𝗲𝗿𝗲! ⤵️ Array Methods You Must Know — Writing Less Loops, More Logic ⚡🧠 Working with arrays using only loops feels repetitive. Modern JavaScript gives cleaner tools — and this blog explains them step by step. 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/gqQKdsAc 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Adding and removing elements using push, pop, shift, unshift ⇢ Looping arrays cleanly with forEach() ⇢ Transforming data using map() ⇢ Filtering values using filter() ⇢ Combining array values using reduce() ⇢ Traditional loops vs modern method chaining ⇢ Real beginner examples and practice assignments ⇢ Common mistakes like forgetting return in map/filter ⇢ Mental model to choose the right method 💬 If arrays still feel like “write loop → do work → repeat”, this article helps you understand how modern array methods make code cleaner, shorter, and easier to reason about. #ChaiAurCode #JavaScript #ArrayMethods #WebDevelopment #ProgrammingBasics #Beginners #LearningInPublic #100DaysOfCoding
To view or add a comment, sign in
-
-
🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 I recently tackled the challenge of reversing an array in-place. The core 🧩 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 was to modify the original array directly without creating a new one, which requires careful index management. To solve this, I implemented the two-pointer technique in JavaScript. I used one pointer starting at the beginning of the array and another at the end. I then swapped the elements pointed to by these pointers and moved them towards the center until they met or crossed. This ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 ensures O(1) space complexity. My 🐞 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗣𝗿𝗼𝗰𝗲𝘀𝘀 involved dry runs to trace the pointer movements and element swaps. Visualizing the array's state at each step was crucial. I also occasionally used the debugger to step through the code and confirm my understanding of the logic. A 📚 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 from this exercise was the power of in-place algorithms for optimizing memory usage, especially when dealing with large datasets. You can see the implementation in my latest PR: https://lnkd.in/d5rAw_CN What are your favorite in-place algorithms or techniques? 📦 Repo: https://lnkd.in/d5rAw_CN #DataStructures #Algorithms #JavaScript #TwoPointerTechnique #ProblemSolving #InPlaceAlgorithm #CodingChallenge #SoftwareDevelopment #ArrayManipulation
To view or add a comment, sign in
-
-
The Efficiency of the Sliding Window 🪟🏃 Consistency isn't just about writing code; it's about refining the logic until the "edge cases" no longer feel like obstacles. Today was all about moving from brute-force thinking to an optimized Sliding Window approach. 1️⃣ What I Studied & Solved I focused on the Fixed-Size Sliding Window pattern. The Problem: Finding the Maximum Sum Subarray of size k in an array of integers. The Challenge: Moving away from a nested loop approach — O(n²) — which re-calculates the sum for every possible sub-section, and instead using a linear scan — O(n). 2️⃣ Key Takeaways The Entry/Exit Strategy: Instead of re-summing k elements every time the window moves, I implemented the "O(1) update." You simply add the new element entering the window and subtract the one leaving it. Overcoming the "Off-by-One" Error: I initially struggled with missing the first and last windows. I refined my logic to ensure the maxSum is checked after the window reaches full capacity but before the trailing element is removed. Pointer Coordination: Using two pointers (p1 and p2) to represent the boundaries of the window made the "sliding" logic much more visual and easier to debug. 3️⃣ Time & Space Complexity Time Complexity: O(n) Since we only traverse the array once and perform constant-time additions/subtractions at each step, the algorithm is incredibly efficient even for massive datasets. Space Complexity: O(1) We only store a few variables (currentSum, maxSum, and the pointers) regardless of how large the input array grows. 4️⃣ Conclusion Debugging my own "off-by-one" errors today taught me more than a perfect first-time solution ever could. Engineering is about handling those boundaries. One more pattern mastered, and the "mental muscle" for problem-solving is definitely getting stronger. 💪 #JavaScript #DSA #SlidingWindow #CodingJourney #WebDevelopment #SoftwareEngineering #Consistency #ProblemSolving
To view or add a comment, sign in
-
-
JavaScript’s sort() can silently break your algorithms. I was solving LeetCode #350 (Intersection of Two Arrays II) using the two-pointer approach and hit an unexpected issue. I sorted the arrays like this: nums.sort() It looked fine… until it wasn’t. Example: [1, 2, 10, 5].sort() // → [1, 10, 2, 5] Why? Because JavaScript sorts lexicographically (as strings) by default. So the engine actually compares: "1", "10", "2", "5" Correct numeric sorting requires a comparator: nums.sort((a, b) => a - b) Without this, algorithms that rely on sorted arrays (binary search, two-pointer techniques, etc.) can produce incorrect results. #JavaScript #WebDevelopment #Programming #CodingTips #LeetCode #Algorithms #SoftwareEngineering #FrontendDevelopment
To view or add a comment, sign in
-
-
It's 5:45 am & I am still looking at my dreams. Today[2/28/2026] is day 23 of learning javascript Today & tommorow i will learn are: 1. Difference between let, const & var 2. How to use the default parameter 3. Template string, Multiline string, Dynamic string 4. Arrow Function Syntax, params 5. Spread Operator, Array Max, Copy Arrays 6. Object & Array destructuring 7. Keys, Values, Entries, Delete, Seal, Freeze 8. Accessing Object Data: Nested Object, Optional Chaining 9. Looping Object 10. Primitive Type, Non Primitive Type 11. Null Vs Undefines 12. Truthy & Falsy Values 13. ==, === , implicit conversion 14. Block Scope, Global Scope, Simple Unders. of Hoisting 15. Closure 16. Callback Function & pass different function 17. Function Arguments, pass by ref. pass by value 18. Map, ForEach 19. Filter, Find, Reduce #letsconnect #programmer #frontenddeveloper #mernstakedeveloper #Coding
To view or add a comment, sign in
-
Solved Linked List Cycle II using Floyd’s Cycle Detection Algorithm (Tortoise and Hare). The approach uses two pointers moving at different speeds to first detect the cycle and then identify the exact node where the cycle begins. Once the pointers meet, resetting one pointer to the head and moving both one step at a time leads them to the cycle start node. Key Takeaways: Efficient cycle detection in linked lists O(n) time complexity O(1) space complexity Classic two-pointer technique #DataStructures #Algorithms #LinkedList #JavaScript #LeetCode #ProblemSolving #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 I recently tackled a fun logical puzzle: how to move all zeroes to the end of an array while maintaining the relative order of the non-zero elements. This challenge, which I've documented in my latest PR (https://lnkd.in/dSXWnSES), really tested my ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 to array manipulation. My solution involved iterating through the array and using a pointer to keep track of the position where the next non-zero element should be placed. This allowed me to effectively "compress" the non-zero elements to the front, implicitly leaving zeroes at the end. During the process, I leaned on dry runs to trace the array's state and visualize the pointer movements. When I hit a snag, the debugger was invaluable for stepping through the logic line by line and understanding exactly where my assumptions were off. A key takeaway for me was the power of in-place modification and how a well-placed pointer can simplify array problems significantly. How do you ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 similar array manipulation challenges? Share your strategies below! 📦 Repo: https://lnkd.in/dSXWnSES #ArrayManipulation #JavaScript #Algorithms #ProblemSolving #CodingChallenge #DataStructures #InPlaceAlgorithms #LogicalReasoning #SoftwareDevelopment #LeetCodeStyle
To view or add a comment, sign in
-
-
Arrow Functions — the modern way to write functions Here's the thing about arrow functions. They don't do anything a regular function can't do. They just do it in far fewer characters. And once you see them inside map() and filter(), you never want to go back. In this chapter I cover: → What arrow functions are and why they exist → Basic syntax with a full anatomy diagram (every part labelled) → One parameter — when you can drop the parentheses → Multiple parameters — when they come back → Implicit return vs explicit return (the biggest shortcut) → Arrow vs normal function — comparison table The moment it clicks for most people: Instead of: const doubled = numbers.map(function(n) { return n * 2; }); You write: const doubled = numbers.map(n => n * 2); Same result. One line. Instant readability. Link : https://lnkd.in/gJJV8ARv checkout the hashnode profile : https://lnkd.in/gAwxuryw #JavaScript #ES6 #WebDevelopment #LearnToCode #Frontend #JSFundamentals #chaicode #hoteshchoudhary #piyushgargh
To view or add a comment, sign in
-
-
When Prefix Sums Repeat, Something Interesting Happens 🔁📊 Solved LeetCode 523 today. Problem 🔍 Check if a subarray of length ≥ 2 exists whose sum is divisible by k. Initial thought 🧠 Check every subarray using prefix sums. But that quickly becomes O(n²). Better approach 🚀 Use Prefix Sum + Remainder HashMap. Store the first index where each remainder appears. If the same remainder appears again and currentIndex - previousIndex >= 2, a valid subarray exists. Mental model 🧩 If: prefix[j] % k = prefix[i] % k Then: prefix[j] - prefix[i] is divisible by k. Interview takeaway 🎯 Subarray + divisibility → Prefix Sum + Remainder tracking. Practical insight 💡 Store the first occurrence of each remainder to maximize subarray length detection. This same pattern appears in problems like 974 and 560. #DSA #LeetCode #Algorithms #PrefixSum #HashMap #JavaScript #CodingInterview #InterviewPrep
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