🚀 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
Two Sum II: Sorted Array Solution
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
-
-
👉 Binary Tree Maximum Path Sum Using DFS --------------------------------------------------------------------------------------- 43 🔥 The challenge is to find the maximum sum of any path in a binary tree, where a path can start and end at any node (not necessarily passing through the root). ✔ Traverse the tree using Depth First Search (DFS) ✔ Ignore negative paths using Math.max(0, childSum) ✔ Maintain a global maximum path sum ✔ Return only one side (left or right) to the parent to maintain a valid path #DataStructures #Algorithms #BinaryTree #JavaScript #TypeScript #DSA #CodingPractice #ProblemSolving #SoftwareEngineering #FrontendDeveloper #LearningInPublic #100DaysOfCode
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
-
-
✅ Solved LeetCode: Symmetric Tree (101) — Recursive Mirror Approach Implemented a clean recursive DFS solution in JavaScript using a mirror comparison strategy. Approach: - Create a helper function isMirror(left, right) to compare two nodes. - If both nodes are null, return true. - If only one is null, return false. - Otherwise: - Check if left.val === right.val. - Recursively compare: - left.left with right.right - left.right with right.left - Return the combined result of all three conditions. This approach leverages symmetry by comparing opposite children, keeping the logic elegant and easy to reason about. Time Complexity: O(n) — each node is visited once Space Complexity: O(h) — recursion stack space (where h is tree height) A classic divide-and-conquer tree problem solved with clean mirror recursion!
To view or add a comment, sign in
-
-
✅ Solved LeetCode: Invert Binary Tree (226) — Recursive DFS Approach Implemented a clean recursive solution in JavaScript using a simple swap-and-recurse strategy. Approach: - If the node is null, return it immediately. - Swap the left and right children: - Store root.left in a temporary variable. - Assign root.right to root.left. - Assign the temporary value to root.right. - Recursively call the function on: - root.left - root.right - Return the root after inversion. This approach flips the tree at every node and naturally propagates the inversion down to all subtrees using recursion. Time Complexity: O(n) — each node is visited once Space Complexity: O(h) — recursion stack space (where h is tree height) A classic tree problem solved with a simple and elegant recursive swap!
To view or add a comment, sign in
-
-
Day 21: The Final Logic – Closures & The Magic of Property Access 🔒✨ Today marks the grand finale of the JavaScript deep-dive. We didn't just look at the code; we looked at the Memory and the Engine logic that governs how variables live and die. 🧠 The "Crack-It Kit" Checklist: Day 21 📑 🔹 The "Stack Overflow" Trap: Understanding why a setter that calls itself triggers a recursion loop, and the "Underscore Logic" (_variable) used to fix it. 🛡️ 🔹 Getters & Setters: Moving beyond simple data storage to "Smart Properties." Whether using Class syntax or Object.defineProperty, it's about intercepting and validating every piece of data. ⚙️ 🔹 The .length Mystery: Breaking down how arr.length actually works. It’s not just a counter—it’s an exotic property managed by the engine with a setter that can physically truncate memory. 🧪 🔹 Lexical Scoping: Mastering the "Hierarchy of Access." Understanding that where you write your code determines what your functions can see. 🏛️ 🔹 Closures (The Memory Lock): The ultimate interview topic. Learning how JS "locks" parent variables in memory to keep them alive for inner functions, even after the parent has finished executing. 🔒 The JavaScript foundation is now 100% complete. From the TCP 3-way handshake to the internal mechanics of Closures, the logic is locked in. 🏗️ #JavaScript #WebDevelopment #CrackItKit #Closures #WebEngineering #CodingJourney #SoftwareArchitecture #TechInterviews #MERNStack #WanderlustProject
To view or add a comment, sign in
-
-
𝗧𝗶𝗽𝘀 𝗳𝗼𝗿 𝗪𝗼𝗿𝗸𝗶𝗻𝗴 𝗪𝗶𝘁𝗵 𝗧𝘆𝗽𝗲𝗱 𝗔𝗿𝗿𝗮𝘆𝘀 𝗮𝗻𝗱 𝗔𝗿𝗿𝗮𝘆𝗕𝘂𝗳𝗳𝗲𝗿 You need to work with binary data in JavaScript. Typed Arrays and ArrayBuffers can help. Here's what you need to know: - Typed Arrays provide a way to read and write binary data - ArrayBuffers store binary data - You can create different types of Typed Arrays, such as Int8Array, Uint8Array, and Float32Array To get started, you create an ArrayBuffer and a Typed Array view: ``` plain text is not allowed, so here is a simple description Create a new ArrayBuffer with a size in bytes Create a Typed Array view over the ArrayBuffer ``` You can then fill the Typed Array with values and perform operations on it. Some key things to keep in mind: - Modifying a value in one view affects the memory representation viewed by other views - You can use Typed Arrays to send binary data over WebSockets - Typed Arrays are useful for audio and video processing, game development, and WebGL When working with Typed Arrays, consider the following tips: - Ensure byte alignment for better performance - Reuse ArrayBuffers to minimize garbage collection overhead - Be aware of byte order issues For more information, you can check out the following resources: Source: https://lnkd.in/g8PtCkbH
To view or add a comment, sign in
-
From Sorted Data to Balanced Trees: Divide, Conquer, Balance 🌳 Solved LeetCode 108 - Convert Sorted Array to Binary Search Tree today. The solution clicked by treating the array like a search space: -Pick the middle element as the root -Recursively build the left half and right half -Stop when the range becomes invalid This guarantees a height-balanced BST without extra work. Key takeaway: Balanced trees are a natural outcome of divide-and-conquer. Choosing the midpoint at every step keeps depth under control. Strengthening recursive thinking and tree intuition. #LeetCode #DSA #BinarySearchTree #Recursion #DivideAndConquer #JavaScript #ProblemSolving #LearnInPublic
To view or add a comment, sign in
-
📌 #60 DailyLeetCodeDose Today's problem: 73. Set Matrix Zeroes – 🟡 Medium When a problem states that you must modify the data in-place, LeetCode has taught me a useful pattern: to boost performance and avoid extra memory, you can reuse the same mutable data structure to encode all the information you need. In this problem, instead of using additional arrays or hash sets, I use the first row and the first column of the matrix as markers – while scanning the matrix, whenever I encounter a zero, I mark its entire row and column by setting the corresponding cell in the first row or first column to zero. Since the first row and first column are also part of the original data, I store their initial state in two boolean flags. This allows me to correctly decide at the end whether they themselves should be zeroed out. As a result, the solution runs in O(m × n) time and uses O(1) extra space, fully satisfying the in-place requirement. https://lnkd.in/eRxwBy4g #DailyLeetCodeDose #LeetCode #JavaScript #Algorithms #ProblemSolving #Coding
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
-
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