Day 15 of my 100-Day LeetCode Challenge: Streamlining Data Streams! 🌊 Today I tackled LeetCode #2149: Rearrange Array Elements by Sign. The problem asks you to take an array of positive and negative numbers and interleave them perfectly (positive, negative, positive...) while strictly maintaining their original relative order. The Engineering Solution: The Two-Pointer Placement Technique. While you could split the data into two separate lists and merge them, that requires multiple passes. To do this efficiently, I used a single-pass approach: • Initialize an exact-size result array. • Use two separate index trackers: 'positive' starting at 0, and 'negative' starting at 1. • Iterate through the raw data once. If a number is positive, place it at positive and jump the pointer forward by 2. If negative, place it at negative and jump by 2. The Complexity Win: ⏱️ Time: O(N) - The raw data is evaluated in exactly one pass. 💾 Space: O(N) - We allocate exactly what is needed for the restructured output. Often, engineers get hyper-focused on trying to achieve O(1) space. But trying to solve this specific problem in-place while preserving relative order requires heavy element shifting, resulting in a massive O(N^2) time penalty. Understanding when to trade space for speed is the core of system design! #100DaysOfCode #Java #LeetCode #DataStructures #Algorithms #SeniorEngineer #BackendDevelopment #SoftwareEngineering
Rearrange Array Elements by Sign in O(N) Time
More Relevant Posts
-
⚡ Optimized Two Sum from O(n²) to O(n) Using Hash Mapping While practicing algorithmic problem-solving on LeetCode, I revisited the classic Two Sum problem — but focused on optimization, not just solving. Initial approach: • Brute force with nested loops • Time complexity: O(n²) Then I restructured the solution using a hash map (dictionary): Optimized approach: • Store visited numbers with their indices • Compute complement = target - current value • Check lookup in constant time Result: Reduced time complexity to O(n) with O(n) space. What this reinforced for me: This problem is not about addition. It’s about: • Efficient data structures • Time-space trade-offs • Thinking in terms of system optimization As I continue building my foundation in software engineering, I’m focusing on: • Writing scalable logic • Optimizing performance early • Understanding how small decisions impact system efficiency Because in real-world systems, efficiency is not optional — it’s expected. #SoftwareEngineering #DataStructures #Algorithms #LeetCode #TechStudent #ProblemSolving #WomenInTech #LearningInPublic
To view or add a comment, sign in
-
#100DaysOfCode | Day 7 of my LeetCode challenge : Arrays to Linked Lists! Problem - LeetCode #21 (Merge Two Sorted Lists). While this problem can be solved recursively, I chose the Two-Pointer Iterative Approach. Here is why: Production Safety: Recursion is elegant, but on massive datasets, it risks a StackOverflowError. Iteration is much safer for enterprise-level data. The "Dummy Node" Pattern: By initializing a sentinel/dummy node at the start, I eliminated the need to write clunky if-else checks to determine the new head. It keeps the code clean and implicitly handles edge cases like empty lists. The Complexity : ⏱️ Time Complexity: O(N + M) (Where N and M are the lengths of the two lists). 💾 Space Complexity: O(1) (No extra memory used, just re-pointing existing nodes). Getting this to run perfectly in my local IDE tonight was a great feeling. #100DaysOfCode #Java #LeetCode #SoftwareEngineering #SeniorEngineer #BankingTech #DataStructures #Algorithms
To view or add a comment, sign in
-
-
Day 100/100 – #100DaysOfLeetCode 🎉 🧩 Problem: LeetCode 94 – Binary Tree Inorder Traversal(Easy) 🧠 Approach: Use recursion to traverse the tree in Left → Root → Right order. Store the values during traversal to get the inorder sequence. 💻 Solution: # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: result = [] def inorder(node): if not node: return inorder(node.left) result.append(node.val) inorder(node.right) inorder(root) return result ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Recursion provides a clean and intuitive way to perform tree traversals following defined orders. 100 days. 100 problems. Countless learnings. Grateful for the consistency, the challenges, and the growth throughout this journey. This is just the beginning—more to come! 💪 #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 36 of #100DaysOfCode Today I solved LeetCode 155 – Min Stack 💻 🔍 Problem Summary: Design a stack that supports push, pop, top, and retrieving the minimum element — all in constant time O(1). 🧠 Key Learning: This problem teaches how to optimize operations using an auxiliary stack to track the minimum element efficiently. 💡 Approach: Use two stacks: Main stack → stores all elements Min stack → keeps track of minimum values While pushing: Push element to main stack Push to min stack only if it’s smaller or equal While popping: Remove from min stack if it matches top of main stack 📊 Complexity: Time: O(1) for all operations Space: O(n) 🔥 Takeaway: Using extra space smartly can drastically improve performance. This is a great example of designing efficient data structures. #LeetCode #Java #Stack #DataStructures #Algorithms #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Building My DSA Foundation on LeetCode I’ve started focusing seriously on Data Structures & Algorithms and recently completed 30 problems on LeetCode. Instead of just solving problems, I focused on understanding the why behind each approach. 🔹 What I worked on: Arrays & Strings Two Pointer Technique Basic Sorting & Searching 🔹 Key challenges: Moving from brute force to optimized solutions Handling edge cases effectively Improving time & space complexity 🔹 What improved: Problem-solving approach Ability to recognize patterns Writing cleaner and more efficient code 📌 I’ve documented my solutions with explanations here: 👉 https://lnkd.in/dzvjyViC This is just the starting point. Next goal: 50+ problems with a focus on Medium-level questions and deeper pattern recognition. #DSA #LeetCode #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🥷 Day 343 of My 365 LeetCode Challenge is done! 💥 Kicked off strong, solved my problem, and the coding vibe is awesome! 🧠 🚀 Solved: Closest Equal Element Queries Today’s problem looked simple at first, but it had a clever twist involving circular arrays and efficient searching. 🔍 Problem Overview: You’re given an array and multiple queries. For each query index, the goal is to find the minimum distance to another index having the same value, considering the array as circular. If no such index exists, return -1. 💡 Key Observation: Brute force would be too slow ❌ Instead, the idea is to: Store positions of each value 📍 Use binary search to quickly find the nearest occurrence Handle the circular nature by checking both directions 🧠 Approach: Preprocess the array using a map (value → list of indices) For each query: Get the list of indices for that value Use binary search to locate the current index Check neighbors (left & right) to compute minimum distance Don’t forget to account for circular wrapping 🔄 ⚡ Why this works: Preprocessing reduces repeated work, and binary search ensures efficient lookups, making the solution scalable even for large inputs. 🔥 Takeaway: Sometimes optimization comes from organizing data smartly rather than complex logic. #LeetCode #DSA #BinarySearch #DataStructures #Coding #ProblemSolving #Cpp #TechJourney
To view or add a comment, sign in
-
-
🚀 Solved LeetCode 2515 – Shortest Distance to Target String in a Circular Array Today I tackled an interesting problem that highlights the importance of handling circular data structures efficiently. 🔍 Problem Insight: Given a circular array of words, a target string, and a starting index, the goal is to find the minimum number of steps required to reach the target by moving either left or right. 💡 Key Learnings: Circular arrays require thinking beyond linear traversal Always consider both directions (forward & backward) Optimizing distance using min(distance, n - distance) is the key trick Simple logic + correct observation = optimal solution ⚙️ Approach Used: Traverse the array to find all occurrences of the target Calculate distance from the starting index Take the minimum considering circular movement 📈 Complexity: Efficient O(n) solution with constant space 🔥 Takeaway: This problem reinforced how small tweaks (like circular behavior) can change the entire approach. A great example of combining logic + observation for clean and optimal solutions. #LeetCode #Algorithms #ProblemSolving #CodingJourney #Java #DataStructures #CompetitiveProgramming
To view or add a comment, sign in
-
-
🚀 Day 82 of #100DaysOfCode Today, I solved LeetCode 41 – First Missing Positive, a classic hard problem that tests in-place array manipulation and optimization. 💡 Problem Overview: Given an unsorted array, the goal is to find the smallest missing positive integer in O(n) time and O(1) space. 🧠 Approach: ✔️ Used index-based placement (cyclic sort idea) ✔️ Placed each number x at index x - 1 whenever possible ✔️ Ignored negative numbers and values out of range ✔️ Finally, scanned the array to find the first index where the value is incorrect This ensures optimal time and space complexity without using extra data structures. ⚡ Key Takeaways: In-place manipulation can eliminate the need for extra space Index mapping is a powerful trick for array problems Hard problems often rely on simple but clever observations 📊 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(1) Solving challenging problems and strengthening core fundamentals 🚀 #LeetCode #100DaysOfCode #DSA #Arrays #ProblemSolving #CodingJourney #SoftwareDevelopment #InterviewPrep #HardProblems
To view or add a comment, sign in
-
-
🚀 Cracked one of the toughest 🔥 problems on LeetCode — Median of Two Sorted Arrays." 💡 Problem: Find the median of two sorted arrays in O(log (m+n)) time. 🧠 Key Insight: Instead of merging arrays (O(n)), I used Binary Search + Partitioning to split both arrays such that: ✔ Left half contains equal elements ✔ All left elements ≤ right elements ⚙️ Approach Highlights: ✅ Binary search on smaller array ✅ Handle edge cases using ±∞ ✅ Partition validation logic ✅ Works for both even & odd lengths 🔥 Journey: After 3 attempts, finally nailed this problem 💪 Each attempt taught something new — edge cases, partition logic, and precision. ⚡ Result: ✔ Accepted ✅ ⚡ Runtime: 0 ms (Beats 100%) 💻 Clean & optimal solution 🎯 What I learned: Thinking beyond brute force is key Binary search isn’t just for searching Edge cases define correctness 💬 Challenge for you: Can you solve this without merging arrays? 😉 #LeetCode #DataStructures #Algorithms #BinarySearch #CodingInterview #SoftwareEngineer #ProblemSolving #TechInterview #100DaysOfCode
To view or add a comment, sign in
-
-
🎯Day 1 of #150DaysOfCode 🚀 👨💻 Platform: #LeetCode 🧠 Today’s Problem: ⚡ 1. Two Sum Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1]
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