Day 43/100 Problem Statement : Given an array nums, you can perform the following operation any number of times: Select the adjacent pair with the minimum sum in nums. If multiple such pairs exist, choose the leftmost one. Replace the pair with their sum. Return the minimum number of operations needed to make the array non-decreasing. An array is said to be non-decreasing if each element is greater than or equal to its previous element (if it exists). Input: nums = [5,2,3,1] Output: 2 Solution : https://lnkd.in/g3Z6NQxN public int minimumPairRemoval(int[] nums) { int length = nums.length - 1; int count = 0; while(length > 0) { boolean increase = true; int minSum = Integer.MAX_VALUE; int minIndex = -1; for(int i = 0; i < length; i++) { if(nums[i] > nums[i + 1]) increase = false; if(nums[i] + nums[i + 1] < minSum) { minSum = nums[i] + nums[i + 1]; minIndex = i; } } if(increase) break; nums[minIndex] = minSum; for(int i = minIndex + 1; i < length; i++) nums[i] = nums[i + 1]; length--; count++; } return count; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
How to make an array non-decreasing with minimum operations
More Relevant Posts
-
Day 58/100 Problem Statement : You are given a 0-indexed array nums consisiting of positive integers. You can do the following operation on the array any number of times: Select an index i such that 0 <= i < n - 1 and replace either of nums[i] or nums[i+1] with their gcd value. Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1. The gcd of two integers is the greatest common divisor of the two integers. Input: nums = [2,6,3,4] Output: 4 Solution : https://lnkd.in/eaD3v_XT public int minOperations(int[] nums) { int n = nums.length; int ones = 0; for (int x : nums) { if (x == 1) ones++; } if (ones > 0) return n - ones; int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int g = nums[i]; for (int j = i + 1; j < n; j++) { g = gcd(g, nums[j]); if (g == 1) { ans = Math.min(ans, j - i); break; } } } if (ans == Integer.MAX_VALUE) return -1; return ans + n - 1; } private int gcd(int a, int b) { while (b != 0) { int t = a % b; a = b; b = t; } return a; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
💡 Day 10 of 100 Days of LeetCode 📘 Problem: #26. Remove Duplicates from Sorted Array 💻 Difficulty: Easy 🔍 Concept: The task is to remove duplicates in-place from a sorted array so that each unique element appears only once. The function should return the count of unique elements k. ⚙️ Approach Used: Used two-pointer technique — one pointer (k) tracks the position of the last unique element, and the other (i) scans the array. Whenever a new unique element is found, it’s moved to the next position in the array. 🧠 Key Learnings: Mastered the in-place modification concept in arrays. Learned how to use two-pointer pattern for linear-time solutions. Refined logic building with minimal extra space usage (O(1) space). 💻 Code (Java): class Solution { public int removeDuplicates(int[] nums) { int k = 0; for (int i = 1; i < nums.length; i++) { if (nums[i] != nums[k]) { k++; nums[k] = nums[i]; } } return k + 1; } } 💬 Reflection: A simple-looking problem — but it’s one that trains you to think in space-efficient ways. Sometimes, mastering basics is what builds strong problem-solving intuition! #100DaysOfLeetCode #Day10 #DSA #Java #ProblemSolving #CodingChallenge #LeetCode #LearningEveryday
To view or add a comment, sign in
-
-
✅Day38 : Leetcode 35 - Search Insert Position #60DayOfLeetcodeChallenge 🧩 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. 💡 My Approach I used Binary Search to efficiently find the target position. Initialize low = 0 and high = n - 1. Use a variable ans = n to store the possible insert position. While low <= high, find the mid index. If nums[mid] >= target, store mid as a possible answer and move left. Else, move right by setting low = mid + 1. Return ans at the end. ⏱ Time Complexity O(log n) — because we use Binary Search. 💾 Space Complexity O(1) — only a few variables are used. #BinarySearch #LeetCode #Java #DataStructures #DSA #LeetCodeEasy #SearchInsertPosition
To view or add a comment, sign in
-
-
📌 Day 27/100 - Generate Parentheses (LeetCode 22) 🔹 Problem: Given n pairs of parentheses, generate all combinations of well-formed (balanced) parentheses. 🔹 Approach: Use backtracking to build strings character-by-character. Keep two counters: open = number of '(' used, close = number of ')' used. You may add '(' while open < n. You may add ')' while close < open (to maintain balance). When the current string length reaches 2*n, add it to the result list. 🔹 Complexity: Time: proportional to the number of valid combinations (Catalan number) — roughly O(4ⁿ / n^(3/2)). Space: output-sensitive — O(n * Cn) for storing results, and O(n) extra for recursion depth. 🔹 Key Learning: Backtracking is ideal when you need to enumerate valid combinations subject to constraints. Always enforce constraints early (here: close < open) to prune invalid branches. Think in terms of state (open/close counts) rather than raw string manipulation. #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA
To view or add a comment, sign in
-
-
💻 Day 52 of #100DaysOfCodeChallenge Today’s problem: LeetCode 203 – Remove Linked List Elements 🧩 I worked on a Linked List manipulation problem where the goal is to remove all nodes that match a given value. This problem helped strengthen my understanding of pointer handling and dummy node usage in linked lists. 🧠 What I Learned: Handling edge cases where the head itself might need to be removed. Using a dummy node before the head to simplify pointer operations. How current and next pointers work together to modify a linked list safely. 🧩 Java Solution: class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode current = dummy; while (current.next != null) { if (current.next.val == val) current.next = current.next.next; else current = current.next; } return dummy.next; } } ⏱️ Complexity: Time: O(n) Space: O(1) Every day, I’m getting more confident with data structures and linked list traversal logic. On to the next challenge 🚀 #Day52 #LeetCode #Java #100DaysOfCode #CodingChallenge #LinkedList #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 75 — Find All Pairs with a Given Sum (75/100) 🧩 Problem: Given an array of integers, find all unique pairs (a, b) such that a + b = 0. Return all pairs sorted in ascending order based on their first and then second element. 📘 Example: Input: [1, -1, 2, -2, 3] Output: [[-2, 2], [-1, 1]] ⚙️ Approach: Sort the array. Use two-pointer technique (left and right indices). Move pointers based on the sum: If sum == 0 → store the pair. If sum < 0 → move left pointer up. If sum > 0 → move right pointer down. Used a HashSet to avoid duplicates. Finally, sort all pairs lexicographically. 🧠 Key Concept: Efficient pair finding in sorted arrays using two-pointer logic (O(n log n)). ⏱️ Time Complexity: O(n log n) 💾 Space Complexity: O(n) ✅ Result: All 1115 / 1115 test cases passed ✅ Accuracy: 100% Points: 2 / 2 Total Score: 144 💪 Every line of code brings you closer to mastery — stay consistent, stay sharp! 🔥 #100DaysOfDSA #Java #TwoPointer #GeeksForGeeks #DSAChallenge #CodingJourney
To view or add a comment, sign in
-
-
DSA Practice – Day 68 🚀 Problem: Subsets II (LeetCode 90) ✨ Brute Force Approach 1. Generate all possible subsets using recursion (like Subsets I). 2. Use a Set or HashSet to store unique subsets and avoid duplicates. 3. Convert the set back to a list before returning the result. Time Complexity: O(2ⁿ × n) (to generate all subsets) Space Complexity: O(2ⁿ × n) (storing all subsets) ✨ Optimal Approach (Backtracking with Duplicate Handling) We use backtracking, but with a twist — handle duplicates smartly. Steps: 1. Sort the array so duplicates come together. 2. Use a loop with a check if(i != ind && nums[i] == nums[i - 1]) continue; to skip duplicates. 3. Recursively generate subsets and backtrack after each recursive call. Time Complexity: O(2ⁿ × n) Space Complexity: O(n) 🌟 Key Idea Sorting + Skipping duplicates ensures we only generate unique subsets efficiently. #Day68 #Backtracking #DSA #Java #LeetCode #Placements
To view or add a comment, sign in
-
-
Day 46/100 Problem Statement : You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer. Input: target = [1,2,3,2,1] Output: 3 Solution : https://lnkd.in/gsXFvUr3 public int minNumberOperations(int[] target) { final int n=target.length; int ans=target[0]; for(int i=1; i<n; i++) ans+=Math.max(target[i]-target[i-1], 0); return ans; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
🚀 LeetCode #58 – Length of Last Word (Java Solution) Today I solved a classic string problem that tests how well you handle edge cases and string traversal logic. 🧩 Problem Statement: Given a string s consisting of words and spaces, return the length of the last word in the string. A word is defined as a maximal substring consisting of non-space characters only. 🧠 Dry Run Example Input: " fly me to the moon " ➡ After skipping spaces → "fly me to the moon" ➡ Last word = "moon" ➡ Output: 4 ⚙️ Time & Space Complexity Time Complexity: O(n) — we traverse the string once (from the end to the start). Space Complexity: O(1) — no extra space used apart from a few variables. 💡 Key Takeaways: ✅ Learned how to handle trailing spaces properly before counting. ✅ Strengthened understanding of string traversal in reverse. ✅ Explored an alternative approach using trim() + split("\\s+") for readability. ✅ Remembered to test with edge cases like "a" or "Hello " to ensure correctness. Every small problem like this helps in building stronger fundamentals 💪 #Java #LeetCode #ProblemSolving #CodingJourney #LearningInPublic #75DaysOfCode #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🔹 Day 47: Find Pivot Index (LeetCode #724) 📌 Problem Statement: Given an array of integers nums, the pivot index is the index where the sum of all numbers to the left is equal to the sum of all numbers to the right. If no such index exists, return -1. If multiple exist, return the leftmost one. ✅ My Approach: I first calculated the total sum of the array, then iterated through each element keeping track of the left sum. At each index, I checked whether left sum == total sum - left sum - current element. If true, that index is the pivot index. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ⚡ Submission Stats: Runtime: 0 ms (Beats 100%) Memory: 45.41 MB (Beats 66.27%) 💡 Reflection: This problem strengthened my understanding of prefix sums and efficient single-pass array traversal. A clean and optimized logic! 💪 #LeetCode #Java #Arrays #PrefixSum #100DaysOfCode #Day47
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