💻 Solving “Longest Common Prefix” on LeetCode (JavaScript Edition) Today I solved the “Longest Common Prefix” problem on LeetCode — a classic string challenge that’s simple on the surface but elegant when you find the right approach. 🧩 The challenge: Given an array of strings, return the longest prefix that’s common to all of them. Example: ["flower", "flow", "flight"] → "fl" ⚙️ My solution (JavaScript): Instead of checking every string one by one, I decided to sort the array first. This way, only the first and last words in sorted order need to be compared — because they’ll show the full range of differences in the array. 🧠 Why I like this approach: It’s clean and easy to reason about. Sorting reduces the comparison scope. It demonstrates how a small insight can simplify a problem significantly. 💬 Takeaway: Sometimes the most elegant solutions come from looking at the data differently — not from writing more code. #LeetCode #JavaScript #Coding #ProblemSolving #SoftwareEngineering #LearningJourney
Solved "Longest Common Prefix" on LeetCode with JavaScript
More Relevant Posts
-
🚀 Day 9 of My 30 Days of JavaScript Journey ✅ Challenge: Arguments Length (LeetCode #2703) Write a function argumentsLength that returns the total number of arguments passed to it — no matter how many or what type! This challenge is a simple yet powerful way to understand rest parameters in JavaScript. 💻 Language Used: JavaScript ❓ Problem Link: https://lnkd.in/g8gK65Cp 💡 Solution: https://lnkd.in/gJQyNBaq 🧠 Concept Highlighted: This problem emphasizes the use of rest parameters (...args) to handle variable-length arguments, a handy feature for building flexible and reusable functions in JavaScript. #Day9 #JavaScript #LeetCode #30DaysOfCode #CodingChallenge #WebDevelopment #FrontendDevelopment #LearningEveryday #ProblemSolving #ES6
To view or add a comment, sign in
-
Today, I explored one of the most important concepts in JavaScript — Functions, Parameters and Arguments ✨ 💡 Functions make code reusable and structured, while parameters and arguments help in passing data dynamically. It’s interesting to see how a small change in a function can make a big difference in output! Every concept I learn brings me one step closer to becoming a better developer 💻🚀 #JavaScript #LearningJourney #WebDevelopment #CodingDaily #FrontendDevelopment #JSFunctions
To view or add a comment, sign in
-
👻 Undefined Ghost vs. Null Void 🚫 I spent too long to fix a bug today: my API sent `{ user: null }`, but my code checked for `undefined`! 🕵️♂️ The result? Unexpected crashes! 💥 🔑 Lesson: - `undefined` = not initialized, doesn’t exist yet - `null` = definitely empty, deliberately no value 👉 Remember: `null === undefined // false` `null == undefined // true` (better to avoid `==`!) Switching my check to `if (user === null)` made my code safer and bug-free. Ever got tripped up by a tiny JavaScript detail? Drop your story below! 👇 #JavaScript #NodeJS #MERNStack #WebDev #CodingTips #DevJourney
To view or add a comment, sign in
-
-
Hidden JavaScript Trick You Should Know! Ever struggled with nested arrays? Here’s a simple method to flatten them instantly 👇 Check the image below — one line of code and your messy array becomes clean and readable. 💡 Tip: flat() can take a depth level as an argument. Try array.flat(Infinity) to flatten all levels! What’s your favorite “hidden” JavaScript method? Share it in the comments 👇 #JavaScript #WebDevelopment #CodingTips #FrontendDeveloper #100DaysOfCode #JSDeveloper
To view or add a comment, sign in
-
-
Going back to basics 🌱 In my last post, we saw how "this" can get lost when a method is called separately. So let’s take that one step deeper today. What if we could manually tell Javascript what "this" keyword should point to? That is exactly what "call()" , "apply()", and "bind()" help us do. Lets see a below code example to understand "this" : "call()" : Calls immediately, pass arguments directly. "apply()": Calls immediately, but takes arguments as an "array". "bind()": Does not call right away , returns a "new function" with fixed "this". We use these when we need to control , specially in "callbacks" and "event handlers". There is still more to uncover!!! So now my question is, do "arrow functions" also behave the same way as "regular functions" when it comes to "this"? #Javascript #Frontend
To view or add a comment, sign in
-
-
👋 Hello Connections! Hope you’re all doing great 😊 Today, I’d like to share something I learned... Stages of Errors in JavaScript. When working with JavaScript, we often face different types of errors, but not all errors are the same! Here are the three main stages of errors every developer should know: Syntax Error, Runtime Error, and Logical Error. 1.Syntax Error (Compile-Time): Occurs when your code has a syntax mistake — like missing brackets, commas, or incorrect keywords. Example:console.log("Hello World" **// missing parenthesis//** 2. Runtime Error (Execution-Time): Happens while the program is running for example, when you use an undefined variable or call a non-existing function. Example: let x = 10; console.log(y); **// y is not defined//** 3.Logical Error: The code runs without crashing, but the output is wrong due to incorrect logic. For Example: let num = 5; if (num = 10) { console.log("Number is 10"); } **//Wrong logic/output//** #JavaScript #WebDevelopment #ErrorHandling #10000coders #FresherJourney #TechLearning
To view or add a comment, sign in
-
-
Extracting Types from Arrays Ever needed to get the type of items inside an array without rewriting it manually? You can achieve that with TypeScript as follows ⬇️. const statuses = ["active", "inactive", "pending"] as const; type Status = (typeof statuses)[number]; // "active" | "inactive" | "pending" That is because Arrays in JavaScript are actually objects with numeric keys, So [number] literally means: “Give me the type of whatever is stored at any index in this array.” It even works with arrays of objects: const tabs = [ { label: "Home", value: "/home" }, { label: "About", value: "/about" }, ]; type Tab = (typeof tabs)[number]; // { label: string; value: string; } 💡 This applies the Open/Closed Principle (OCP). #TypeScript #WebDevelopment #Frontend #CodingTips #JavaScript #LearnInPublic
To view or add a comment, sign in
-
-
🚀 Day 19 of 30 Days of JavaScript – LeetCode Problem: 1207. Unique Number of Occurrences Today’s challenge was all about checking whether the number of occurrences of each value in an array is unique. ✅ My Approach 1️⃣ Count occurrences I used a for...of loop to count how many times each element appears in the array. 2️⃣ Store frequency results This gives me an object holding the occurrence count of every unique item. 3️⃣ Convert to a Set I extracted the values and converted them into a Set using new Set(), since a set automatically removes duplicates. 4️⃣ Compare values Arrays and sets can’t be directly compared, so I converted both to strings using JSON.stringify() to compare their datatype + values. 5️⃣ Return result If both match, I return true; otherwise, false. #JavaScript #LeetCode #30DaysOfCode #codingjourney #developerlife
To view or add a comment, sign in
-
-
JavaScript for 15 Days – Day 6: If / Else Statements. Today you'll know how to make your JavaScript code think and decide using if, else if, and else statements. These structures allow programs to run different blocks of code based on specific conditions just like real-life decisions: let score = 85; if (score >= 90) { console.log("Excellent!"); } else if (score >= 70) { console.log("Good job!"); } else { console.log("Keep practicing!"); } Key Takeaways: if checks the first condition. else if tests another one if the first fails. else runs only when all above are false. Conditional statements are what make code dynamic and smart they let programs respond to different situations! #JavaScript #FrontendDevelopment #WebDevelopment #CodingJourney #LearnToCode #15DaysJS #DevPerDay
To view or add a comment, sign in
-
👀 JS Macro vs Micro tasks: A very important concept of JS, often ignored, but can put you in hours long debugging sessions 😂 🧩 Basically, JS doesn’t just have one queue — it has two (if categorized majorly on priority basis): Macrotasks: timers, I/O, setTimeout, etc. Microtasks: promises, queueMicrotask, process.nextTick etc. Microtasks run right after the current stack — before the next macrotask. So even a setTimeout(..., 0) gets delayed behind promises. That’s why code like attached image prints in this order: ``` promise timeout ``` You can read more about this in the article below: https://lnkd.in/gEjWn3_S #JavaScript #NodeJS #EventLoop #AsyncProgramming #WebDevelopment #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
More from this author
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