Cracking the Logic: Finding the First Occurrence! I’ve always believed that the best way to master a programming language is by building your own logic from scratch before jumping into built-in methods. Today, I worked on a classic problem: Finding the starting index of a substring within a string. The Task: Given two strings, identify the index where the second string first appears in the first one. For example: Input: ("sadbutsad", "sad") ➔ Output: 0 My Approach: Array Transformation: Split the strings into arrays to iterate through each character. Filtering Logic: Used the .filter() method to check if the main string's characters exist in the target substring using .includes(). Index Tracking: Pushed the matching indices into a temporary array. Result Extraction: Sliced the first element to get the exact starting point. The Code: JavaScript function findIdStr(a, b) { const repetArrId = [] const y = a.split('') const x = b.split('') y.filter((v, idx) => { if (x.includes(v)) { repetArrId.push(idx) } }) const result = repetArrId.slice(0, 1) console.log("Starting Index:", result[0]) } findIdStr("sadbutsad", "sad") // Output: 0 While JavaScript offers built-in tools like .indexOf(), breaking it down manually helps in understanding how data flows and how loops work under the hood. I’m curious—how would you optimize this logic? Let’s discuss in the comments! #JavaScript #WebDevelopment #ProblemSolving #CodingJourney #SoftwareEngineering #LogicBuilding #JSIndex
Cracking the Logic: Finding First Occurrence in Strings
More Relevant Posts
-
LeetCode Day 19 : Problem 167 (Two Sum II - Input Array Is Sorted) Just solved my LeetCode problem for today. It was "Two Sum II", sorted array, constant space, find two numbers that add up to a target. Sounds like a simple two-pointer problem, right? But here's what I actually learned: My first instinct was to write three separate while loops, each moving a different pointer in a different direction, thinking I was covering all the cases. I wasn't. The bugs were layered. The first loop only moved the right pointer. The second only moved the left. The third moved both but only toward the center. No single loop ever explored the full space of valid pairs. There was also a check I wrote: if (arr !== undefined) return arr. Looked like a guard. Did absolutely nothing. An empty array is never undefined in JavaScript. The condition was always true and I never noticed. The real fix wasn't patching the loops. It was understanding why the sorted order makes three loops completely unnecessary. The two-pointer solution: start left at index 0, right at the last index. If the sum is too small, move left forward. If the sum is too big, move right backward. One loop, every pair covered, O(n) time, O(1) space. The sorted order is the key insight. It guarantees you never need to backtrack, which is exactly why one clean loop beats three broken ones. The real lesson? When your instinct is to add more loops to cover more cases, stop. Ask whether the structure of the data already tells you which direction to move. Sometimes the constraint in the problem is the solution. #DSA #LeetCode #JavaScript #CodingJourney #Programming
To view or add a comment, sign in
-
-
Difference between fundamental data structures used in JavaScript: - If you need to access items by index, you should probably be using an Array. - If you need to access items by key, you should probably be using an Object. - If you need to access items by value, you should probably be using a Map. - If you need to store unique items and perform operations on that collection, you should probably be using a Set. #javascript #concepts #developer #coding #engineer
To view or add a comment, sign in
-
Ever notice how small food businesses still rely on printed menus that constantly go outdated? I’ve been building a QR-based digital menu system to solve that problem, allowing owners to update their menu in real-time without reprinting anything. Built using JavaScript for the frontend experience and a simple backend system to manage menu data, updates reflect instantly once changes are made. One key insight: simplicity beats complexity. Most businesses don’t need “advanced systems” they need something fast, easy, and practical that fits their daily workflow. Still refining how to make it even more intuitive for non-technical users. How do you usually balance simplicity and flexibility when building tools for real-world users? #Python #JavaScript #WebDevelopment #SoftwareEngineering #BuildInPublic
To view or add a comment, sign in
-
I compared the same logic in JS and Rust. The result? The "complex" Rust version wasn't just drastically faster — it was actually shorter and cleaner. If you’ve worked with JavaScript, Python, or Java, you’ve likely encountered the classic problem of counting how many times each character appears in a string. In JavaScript, the typical approach looks like this: if (map.has(ch)) { map.set(ch, map.get(ch) + 1); } else { map.set(ch, 1); } While this seems straightforward, there’s a hidden performance flaw: The Double Lookup & Value Copying. This one-liner requires extra work from the engine: 1️⃣ map.get(ch): Calculates the hash, traverses memory, finds the bucket, and extracts a copy of the number. 2️⃣ + 1: Creates a brand-new number primitive in memory. 3️⃣ map.set(ch, ...): Calculates the hash again, traverses memory again, finds the same bucket, and copies the new number back into it. Now, let's see how Rust handles the same logic: *counts.entry(ch).or_insert(0) += 1; This isn't just syntactic sugar; it utilizes Rust's Entry API, designed for maximum hardware efficiency. Here’s why it’s blazingly fast: - It calculates the hash exactly once. - It locates the memory bucket exactly once. - It returns a &mut (a direct mutable pointer/reference) right to that memory slot. The += operator modifies the primitive value in-place without copying it out or needing a .set() method to put it back. This results in code that reads like a high-level script but executes with the speed of a systems language. Zero-cost abstractions at their finest! #Rust #JavaScript #Programming #Performance #SoftwareEngineering #WebDev #RustLang
To view or add a comment, sign in
-
-
I recently implemented my first Linked List from scratch in JavaScript — no libraries, just raw pointer manipulation. This wasn’t just about writing code; it forced me to understand how data structures actually work under the hood. Here’s what I built: A custom Node structure with value and next pointers Core operations: addAtHead addAtTail addAtIndex deleteAtIndex get What made this interesting wasn’t the syntax — it was the edge cases and pointer management: Handling insertions at head vs tail Maintaining consistent length Avoiding broken references during insertion/deletion Fixing off-by-one errors in traversal Biggest takeaway: Linked Lists are simple in theory, but brutally unforgiving if your pointer logic is even slightly off. This exercise sharpened how I think about: Data structure integrity Boundary conditions Writing predictable, bug-resistant logic Still refining and testing edge cases — but this was a solid step forward. #JavaScript #DataStructures #LinkedList #Coding #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
-
Name vs. Slug: They aren't as interchangeable as we sometimes think! 💡 While contributing to the django-taggit project recently, I ran into an interesting edge case that reminded me of a common developer trap: treating a slug as an exact replica of a name. It’s an easy habit to fall into. We usually auto-generate a slug from a name ("My Post" ➡️ "my-post") and then start using them interchangeably in our database queries or business logic. But here is the catch: a slug is a normalized version of a name, not a 1:1 match. Think about tags like "C++" and "C#". Depending on your slugify function, both might normalize to just "c". If your system logic assumes they are identical and queries by slug when it actually needs the exact name, you are going to hit unexpected collisions and data bugs! 🛠️ How to manage them & make the right decision: 📌 Use Name for humans: UI rendering, reports, and anywhere readability is the priority. This is your exact source of truth for display. 📌 Use Slug for systems: URLs, API routing, and SEO-friendly lookups. It’s built for the web, not for exact data representation. The Golden Rule: Before writing a query, ask yourself: "Am I trying to route a web request, or am I trying to display the exact identity of an object?" Have you ever run into a weird bug because of a name/slug collision? Let's discuss in the comments! 👇 #Django #Python #BackendEngineering #OpenSource #SoftwareArchitecture #WebDevelopment
To view or add a comment, sign in
-
-
Most developers think encapsulation in JavaScript is just about “hiding variables.” It’s more than that. Encapsulation is about controlling access and protecting your logic. 💡 In simple terms: 👉 Keep data safe 👉 Expose only what’s necessary 🔹 1. Using Closures (Classic Way) function createCounter() { let count = 0; return { increment() { count++; console.log(count); }, getCount() { return count; } }; } const counter = createCounter(); counter.increment(); // 1 counter.increment(); // 2 console.log(counter.count); // ❌ undefined ✔ count is private ✔ Accessible only through methods 🔹 2. Using Classes + Private Fields (Modern JS) class BankAccount { #balance = 0; deposit(amount) { this.#balance += amount; } getBalance() { return this.#balance; } } const acc = new BankAccount(); acc.deposit(1000); console.log(acc.getBalance()); // 1000 console.log(acc.#balance); // ❌ Error ✔ True private fields ✔ Cleaner and structured ⚡ Why encapsulation matters: • Prevents accidental data changes • Makes code more secure • Improves maintainability • Creates clear boundaries in your system 🧠 The real shift: Don’t just write code that works. Write code that protects itself. What’s your go-to pattern for encapsulation in JavaScript—closures or private fields? 👇 #JavaScript #WebDevelopment #Programming #Frontend #Coding #SoftwareEngineering
To view or add a comment, sign in
-
Ever changed a variable in JavaScript only to realize you accidentally broke the original data too? 🤦♂️ That’s the classic Shallow vs. Deep Copy trap. Here is the "too long; didn't read" version: 1. Shallow Copy (The Surface Level) When you use the spread operator [...arr] or {...obj}, you’re only copying the top layer. The catch: If there are objects or arrays inside that object, they are still linked to the original. Use it for: Simple, flat data. 2. Deep Copy (The Full Clone) This creates a 100% independent copy of everything, no matter how deep the nesting goes. The easy way: const copy = structuredClone(original); The old way: JSON.parse(JSON.stringify(obj)); (Works, but it’s buggy with dates and functions). The Rule of Thumb: If your object has "layers" (objects inside objects), go with a Deep Copy. If it’s just a basic list or object, a Shallow Copy is faster and cleaner. Keep your data immutable and your hair un-pulled. ✌️ #Javascript #WebDev #Coding #ProgrammingTips
To view or add a comment, sign in
-
-
🚀 Day 9| JavaScript Today I explored JavaScript Foundations: Primitive Data Types & Operations — the building blocks of programming. 📌 Key concepts I learned: 🔹 Primitive Data Types • Number & BigInt → Used for numeric values and large integers • Boolean → Represents true or false (used in decision making) • Null & Undefined → Represent empty or uninitialized values 🔹 Operations in JavaScript • Arithmetic operations (+, -, *, /) • Logical operations (&&, ||, !) • Comparison operations (==, ===, >, <) ⚙️ I also understood how JavaScript performs computational actions to process and manipulate data effectively. 💡 Learning these fundamentals is important to build strong problem-solving skills and write efficient code. Step by step, I’m strengthening my JavaScript basics and programming logic. 💻✨ #JavaScript #WebDevelopment #FrontendDevelopment #CodingJourney #LearningInPublic #DeveloperJourney #ProgrammingBasics
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