🔥 Day 33/100 of #100DaysOfCode - Alternating Positive & Negative! Today's Problem: Rearrange Array Elements by Sign Task: Given an array with equal number of positive and negative integers, rearrange them in alternating positive/negative order (starting with positive). Solution: Used a two-pointer approach with separate indices for positive and negative positions! Created a temp array and placed positives at even indices (0, 2, 4...) and negatives at odd indices (1, 3, 5...). Key Insights: Since the array has equal positives and negatives, we can pre-determine positions O(n) time complexity with O(n) space for the temp array Clean and intuitive - no complex swapping needed Smart Pointer Management: Positive pointer moves by +2 each time Negative pointer moves by +2 each time Single pass through the original array Elegant solution for maintaining relative order while achieving the required alternation! ⚡ #100DaysOfCode #LeetCode #Java #Algorithms #Arrays #TwoPointers #CodingInterview
Rearranging Array Elements by Sign with Two Pointers
More Relevant Posts
-
🌟 Day 41 of #100DaysOfCode 🌟 🔍 Exploring String Reversal — Simplicity in Motion 🔹 What I Solved Today’s challenge focused on one of the most fundamental yet essential problems — reversing a string in-place. No shortcuts, no helper strings — just clean pointer manipulation and precision. 🧩 Problem: Reverse a String (In-Place) 💡 Problem Statement Given an array of characters s, reverse it in-place. You must modify the input array directly, without using any extra memory. 💡 Example 1: Input: ["h","e","l","l","o"] → Output: ["o","l","l","e","h"] 💡 Example 2: Input: ["H","a","n","n","a","h"] → Output: ["h","a","n","n","a","H"] 🧠 Concepts Used Two-Pointer Technique 🔁 In-Place Array Manipulation Constant Space Optimization ⚙️ Approach 1️⃣ Use two pointers — one at the start (left) and one at the end (right). 2️⃣ Swap characters at both ends. 3️⃣ Move both pointers toward the center until they meet. 🚀 What I Learned ✨ Two-pointer techniques make complex tasks effortless. ✨ In-place operations strengthen logic and memory efficiency. ✨ Simplicity is often the most elegant form of problem-solving. 💬 Reflection Today’s challenge was a reminder that mastery begins with fundamentals. Sometimes, the most impactful solutions are built on clear, minimal logic — where simplicity meets efficiency. #100DaysOfCode #Day41 #ReverseString #TwoPointer #DSA #Java #LeetCode #Algorithm #ProblemSolving #CleanCode #ProgrammingJourney #MindfulCoding #CodeOptimization #StringManipulation
To view or add a comment, sign in
-
-
Problem: "73. Set Matrix Zeroes" The core of this problem is simple: if a cell is zero, its entire row and column must become zero. But the execution is tricky—you can't modify the matrix while you're still scanning for original zeros! My solution uses a clean, two-pass strategy with auxiliary storage: Pass 1: Use two HashSets to record the indices of rows and columns that contain an initial zero. Pass 2: Iterate again and set any cell to zero if its row or column is present in the HashSets. This approach is highly readable and ensures optimal O(M . N) time complexity. While this solution uses O(M+N) extra space, it's a fantastic baseline. The next step is tackling the O(1) space constraint by cleverly using the matrix's first row and column as the marker sets. That's the real optimization puzzle! #Algorithms #DataStructures #LeetCode #CodingChallenge #Java #SoftwareEngineering #100daysofcode
To view or add a comment, sign in
-
-
#Day_34 Today’s problem was a satisfying one to solve — “Single Element in a Sorted Array” 🔍 Given a sorted array where every element appears twice except for one unique element, the task is to identify that single element. At first, it seems like a simple linear scan could do the job — and yes, it can. But I focused on building a clean and logical O(n) approach before thinking about optimization 🧠 Approach We observe that: Every element appears in pairs, and because the array is sorted, duplicates are adjacent. The unique element is the only one that doesn’t match its left or right neighbor. We can handle three cases: First element: If it’s not equal to the next one → it’s the single element. Last element: If it’s not equal to the previous one → it’s the single element. Middle elements: If an element is different from both its previous and next → that’s our answer. This way, we can detect the single element in just one pass through the array ⏱ Complexity Time: O(n) — We traverse the array once. Space: O(1) — No extra memory used. 💬 Reflection This problem is a good reminder that not every efficient solution has to start complex. Sometimes, the cleanest brute-force version gives a perfect foundation for further optimization — in this case, even leading to an O(log n) binary search variant. Each problem in this challenge pushes me to think deeper about patterns, structure, and clarity in problem-solving. #CodingJourney #LeetCode #ProblemSolving #100DaysOfCode #Java #LearnByDoing #DSA
To view or add a comment, sign in
-
-
🚀Day 5️⃣9️⃣of #100DaysOfCode Solved LeetCode 3354 – Make Array Elements Equal to Zero 🧮 ⚡ Runtime: 1 ms (Beats 83.13%) 📊 Memory: 42.10 MB (Beats 69.28%) 🔍 Concept: This problem revolves around array traversal, directional logic, and state transitions. You start from an index where the element is 0 and move left or right while updating values and reversing direction — until all elements reach zero. 🧩 Approach Summary: Identify the initial index containing 0. Traverse left and right, updating values and counting valid selections. Keep it simple, linear, and effective. Some problems test patience as much as skill — but every solved logic strengthens the problem-solving mindset. #LeetCode #Java #ProblemSolving #100DaysOfCode #CodingJourney #SoftwareEngineer #Developer #AlgorithmDesign #Consistency #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Day 87/100 of #100DaysOfCode 💡 Problem: 3321. Find X-Sum of All K-Long Subarrays II (Hard) 🔗 Platform: LeetCode Today’s challenge was all about optimizing sliding window logic with frequency-based ordering! The task — find the “x-sum” of every k-sized subarray, keeping only the top x most frequent elements (and if tied, prefer larger values). 🧠 Key Learnings: How to maintain frequency counts efficiently in a sliding window. Managing top-x elements dynamically using TreeSet and custom comparators. Overcoming TLE issues by switching from naive sorting (O(n*k)) to a balanced TreeSet approach (O(n log n)). ⚙️ Concepts Used: → Sliding Window → Frequency Map (HashMap) → Ordered Sets (TreeSet) → Custom Comparator Logic 🔥 This one really tested both logic & optimization — but once it clicked, it felt amazing! #LeetCode #100DaysOfCode #Java #CodingChallenge #ProblemSolving #DSA #SlidingWindow #Optimization
To view or add a comment, sign in
-
-
🚀 Day 43 of #100DaysOfLeetCode Today's problem: LeetCode #160 – Intersection of Two Linked Lists 💡 Concept: Find the node where two singly linked lists intersect. Used the Two Pointer Approach — a smart and efficient way to solve this without using extra memory. 🧠 Logic: Move both pointers through the lists. When one pointer reaches the end, switch it to the other list’s head. They’ll either meet at the intersection node or end up as null together. ✅ Complexity: Time – O(n + m) Space – O(1) 💬 Takeaway: Sometimes, the best solutions come from balancing the path — literally! Understanding how pointers sync up teaches a lot about memory references and linked list behavior. #LeetCode #CodingChallenge #Java #DataStructures #TwoPointerTechnique #ProblemSolving #LinkedLists
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 81 Linked List Cycle Problem Given the head of a linked list, determine whether the list contains a cycle meaning a node’s next pointer refers back to a previous node. My Approach Used Floyd’s Cycle Detection Algorithm (Tortoise & Hare Method): Initialized two pointers slow and fast. Moved slow one step and fast two steps in each iteration. If they ever meet → cycle detected. If fast or fast.next becomes null → no cycle exists. Complexity Time: O(n) Space: O(1) Even in problems involving dynamic structures like linked lists, a simple pointer-based approach can lead to an elegant and optimal solution. #100DaysOfCode #LeetCode #Java #ProblemSolving #DataStructures #LinkedList #TortoiseAndHare #takeUforward #CodeNewbie #CodingJourney
To view or add a comment, sign in
-
-
Day 18 — Frequency Boost Mode ON! Problem: 3346. Maximum Frequency of an Element After Performing Operations I Difficulty: Medium Today’s problem was all about maximizing the frequency of an element in an array — but with a twist 🔄. You can tweak elements up or down by up to k, but only for a limited number of operations. The challenge? Figuring out how to best use those operations to make one number appear the most times possible. It’s a mix of prefix sums, counting frequency, and a bit of greedy optimization — perfect for sharpening problem-solving intuition. Takeaway: Sometimes, optimization isn’t about making everything perfect — it’s about finding where a few smart changes make the biggest difference. #Day18 #LeetCode #Java #ProblemSolving #100DaysOfCode #CodingChallenge #LeetCodeMedium #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🔹 Day 50: Maximum Average Subarray I (LeetCode #643) 📌 Problem Statement: Given an integer array nums and an integer k, find the contiguous subarray of length k that has the maximum average value and return this value. ✅ My Approach: I used the sliding window technique to efficiently calculate the sum of subarrays of length k. First, I computed the sum of the first k elements. Then, as the window slid forward, I subtracted the element going out and added the new element entering the window. I continuously updated the maximum sum encountered and finally returned the average by dividing it by k. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ⚡ Submission Stats: Runtime: 2 ms (Beats 99.90%) Memory: 56.27 MB (Beats 66.43%) 💡 Reflection: This problem highlighted how the sliding window technique can drastically improve performance over recalculating sums for each subarray, making the approach both elegant and efficient. 🚀 #LeetCode #Java #SlidingWindow #Optimization #100DaysOfCode #Day50
To view or add a comment, sign in
-
-
💻 Enhancing Problem-Solving Skills with LeetCode (Java) Recently solved a couple of fundamental algorithmic problems that helped strengthen my understanding of two-pointer techniques, array manipulation, and writing efficient solutions. 🔹 Container With Most Water Implemented an optimised two-pointer approach to find the maximum water area between vertical lines. Instead of checking every pair (which would be O(n²)), the solution smartly moves the pointer at the shorter height inward to explore potentially larger areas. Approach: Two Pointers, Greedy Time Complexity: O(n) Space Complexity: O(1) 🔹 3Sum Solved the classic triplet-finding challenge by sorting the array and using two pointers to efficiently search for combinations that sum to zero. Also handled duplicates to avoid repeated triplets. Approach: Sorting + Two Pointers Time Complexity: O(n²) Space Complexity: O(1) (excluding output list) These problems helped sharpen my understanding of pointer movement, edge-case management, and designing clean, efficient solutions. #LeetCode #Java #Algorithms #DSA #Coding #ProblemSolving #SoftwareEngineering #LearningJourney
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