🚀 Day 13/100 – LeetCode Journey Today’s problem: Squares of a Sorted Array 🔥 Approach 1 (Brute Force + Sorting) 👉 Workflow: Square every element Store in new array Sort the array ⚡ Time Complexity: O(n log n) (because of sorting) 💡 Approach 2 (Two Pointer – Optimized) 👉 Workflow: Use two pointers (left, right) Compare squares of both ends Place larger square at the end of result array Move pointers accordingly ⚡ Time Complexity: O(n) 🧠 Why Optimized is Better? Original array is already sorted But after squaring, order may break (because negatives become positive) 👉 Example: [-4, -1, 0, 3, 10] Squares → [16, 1, 0, 9, 100] ❌ not sorted Sorting again → O(n log n) Two-pointer uses property of sorted array → O(n) 👉 We compare largest absolute values from ends instead of sorting 🧠 Key Insight: Largest square always comes from either: leftmost (large negative) or rightmost (large positive) 🧠 Space Complexity: O(n) (result array) Learning optimization step by step 🚀 #100DaysOfCode #LeetCode #DSA #Java
Squaring a Sorted Array with Optimized Two Pointer Approach
More Relevant Posts
-
🚀 LeetCode Challenge 19/50 💡 Approach: Horizontal Scanning The sorting-based approach costs O(S log n). Instead, I used Horizontal Scanning — take the first string as the prefix and keep shrinking it until every string agrees. No sorting, no extra space! 🔍 Key Insight: → Start with strs[0] as the full prefix candidate → For each next string, shrink prefix from the right until it matches → If prefix becomes empty at any point → return "" → What's left is the longest common prefix! 📈 Complexity: ❌ Sort-based → O(S log n) Time ✅ Horizontal Scan → O(S) Time, O(1) Space where S = total characters across all strings The smartest solutions don't always need fancy data structures — sometimes a simple shrinking window does the job perfectly! 🪟 #LeetCode #DSA #StringManipulation #Java #ADA #PBL2 #LeetCodeChallenge #Day19of50 #CodingJourney #ComputerEngineering #AlgorithmDesign #LongestCommonPrefix
To view or add a comment, sign in
-
-
Day 71/100 Completed ✅ 🚀 Solved LeetCode – Reshape the Matrix (Java) ⚡ Implemented an efficient matrix transformation approach by mapping elements from the original matrix to the reshaped matrix using a single traversal. Instead of creating intermediate structures, used index manipulation (count / c, count % c) to place elements correctly while maintaining row-wise order. 🧠 Key Learnings: • Understanding how to map 2D indices into a linear traversal • Efficiently converting between different matrix dimensions • Handling edge cases where reshape is not possible • Writing clean and optimized nested loop logic 💯 This problem strengthened my understanding of matrix traversal and index mapping techniques, which are very useful in array and grid-based problems. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀 LeetCode — Problem 18 | Day 16 💡 Problem: 4Sum 🧠 Problem: Given an array nums and a target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that their sum equals the target. 🧠 Approach (Sorting + Two Pointers): Sort the array: Essential for two-pointer movement and skipping duplicates. Nested Loops: Fix the first two elements using two loops (i and j). Two Pointers: Use left and right pointers for remaining two elements. Skip Duplicates: Avoid duplicate quadruplets by skipping same values for i, j, left, right. ⚙️ Core Logic: Fix i and j, then set left = j + 1 and right = n - 1. Compute sum = nums[i] + nums[j] + nums[left] + nums[right]. If sum == target: Add quadruplet to result and move both pointers while skipping duplicates. If sum < target: Move left++ If sum > target: Move right-- ⏱ Time Complexity: O(n^3) 📦 Space Complexity: O(1) (excluding output list) ⚠️ Edge Cases: - Array size < 4 - Integer overflow (use long for sum) - Duplicate values leading to repeated results 🔍 Insight: 4Sum is an extension of 3Sum. Fixing two numbers reduces problem to two-pointer search. 🔑 Key Learning: - Extending two-pointer technique to higher dimensions - Handling duplicates efficiently in sorted arrays - Using long to avoid overflow "Use sorting and nested two pointers to reduce complexity from O(n^4) to O(n^3) while ensuring unique quadruplets." #LeetCode #DSA #Java #TwoPointers #CodingJourney #4Sum #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 45/60 – DSA Challenge Today’s problem was about searching in a Rotated Sorted Array using Binary Search 🔍 🔍 Problem Solved: Given a rotated sorted array, efficiently find the index of a target element. 🧠 Approach I Used: Instead of directly applying binary search, I broke the problem into two steps: 1️⃣ Find the pivot (rotation point) using binary search 2️⃣ Apply binary search on the correct half of the array Left half → sorted from start to pivot-1 Right half → sorted from pivot to end ⚡ Key Insight: By identifying the pivot, the problem becomes two simple binary searches Careful boundary checks (like target >= nums[0]) ensure we search in the correct half Handling edge cases (like pivot at index 0) is crucial for correctness 📈 Complexity: Time: O(log n) Space: O(1) 🎯 What I Learned: Complex problems can often be simplified by breaking them into smaller parts Binary Search is not just about searching—it’s about understanding structure Boundary conditions can make or break your solution Debugging edge cases today made the concept even clearer 💡 #Day45 #DSAChallenge #BinarySearch #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 28 Today’s focus: Binary Search for minimum in rotated arrays. Problem solved: • Find Minimum in Rotated Sorted Array (LeetCode 153) Concepts used: • Binary Search • Identifying unsorted half • Search space reduction Key takeaway: The goal is to find the minimum element in a rotated sorted array. Using binary search, we compare the mid element with the rightmost element: • If nums[mid] > nums[right] → minimum lies in the right half • Else → minimum lies in the left half (including mid) This works because the rotation creates one unsorted region, and the minimum always lies in that region. By narrowing the search space each time, we achieve O(log n) time complexity. This problem highlights how slight modifications in array structure still allow binary search to work efficiently with the right observations. Continuing to strengthen binary search patterns and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
🔥 DSA Challenge – Day 128/360 🚀 📌 Topic: Recursion 🧩 Problem: Letter Combinations of a Phone Number 💡 Problem Statement: Given a string of digits (2–9), return all possible letter combinations that the number could represent based on the classic phone keypad mapping. 🔍 Example: Input: "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 💡 Approach: Backtracking (Recursion) We treat this like a decision tree: Each digit maps to multiple characters For every digit, we try all possible letters Build combinations step-by-step using recursion 👉 Key Idea: Choose → Explore → Backtrack Use StringBuilder for efficient string manipulation ⚙️ Steps: Create a mapping for digits → letters Start recursion from index 0 For each digit: Loop through its mapped letters Add letter to current string Move to next digit Backtrack (remove last character) 🚀 Code Highlights: ✔️ Base case: when index reaches end → add combination ✔️ Efficient backtracking using StringBuilder ✔️ Avoids extra space by modifying same string ⏱️ Time Complexity: O(4^N) 📦 Space Complexity: O(N) (recursion stack) Master this → You master recursion 🔥 #DSA #Java #Backtracking #CodingInterview #LeetCode #128DaysOfCode #Programming #Tech #ProblemSolving
To view or add a comment, sign in
-
-
💡 Day 57 of LeetCode Problem Solved! 🔧 🌟 Maximum Distance Between a Pair of Values 🌟 🔗 Solution Code: https://lnkd.in/gSP_QePE 🧠 Approach: • Two-Pointer Strategy: Maintain two indices (i for nums1 and j for nums2) to scan both non-increasing arrays in a single efficient pass. • Greedy Search: If nums1[i] <= nums2[j], calculate j - i and expand j to find the maximum possible distance. If the value in nums1 is too large, move i forward. ⚡ Key Learning: • Leveraging the non-increasing nature of arrays with two pointers eliminates the need for nested loops, reducing complexity from O(N^2) to linear O(N+M). ⏱️ Complexity: • Time: O(n + m) • Space: O(1) #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #Algorithms #TwoPointers
To view or add a comment, sign in
-
-
🔥 𝗗𝗮𝘆 𝟴𝟵/𝟭𝟬𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝟳𝟰𝟰. 𝗙𝗶𝗻𝗱 𝗦𝗺𝗮𝗹𝗹𝗲𝘀𝘁 𝗟𝗲𝘁𝘁𝗲𝗿 𝗚𝗿𝗲𝗮𝘁𝗲𝗿 𝗧𝗵𝗮𝗻 𝗧𝗮𝗿𝗴𝗲𝘁 | 🟢 𝗘𝗮𝘀𝘆 | 𝗝𝗮𝘃𝗮 Looks easy — but the circular wrap-around is the trap most people miss. 𝗧𝗵𝗲 𝗽𝗿𝗼𝗯𝗹𝗲𝗺: Given a sorted circular array of letters, find the smallest letter strictly greater than the target. If none exists, wrap around to the first letter. 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 — 𝗕𝗶𝗻𝗮𝗿𝘆 𝗦𝗲𝗮𝗿𝗰𝗵: ✅ Standard binary search for the first letter > target ✅ If letters[mid] > target → go left (end = mid - 1) ✅ Else → go right (start = mid + 1) ✅ After the loop, start points to the answer ✅ Use start % letters.length to handle the circular wrap-around 𝗧𝗵𝗲 𝗰𝗹𝗲𝘃𝗲𝗿 𝗯𝗶𝘁: If target is greater than or equal to all letters, start lands at letters.length — modulo wraps it back to index 0 automatically. No special case needed. 🔄 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆: ⏱ Time: O(log n) 📦 Space: O(1) One modulo operation handles the entire circular edge case cleanly. This is binary search with a twist — and the wrap-around trick is worth remembering! 🧠 📂 𝗙𝘂𝗹𝗹 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗼𝗻 𝗚𝗶𝘁𝗛𝘂𝗯: https://lnkd.in/gvK_p44b 11 more days. So close! 💪 #LeetCode #Day89of100 #100DaysOfCode #Java #DSA #BinarySearch #Arrays #CodingChallenge #Programming
To view or add a comment, sign in
-
Day 76/100 Completed ✅ 🚀 Solved LeetCode – Search a 2D Matrix (Java) ⚡ Implemented an optimized binary search approach by treating the 2D matrix as a flattened sorted array. Converted 1D index into 2D coordinates (row = mid / m, col = mid % m) to efficiently locate the target in O(log(m × n)) time. 🧠 Key Learnings: • Applying binary search on a 2D matrix • Converting 1D index to 2D (row & column mapping) • Reducing time complexity from O(m × n) → O(log(m × n)) • Importance of problem observation (matrix behaves like sorted array) 💯 This problem strengthened my understanding of binary search variations and how to apply it beyond simple 1D arrays. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #binarysearch #arrays #optimization #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
**Day 116 of #365DaysOfLeetCode Challenge** Today’s problem: **Next Greater Element II (LeetCode 503)** A classic **Monotonic Stack** problem with a twist: 👉 The array is **circular** So after the last element, we continue from the first element. 💡 **Core Idea:** For every number, find the **first greater element** while traversing forward. If none exists → return `-1` Example: Input: `[1,2,1]` Output: `[2,-1,2]` Why? * First `1 → 2` * `2 → no greater` * Last `1 → wrap around → 2` 📌 **Efficient Approach: Monotonic Stack** Use stack to store indices whose next greater element is not found yet. Traverse array **twice**: `0 → 2*n - 1` Use: `idx = i % n` This simulates circular behavior. Whenever current number is greater than stack top element: 👉 Pop index 👉 Update answer ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Circular array problems often become simple when you traverse twice using modulo. 👉 `i % n` This trick appears in many advanced array questions. 💭 **Key Takeaway:** When you see: * Next Greater Element * Previous Smaller Element * Nearest Bigger Value #LeetCode #DSA #MonotonicStack #Stack #Arrays #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
Explore related topics
- LeetCode Array Problem Solving Techniques
- Leetcode Problem Solving Strategies
- How To Optimize The Software Development Workflow
- How to Improve Array Iteration Performance in Code
- Solving Sorted Array Coding Challenges
- Approaches to Array Problem Solving for Coding Interviews
- Strategies For Code Optimization Without Mess
- How to Improve Code Performance
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