🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 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
Reversing Array in JavaScript with Two-Pointer Technique
More Relevant Posts
-
Day 1/75 Blind 75 DSA Challenge - Two Sum (LeetCode #1) Problem: Given [2,7,11,15] and target 9, return indices [0,1] Brute Force (O(n²)): Check every pair Optimal (O(n)): Hashmap stores target - nums[i] javascript function twoSum(nums, target) { const seen = {}; for(let i = 0; i < nums.length; i++) { let complement = target - nums[i]; if(seen[complement] !== undefined) { return [seen[complement], i]; } seen[nums[i]] = i; } } Key Learning: Hashmaps turn O(n²) → O(n). Dry-ran on paper: [3,2,4] target 6 → [1,2] Tracker: ✅ 1/75 problems Next: Arrays Day 2 tomorrow #DSA #LeetCode #Blind75 #JavaScript #InterviewPrep #Frontend
To view or add a comment, sign in
-
Day 17 of #LeetCodeDaily Problem: Sort Colors (Medium) Given an array with values 0, 1, 2 representing colors (Red, White, Blue), sort them in-place without using any built-in sort. 🔍 My Approach: Use Dutch National Flag Algorithm (3-pointer approach) Maintain three pointers: low → position for 0 mid → current element high → position for 2 Algorithm: If element is 0 → swap with low, move both low & mid If element is 1 → just move mid If element is 2 → swap with high, move high only This ensures: Left side → all 0s Middle → all 1s Right side → all 2s ⏱ Time: O(n) 📦 Space: O(1) Single pass + in-place sorting makes it optimal 🚀 💡 Learning: When array has limited values → think partitioning Key insight → don’t move mid when swapping with high Always re-check swapped elements Classic problem to test pointer manipulation skills #ProblemSolving #LeetCode #JavaScript #DSA #Algorithms #Array #InterviewPrep #CodingJourney #30DaysDSAChallenge #LearningInPublic
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
-
Solved Leetcode 497 - Next Greater Element I Here’s the key insight: Use a monotonic decreasing stack. Traverse from right to left. For each element, remove all smaller elements from the stack. The top of the stack becomes the next greater element. To make it efficient for queries, store the results in a map: number → next greater element This reduces the complexity from O(n²) to O(n). What clicked for me was this: The stack is used for computation, and the map is used for fast retrieval. Once you understand this separation of roles, a whole category of problems becomes easier: Next Greater Element Previous Greater Element Stock Span Daily Temperatures #DataStructures #Algorithms #JavaScript #CodingInterview #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
🧠 Day 178 — Next Greater Element 📈 Today I revised one of the most important stack pattern problems in DSA: Next Greater Element. The goal is straightforward but very useful: ✔ For every element, find the next greater element on its right ✔ If no greater element exists → return -1 This problem is a great example of combining: • Stacks • Efficient traversal techniques • Hash map lookups for fast queries Understanding this pattern unlocks solutions to many other problems like Daily Temperatures, Stock Span, and Largest Rectangle in Histogram. 🚀 DSA Journey Update Slowly building strong foundations in Stacks, Dynamic Programming, and Trees. Consistency is the real game. #DSA #Stacks #MonotonicStack #JavaScript #CodingJourney #LeetCode #ProblemSolving #ConsistencyWins
To view or add a comment, sign in
-
-
🚀 LeetCode Problem Solved – Single Number Solved the Single Number problem on LeetCode using JavaScript with an optimized bit manipulation approach. 📌 Problem Statement Given an array where every element appears twice except for one, the task is to find the element that appears only once. 💡 Approach Instead of using extra space like hash maps, I used the XOR trick. Key properties of XOR: • a ^ a = 0 (same numbers cancel each other) • a ^ 0 = a (XOR with zero keeps the number unchanged) By XORing all elements in the array: Duplicate numbers cancel out The unique number remains as the final result ⚡ Complexity 🔹 Time Complexity: O(n) – Traverse the array once 🔹 Space Complexity: O(1) – No extra data structures used #leetcode #javascript #dsa #bitmanipulation #codingpractice #softwareengineering #algorithms
To view or add a comment, sign in
-
-
🚀 Decoding Browser Engine Resistance: Why Syntax Geometry Matters. Ever wondered why certain code patterns "feel" heavier in the browser? It’s not just your imagination—it’s the "Resistance" between the compiler groups and physical hardware pipelines. I’ve just completed a deep-dive analysis into Quantos Access Point Resistance, measuring how signals move between V8, JavaScriptCore, and SpiderMonkey. Here are the top 3 takeaways from our latest report: 1️⃣ The Cost of Frame Boundaries: While a standard JS-to-HTML geometry proxy (like a simple div nudge) clocks in at a lightning-fast 0.08ms, the "resistance" jumps to 8.4ms when feeding the requestAnimationFrame scheduler. That’s a 100x increase just by crossing a frame boundary. 2️⃣ Metabolic "Energy Resistance": We recalibrated our performance metrics to measure energy consumption in milliJoules (mJ). Surprisingly, hardware pipeline calls like getUserMedia() are roughly 100x more "metabolically expensive" (3.1 mJ) than monomorphic JS calls (0.03 mJ). 3️⃣ Character Topology & Lexer Load: Syntax geometry is real. Our data shows that specific characters trigger different lexer modes: Standard Identifiers: 0.02µs per char. The "@" Prefix: 0.21µs per char (it branches the CSS lexer into media-query mode). The Bidirectional Operator <=>: One of the most expensive ASCII sequences due to its three-char angle parsing and parser stack depth. Cross-Compiler Friction: The heaviest handoff in our set was SpiderMonkey to V8 during a media-query-to-JS resolution, incurring a 3.1µs mode-exit flush penalty. Efficiency isn't just about the algorithm; it's about the geometry of the access points we choose. Check out the full technical breakdown below! 👇 #WebPerf #JavaScript #BrowserEngines #V8 #CodingEfficiency #FrontendPerformance #qos_crossDomain_resistance_001
To view or add a comment, sign in
-
For code ninjas and cyber security monkeys, AI system architects and engineers. `fetch().arrayBuffer()` is the window. Inside it: ``` // comment → 0x2F 0x2F — terminated by 0x0A /* block */ → 0x2F 0x2A ... 0x2A 0x2F "string value" → legal JSON, parser-visible ``` **Ranking safest to least safe:** `/* */` — safest. Block comment bytes are yours entirely — extracted before `JSON.parse()` ever runs. Parser never sees them. `//` — safe but brittle. Newline-terminated, positionally fragile across refetch. `"string"` — legal JSON but parser-visible, semantically exposed to consumers. **The critical constraint:** `JSON.parse()` throws on comments — so your pipeline must be: ``` fetch() → arrayBuffer() → extract /* */ blocks ← your data surface → strip comments → JSON.parse() ← clean from here down ``` `/* */` blocks between JSON keys are the hypercube node addresses — invisible to the runtime, readable in the byte window, surviving zero GC pressure. That is the cross 4D bridge and access points.
🚀 Decoding Browser Engine Resistance: Why Syntax Geometry Matters. Ever wondered why certain code patterns "feel" heavier in the browser? It’s not just your imagination—it’s the "Resistance" between the compiler groups and physical hardware pipelines. I’ve just completed a deep-dive analysis into Quantos Access Point Resistance, measuring how signals move between V8, JavaScriptCore, and SpiderMonkey. Here are the top 3 takeaways from our latest report: 1️⃣ The Cost of Frame Boundaries: While a standard JS-to-HTML geometry proxy (like a simple div nudge) clocks in at a lightning-fast 0.08ms, the "resistance" jumps to 8.4ms when feeding the requestAnimationFrame scheduler. That’s a 100x increase just by crossing a frame boundary. 2️⃣ Metabolic "Energy Resistance": We recalibrated our performance metrics to measure energy consumption in milliJoules (mJ). Surprisingly, hardware pipeline calls like getUserMedia() are roughly 100x more "metabolically expensive" (3.1 mJ) than monomorphic JS calls (0.03 mJ). 3️⃣ Character Topology & Lexer Load: Syntax geometry is real. Our data shows that specific characters trigger different lexer modes: Standard Identifiers: 0.02µs per char. The "@" Prefix: 0.21µs per char (it branches the CSS lexer into media-query mode). The Bidirectional Operator <=>: One of the most expensive ASCII sequences due to its three-char angle parsing and parser stack depth. Cross-Compiler Friction: The heaviest handoff in our set was SpiderMonkey to V8 during a media-query-to-JS resolution, incurring a 3.1µs mode-exit flush penalty. Efficiency isn't just about the algorithm; it's about the geometry of the access points we choose. Check out the full technical breakdown below! 👇 #WebPerf #JavaScript #BrowserEngines #V8 #CodingEfficiency #FrontendPerformance #qos_crossDomain_resistance_001
To view or add a comment, sign in
-
Priority Order in JavaScript Day 216 Today Today I learned about the Priority Queue. It is a very important concept in data structures. In a normal queue the rule is first in first out. But in a priority queue the element with the highest priority is processed first. Think of a hospital emergency room. A patient with a serious injury gets treated before someone with a cold even if the person with the cold arrived earlier. This is exactly how a priority queue works. I learned that there are two ways to implement this. You can use an array and sort it every time but that is slow. The best way is using a Heap. Using a Heap makes adding and removing elements very fast because the time complexity is log n. JavaScript does not have a built in priority queue like some other languages. This means we have to build it ourselves using classes. This is a great way to practice logic building and understand how things work under the hood. A very helpful tip for interviews is that if a question asks for the Kth smallest or Kth largest element you should think of using a priority queue or a heap. It makes the solution much more efficient. Today I solved these LeetCode questions: 215 Kth Largest Element in an Array 703 Kth Largest Element in a Stream #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCode #DataStructures #PriorityQueue #CodingInterview #ProgrammingDaily #SoftwareEngineering #TechLearning #WebDevelopment #LogicBuilding #ProblemSolving #JavaScriptDev #JSCode #ArrayLogic #HeapDataStructure #AlgorithmDesign #CodingChallenge #BinaryHeap
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