Problem :- Merge Sorted Array (LeetCode 88) Problem Statement :- You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n representing the number of elements in nums1 and nums2 respectively. Merge nums2 into nums1 as one sorted array. The final sorted array should not be returned, but instead be stored inside nums1. Approach :- Three Pointer Technique i - Use three pointers: i → last element of nums1 (m-1) j → last element of nums2 (n-1) k → last position of nums1 (m+n-1) ii - Compare nums1[i] and nums2[j], place larger at nums1[k] iii - Move pointers accordingly iv - If elements left in nums2, copy them v - Time Complexity : O(m + n) vi - Space Complexity : O(1) class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int p1 = m -1; int p2 = n -1; int p = m + n -1; while(p1 >=0 && p2 >= 0){ if(nums1[p1] > nums2[p2]){ nums1[p] = nums1[p1]; p1--; }else { nums1[p] = nums2[p2]; p2--; } p--; } while (p2 >= 0){ nums1[p] = nums2[p2]; p2--; p--; } } } Key Takeaway :- Instead of merging from the front (which causes shifting), start from the end and place elements in correct position using three pointers. How would you optimize this further? Is there any way to handle merging without using extra space in other variations? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #TwoPointers
Merging Sorted Arrays with Three Pointers in Java
More Relevant Posts
-
Problem :- Remove Duplicates from Sorted Array (LeetCode 26) Problem Statement :- Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements. The relative order of elements should be kept the same. Approach :- Two Pointer Technique i - Use pointer k to track position of unique elements ii - Traverse array from index 1 iii - If nums[i] != nums[k-1], place it at nums[k] iv - Time Complexity : O(n) v - Space Complexity : O(1) class Solution { public int removeDuplicates(int[] nums) { int k = 1; for(int i = 1; i < nums.length; i++) { if(nums[i] != nums[k - 1]) { nums[k] = nums[i]; k++; } } return k; } } Key Takeaway :- Since the array is already sorted, duplicates are adjacent. Using two pointers allows us to efficiently overwrite duplicates in a single pass without extra space. If yes, how would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #TwoPointers
To view or add a comment, sign in
-
-
🔥 Day 552 of #750DaysOfCode 🔥 🔐 LeetCode 2075: Decode the Slanted Ciphertext (Medium) Today’s problem looked tricky at first, but once the pattern clicked, it became super elegant 😄 🧠 Problem Understanding We are given an encoded string that was: Filled diagonally (↘) into a matrix Then read row-wise (→) 👉 Our task is to reverse this process and recover the original text. 💡 Key Insight If encoding is: ➡️ Fill diagonally ➡️ Read row-wise Then decoding is: ➡️ Read diagonally from row-wise string ⚙️ Approach ✅ Step 1: Calculate number of columns cols = encodedText.length() / rows; ✅ Step 2: Traverse diagonals starting from each column for (int startCol = 0; startCol < cols; startCol++) { int row = 0, col = startCol; while (row < rows && col < cols) { result.append(encodedText.charAt(row * cols + col)); row++; col++; } } ✅ Step 3: Remove trailing spaces 🚀 Complexity Time: O(n) Space: O(n) 🧠 What I Learned How to reverse matrix-based encoding patterns Converting 2D traversal → 1D index mapping Importance of pattern recognition in problems 📌 Takeaway Not every problem needs heavy logic. Sometimes, it's just about seeing the pattern correctly 👀 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Algorithms #SoftwareEngineering #100DaysOfCode #750DaysOfCode
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
-
-
🚀 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 115 of #365DaysOfLeetCode Challenge** Today’s problem: **Diagonal Traverse (LeetCode 498)** A smart **matrix traversal** problem where the goal is to print all elements in zigzag diagonal order. Example: ```text id="k44nq2" 1 2 3 4 5 6 7 8 9 ``` Output: `[1,2,4,7,5,3,6,8,9]` **Core Idea:** Each diagonal is identified by: `row + col` * If `(row + col)` is even → move **up-right** * If `(row + col)` is odd → move **down-left** This removes the need for an extra direction variable. 📌 **Approach:** 1️⃣ Start at `(0,0)` 2️⃣ Add current element to result 3️⃣ Check parity of `(row + col)` 4️⃣ Move diagonally 5️⃣ If boundary reached, adjust row/col accordingly Repeat until all cells are visited. ⚡ **Time Complexity:** O(m × n) ⚡ **Space Complexity:** O(1) extra (excluding output) **What I learned today:** Sometimes parity (`row + col`) can simplify movement logic beautifully. Instead of tracking direction separately: 👉 Even diagonal = upward 👉 Odd diagonal = downward 💭 **Key Takeaway:** Great solutions often replace state variables with mathematical patterns. #LeetCode #DSA #Matrix #Arrays #Traversal #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 88 — Prefix Sum Pattern (Pivot Index) Continuing the prefix sum journey — today I solved a problem that finds the equilibrium point where the sum of elements to the left equals the sum to the right. This is a great example of optimizing space using simple math. 📌 Problem Solved: LeetCode 724 – Find Pivot Index 🧠 Optimized Approach – Single Pass with Total Sum: java int total = 0, leftSum = 0; for (int num : nums) total += num; for (int i = 0; i < nums.length; i++) { // rightSum = total - leftSum - nums[i] if (leftSum == total - leftSum - nums[i]) return i; leftSum += nums[i]; } return -1; Why this works: total = sum of all elements. At index i, rightSum = total - leftSum - nums[i]. No need to store prefix/suffix arrays — just update leftSum as we go. Space complexity drops from O(n) to O(1). Key Insight from Revision: Earlier we discussed the Pivot Index optimization using the relationship: Total Sum = Left Sum + arr[i] + Right Sum → Right Sum = Total Sum - Left Sum - arr[i] This eliminates extra arrays. Edge Cases: Pivot at index 0 → left sum = 0. Pivot at last index → right sum = 0. No pivot → return -1. 💡 Takeaway: Not every prefix sum problem needs extra arrays. Recognizing when you can derive one side from the total sum and the other side saves space and simplifies code. No guilt about past breaks — just mastering optimizations within patterns. #DSA #PrefixSum #PivotIndex #LeetCode724 #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
Problem :- Search Insert Position (LeetCode 35) Problem Statement :- Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Approach :- Binary Search i - Uses Binary Search to efficiently find the target or its position in a sorted array. ii - Compares nums[mid] with target and adjusts search range (start or end). iii - Loop ends when target is not found, and correct position is crossed. iv - If target > nums[mid] => mid + 1 Else => mid v - Time Complexity : O(log n) vi - Space Complexity : O(1) class Solution { public int searchInsert(int[] nums, int target) { int start = 0; int end = nums.length - 1; int mid = 0; while (start <= end) { mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { start = mid + 1; } else { end = mid - 1; } } return (target > nums[mid]) ? mid + 1 : mid; } } Key Takeaway :- Binary Search efficiently finds the position (or insertion point) by repeatedly dividing the search space. How would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #BinarySearch
To view or add a comment, sign in
-
-
🚀 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 85 of #100DaysOfCode Solved 106. Construct Binary Tree from Inorder and Postorder Traversal on LeetCode 🔗 🧠 Key Insight: 👉 Postorder = Left → Right → Root 👉 Last element in postorder = root of tree 👉 Inorder = Left → Root → Right 👉 Use inorder to split into left & right subtrees ⚙️ Approach (HashMap + Recursion): 1️⃣ Take last element of postorder 🔹 This is the root 2️⃣ Find root index in inorder 🔹 Split inorder into: • Left subtree • Right subtree 3️⃣ Build subtrees recursively: 🔹 Important order: 👉 Build right subtree first, then left (because we are consuming postorder from end) 4️⃣ Use a HashMap: 🔹 Store inorder value → index 👉 For O(1) lookup ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(n) #100DaysOfCode #LeetCode #DSA #BinaryTree #Recursion #DivideAndConquer #HashMap #Java #InterviewPrep #CodingJourney
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