question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
โŒ€
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
minimum-pair-removal-to-sort-array-i
๐Ÿ”ฅ Leetcode 3507: Minimum Pair Removal to Sort Array I
leetcode-3507-minimum-pair-removal-to-so-d7l0
๐Ÿ’กIntuitionWe keep merging the pair with the smallest sum until the array becomes non-decreasing. Each merge helps fix the order. We count how many merges are ne
CtrlAltVardhan
NORMAL
2025-04-06T07:25:46.112898+00:00
2025-04-06T07:25:46.112898+00:00
500
false
# ๐Ÿ’กIntuition We keep merging the pair with the smallest sum until the array becomes non-decreasing. Each merge helps fix the order. We count how many merges are needed. ## ๐Ÿ” Approach - Check if the array is already sorted. - If not sorted: - Find the **leftmost pair** with the **smallest sum**. - Replace the pair with their **sum**. - Put the sum in the first position. - Remove the second number. - Repeat the above steps. - Count how many times we do this until the array is sorted. --- ## โฑ๏ธ Complexity - **Time Complexity:** `O(n^2)` We check and modify the array many times as it gets smaller. - **Space Complexity:** `O(1)` No extra space is used except for simple variables. --- # Code ```cpp [] class Solution { private: void shiftLeft(vector<int>& nums, int index) { for (int i = index; i < nums.size() - 1; i++) { nums[i] = nums[i + 1]; } nums.pop_back(); } void mergeMinPair(vector<int>& nums) { //search for min Sum int minSum = INT_MAX; int minIndx = 0; for (int i = 0; i < nums.size()-1; i++) { int sum = nums[i] + nums[i + 1]; if (sum < minSum) { minIndx = i; minSum = sum; } } nums[minIndx] = minSum; shiftLeft(nums, minIndx + 1); } bool isSorted(vector<int>&nums){ for(int i=0;i<nums.size()-1;i++){ if(nums[i]>nums[i+1])return false; } return true; } public: int minimumPairRemoval(vector<int>& nums) { int cnt = 0; while (!isSorted(nums)) { mergeMinPair(nums); cnt++; } return cnt; } }; ```
4
0
['Greedy', 'C++']
0
minimum-pair-removal-to-sort-array-i
JS | Two approach | Beats 100% ๐Ÿš€
js-two-approach-beats-100-by-akashcse200-poci
Complexity Time complexity: O(nยณ) Space complexity: O(1) CodeCode
akashcse2000
NORMAL
2025-04-06T04:07:41.882072+00:00
2025-04-06T04:07:41.882072+00:00
290
false
# Complexity - Time complexity: O(nยณ) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [-JS Approach 1 with in-place array update and while loop] var minimumPairRemoval = function(n) { let c = 0; while (true) { let mn = Infinity, mi = 0, isSorted = true; for (let i = 0; i < n.length-1; i++) { if (n[i] > n[i+1]) isSorted = false; if (mn > n[i]+n[i+1]) { mn = n[i]+n[i+1]; mi = i } } if (isSorted) return c; n[mi] = mn; c++; n.splice(mi+1, 1); } }; ``` # Code ```javascript [-JS Approach 2 with recursion] var minimumPairRemoval = function(n) { let mn = Infinity, mi = -1; for (let i = 0; i < n.length-1; i++) { if (mn > n[i]+n[i+1]) { mn = n[i]+n[i+1]; mi = i } } if (n.every((v,i) => !i || n[i-1] <= v) || mi === -1) return c; n[mi] = mn; c++; return minimumPairRemoval(n.slice(0, mi+1).concat(n.slice(mi+2)), c); }; ```
4
0
['JavaScript']
3
minimum-pair-removal-to-sort-array-i
Using ArrayList || Simple brute force || Beginner friendly
using-arraylist-simple-brute-force-begin-cyic
๐Ÿ’ก Intuition:We are allowed to merge adjacent pairs with the minimum sum, and we aim to make the array non-decreasing in as few operations as possible. To simula
im_obid
NORMAL
2025-04-07T17:10:17.532352+00:00
2025-04-07T17:10:17.532352+00:00
342
false
# ๐Ÿ’ก Intuition: We are allowed to merge adjacent pairs with the minimum sum, and we aim to make the array non-decreasing in as few operations as possible. To simulate the process, we repeatedly: Find the leftmost adjacent pair with the minimum sum. Merge the pair by replacing it with their sum. Continue until the array becomes non-decreasing. # ๐Ÿง  Approach: Convert the input array into a List<Integer> for easier removal of elements during merging. While the list is not non-decreasing: Scan the list to find the leftmost pair with the minimum sum. Merge this pair (i.e., replace both with their sum, keeping only one element). Increment the operation counter. Return the total number of operations once the array becomes non-decreasing. # โœ… Why It Works: By always merging the pair with the smallest sum, we minimize the impact on the rest of the array and move closer to a non-decreasing order without making unnecessary merges. # ๐Ÿ”ข Time Complexity: O(nยณ) worst-case in theory due to repeated scans and removals. But practically efficient for n โ‰ค 50 due to fast array manipulation in Java ArrayList. # Code ```java [] import java.util.*; public class Solution { public int minimumPairRemoval(int[] nums) { List<Integer> list = new ArrayList<>(); for (int num : nums) list.add(num); int ops = 0; while (!isNonDecreasing(list)) { int minSum = Integer.MAX_VALUE; int minIdx = 0; for (int i = 0; i < list.size() - 1; i++) { int sum = list.get(i) + list.get(i + 1); if (sum < minSum) { minSum = sum; minIdx = i; } } // Merge the pair int merged = list.get(minIdx) + list.get(minIdx + 1); list.set(minIdx, merged); list.remove(minIdx + 1); ops++; } return ops; } private boolean isNonDecreasing(List<Integer> list) { for (int i = 1; i < list.size(); i++) { if (list.get(i) < list.get(i - 1)) return false; } return true; } } ```
3
0
['Java']
2
minimum-pair-removal-to-sort-array-i
A UNIQUE APPROACH | | BEATS 100% | | LINKED LIST | | DETAILED EXPLANATION
a-unique-approach-beats-100-linked-list-f1n4n
๐Ÿ”น IntuitionTo make the array non-decreasing, we are allowed to merge any two adjacent elements into their sum and remove the second one. However, to minimize th
dhanunjay_1729
NORMAL
2025-04-06T19:01:27.295304+00:00
2025-04-06T19:01:27.295304+00:00
400
false
### ๐Ÿ”น Intuition To make the array non-decreasing, we are allowed to **merge any two adjacent elements** into their sum and remove the second one. However, to minimize the number of such operations, we need a strategy that makes the array non-decreasing in as few steps as possible. A key idea is that **removing the "most problematic" adjacent pairs early**โ€”those that cause a decreaseโ€”is helpful. Among all such adjacent pairs, merging the one with the **smallest sum** is the safest bet since it introduces a relatively small new number into the array and is less likely to create new decreases. --- ### ๐Ÿ”น Approach 1. Convert the input vector to a `list<int>` for efficient element removal and splicing (as `list` supports O(1) deletion and insertion). 2. Repeatedly check if the current sequence is non-decreasing. If yes, weโ€™re done. 3. If not, find the pair of adjacent elements with the **smallest sum**. 4. Merge them: update the first element with the sum and erase the second element. 5. Increment the operation count and repeat the process. The process terminates when the list becomes non-decreasing. --- ### ๐Ÿ”น Time and Space Complexity - **Time Complexity:** Worst-case is `O(nยฒ)`, because: - In each operation, we may scan the entire list to find the smallest pair โ†’ `O(n)` - We might perform up to `O(n)` such operations in the worst case Hence, total worst-case time is `O(nยฒ)`. - **Space Complexity:** `O(n)` for storing the list version of the input array. --- ### ๐Ÿ”น Code ```cpp class Solution { public: int minimumPairRemoval(vector<int>& nums) { list<int> lst(nums.begin(), nums.end()); int ops = 0; while (true) { // Check if the list is non-decreasing bool nonDecreasing = true; for (auto it = next(lst.begin()); it != lst.end(); ++it) { if (*it < *prev(it)) { nonDecreasing = false; break; } } if (nonDecreasing) break; // Find the pair with the minimum sum auto minIt = lst.begin(); auto nextIt = next(minIt); int minSum = *minIt + *nextIt; for (auto it = lst.begin(); next(it) != lst.end(); ++it) { int sum = *it + *next(it); if (sum < minSum) { minIt = it; nextIt = next(it); minSum = sum; } } // Merge the pair *minIt = *minIt + *nextIt; lst.erase(nextIt); ops++; } return ops; } }; ```
3
0
['C++']
2
minimum-pair-removal-to-sort-array-i
Beats 100% โœ…. Detailed Code Walkthrough.
beats-100-detailed-explanation-by-ravipa-lwa1
IntuitionThe idea is to repeatedly merge the adjacent pair that has the smallest sum. By always choosing the pair with the smallest sum, we expect the array to
ravipatel0508
NORMAL
2025-04-06T04:19:00.138638+00:00
2025-04-06T04:55:55.062057+00:00
342
false
# Intuition The idea is to repeatedly merge the adjacent pair that has the smallest sum. By always choosing the pair with the smallest sum, we expect the array to gradually evolve into a non-decreasing order. Each merge reduces the array size by one and counts as one operation. # Approach 1. **Check if Sorted:** First, we check if the array is already non-decreasing. If it is, no operations are needed. 2. **Find Minimum Sum Pair:** If not sorted, iterate over the array to locate the adjacent pair with the minimum sum. In case of a tie, choose the leftmost pair. 3. **Merge the Pair:** Replace the left element of the pair with the sum of both elements and then remove the right element from the array. 4. **Repeat Until Sorted:** Continue the process until the array becomes non-decreasing, while counting the number of operations. # Complexity - Time complexity: In the worst-case scenario, for each merge operation, we scan the array (O(n)) and then perform an erase operation (O(n)). With at most O(n) merge operations, the ***total time complexity is O(nยฒ)***. > **Given the small constraint (n โ‰ค 50), this is acceptable**. - Space complexity: The solution uses a constant amount of extra space aside from the input array **(O(1) extra space)**. The operations are performed in-place. # Code ```cpp [] class Solution { public: bool isSorted(const vector<int>& nums) { for (int i = 0; i < nums.size() - 1; i++) { if (nums[i] > nums[i + 1]) return false; } return true; } int minimumPairRemoval(vector<int>& nums) { int operations = 0; while (!isSorted(nums) && nums.size() > 1) { int minSum = 1e9; int pos = -1; for (int i = 0; i < nums.size() - 1; i++) { int curSum = nums[i] + nums[i + 1]; if (curSum < minSum) { minSum = curSum; pos = i; } } nums[pos] = nums[pos] + nums[pos + 1]; nums.erase(nums.begin() + pos + 1); operations++; } return operations; } }; ``` # Code Walkthrough ###### **Initialization:** - `operations` is set to 0. This variable will count the number of merge operations performed. ###### **While Loop Condition:** The loop continues as long as: - The array is not sorted (i.e., `!isSorted(nums)` returns `true`), and - The array has more than 1 element (`nums.size() > 1`). This ensures that we stop when the array becomes non-decreasing or has only one element left (which is trivially sorted). ###### **Finding the Adjacent Pair with Minimum Sum:** - Two variables are initialized: - `minSum` is set to a large value (1e9, i.e., 10^9) ensuring that any adjacent sum will be smaller. - `pos` is set to -1 to store the left index of the selected pair. - A for-loop iterates over the vector from index 0 to `nums.size() - 2` (since we look at the pair `[i]` and `[i+1]`). - For each pair, it calculates `curSum = nums[i] + nums[i + 1]`. - If `curSum` is less than the current `minSum`, it updates minSum and stores the current index `i` in `pos`. - This ensures that by the end of the loop, `pos` holds the index of the left element in the adjacent pair which has the minimum sum. - If there are multiple with the same sum, since we update only when a strictly smaller sum is found, the leftmost occurrence is chosen. ###### **Merging the Selected Pair:** - After identifying the pair at indices pos and pos + 1, the code performs the merge: - `nums[pos] = nums[pos] + nums[pos + 1];` - This line replaces the left element with the sum of both. - `nums.erase(nums.begin() + pos + 1);` - This line removes the right element from the vector so that the size is reduced by one. - The `operations` counter is then incremented by 1 as one operation has been completed. ###### **Returning the Final Answer:** Once the while loop completes (meaning the vector is sorted in non-decreasing order or no more operations can be performed), the function returns the number of operations needed.
3
0
['C++']
1
minimum-pair-removal-to-sort-array-i
Brute Force / Simulation
brute-force-simulation-by-escaroda-23my
Iterate until non-decreasing or length is less than 2 On each iteration save index of a minimum sum to process before next iteration if needed.
escaroda
NORMAL
2025-04-08T12:12:00.174949+00:00
2025-04-08T12:12:00.174949+00:00
65
false
Iterate until non-decreasing or length is less than 2 On each iteration save index of a minimum sum to process before next iteration if needed. ```golang [] func minimumPairRemoval(nums []int) int { ops := 0 decrease := true for decrease && len(nums) > 1 { decrease = false minSum := nums[0] + nums[1] j := 0 for i := 1; i < len(nums); i++ { if nums[i-1] > nums[i] { decrease = true } sum := nums[i-1] + nums[i] if sum < minSum { minSum = sum j = i - 1 } } if decrease { ops += 1 nums = append(append(nums[:j], minSum), nums[j+2:]...) } } return ops } ```
2
0
['Go']
0
minimum-pair-removal-to-sort-array-i
Simplest Java Solution by ex-Googler
simplest-java-solution-by-ex-googler-by-2ysl6
IntuitionThe intuition is pretty simple, just perform operations until the array became non-decreasing.Approach Complexity Time complexity: O(n^2) Space comp
ezrealisnotreal
NORMAL
2025-04-08T12:11:20.302538+00:00
2025-04-08T12:11:20.302538+00:00
161
false
# Intuition The intuition is pretty simple, just perform operations until the array became non-decreasing. # Approach <iframe src="https://www.youtube.com/embed/oLdF74pCg-g" frameborder="0" allowfullscreen allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" style="position: absolute; width: 100%; height: 100%;"> </iframe> # Complexity - Time complexity: O(n^2) - Space complexity: O(1) # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { int length = nums.length; int count = 0; while (length > 1) { boolean nonDecreasing = true; int maxSum = Integer.MAX_VALUE; int maxIndex = -1; for (int i = 0; i < length - 1; i++) { if (nums[i] > nums[i + 1]) { nonDecreasing = false; } if (nums[i] + nums[i + 1] < maxSum) { maxSum = nums[i] + nums[i + 1]; maxIndex = i; } } if (nonDecreasing) { break; } nums[maxIndex] = maxSum; for (int i = maxIndex + 1; i < length - 1; i++) { nums[i] = nums[i + 1]; } length--; count++; } return count; } } ```
2
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Python Solution
python-solution-by-dipanjan0013-7d8d
IntuitionNothing :)ApproachSimple brute force approach. Check using while loop that if the array is sorted or not. If not take the set of minimum sum value, rep
dipanjan0013
NORMAL
2025-04-07T05:57:06.450050+00:00
2025-04-07T05:57:06.450050+00:00
88
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Nothing :) # Approach <!-- Describe your approach to solving the problem. --> Simple brute force approach. Check using while loop that if the array is sorted or not. If not take the set of minimum sum value, replace by those two indexes and increase the count by 1. Finally return the count. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(Nยณ) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(N) # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: if len(nums) <= 1: return 0 c = 0 while nums != sorted(nums): msum, mid = float('inf'), 0 for i in range(len(nums) - 1): if msum > nums[i] + nums[i + 1]: msum = nums[i] + nums[i + 1] mid = i nums = nums[:mid] + [msum] + nums[mid + 2:] c += 1 return c ```
2
0
['Python3']
1
minimum-pair-removal-to-sort-array-i
Python3 || pairwise || T/S: 99% / 68%
python3-pairwise-ts-99-68-by-spaulding-a0cg
https://leetcode.com/problems/minimum-pair-removal-to-sort-array-i/submissions/1598821138/I could be wrong, but I think that time complexity is O(N ^2) and spac
Spaulding_
NORMAL
2025-04-06T18:43:30.846977+00:00
2025-04-06T18:46:52.519496+00:00
40
false
``` Python3 [] class Solution: def minimumPairRemoval(self, nums: List[int], ans = 0) -> int: def notSorted(nums: List[int]) -> bool: for a, b in pairwise(nums): if a > b: return True return False while notSorted(nums): minSum, mnIdx = inf, -1 for i, pair in enumerate(pairwise(nums)): if sum(pair) < minSum: minSum, mnIdx, delIdx = sum(pair), i, i+1 nums[mnIdx] = minSum del nums[delIdx] ans+= 1 return ans ``` [https://leetcode.com/problems/minimum-pair-removal-to-sort-array-i/submissions/1598821138/](https://leetcode.com/problems/minimum-pair-removal-to-sort-array-i/submissions/1598821138/) I could be wrong, but I think that time complexity is *O*(*N* ^2) and space complexity is *O*(1), in which *N* ~ `len(nums)`.
2
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
๐ŸŒŸ Simplest Solution For Beginners ๐Ÿ’ฏ๐Ÿ”ฅ๐Ÿ—ฟ
simplest-solution-for-beginners-by-emman-p79r
Code
emmanuel011
NORMAL
2025-04-06T07:06:44.708095+00:00
2025-04-06T07:06:44.708095+00:00
85
false
# Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: res = 0 minimum = float('inf') ind = 0 while nums != sorted(nums): for i in range(len(nums) - 1): if nums[i] + nums[i + 1] < minimum: minimum = nums[i] + nums[i + 1] ind = i nums.pop(ind) nums[ind] = minimum minimum, ind = float('inf'), 0 res += 1 return res ```
2
0
['Python3']
1
minimum-pair-removal-to-sort-array-i
C++ -- Easy To Understand --
c-easy-to-understand-by-pritam-nitj-v7ck
IntuitionApproachComplexity Time complexity: Space complexity: Code
Pritam-nitj
NORMAL
2025-04-06T04:16:42.700934+00:00
2025-04-06T04:16:42.700934+00:00
89
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool checkSorted(vector<int> &temp){ for(int i=0;i<temp.size()-1;i++){ if(temp[i] > temp[i+1]) return false; } return true; } int minimumPairRemoval(vector<int>& nums) { int n = nums.size(); int ans = 0; while(!checkSorted(nums)){ int minIdx = -1; int minSum = INT_MAX; int sum = 0; for(int i=0;i<n-1;i++){ sum = nums[i] + nums[i+1]; if(minSum > sum){ minSum = sum; minIdx = i; } } nums[minIdx] += nums[minIdx+1]; for(int i=minIdx+1;i<n-1;i++){ nums[i] = nums[i+1]; } nums.pop_back(); n--; ans++; } return ans; } }; ```
2
0
['C++']
0
minimum-pair-removal-to-sort-array-i
|| โœ…Beats 100% && #Day_78th_Of_Daily_Codingโœ… ||
beats-100-day_78th_of_daily_coding-by-co-lapd
JAI SHREE DATNA๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™Code
Coding_With_Star
NORMAL
2025-04-06T04:04:28.343445+00:00
2025-04-06T04:04:28.343445+00:00
229
false
# JAI SHREE DATNA๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™๐Ÿ™ # Code ```cpp [] class Solution { public: bool isSorted(const vector<int>& nums) { for (int i = 1; i < nums.size(); ++i) { if (nums[i] < nums[i - 1]) return false; } return true; } void mergeMinSumPair(vector<int>& nums) { int minSum = INT_MAX; int idx = -1; for (int i = 0; i < nums.size() - 1; ++i) { int sum = nums[i] + nums[i + 1]; if (sum < minSum) { minSum = sum; idx = i; } } nums[idx] = nums[idx] + nums[idx + 1]; nums.erase(nums.begin() + idx + 1); } int minimumPairRemoval(vector<int>& nums) { int operations = 0; while (!isSorted(nums)) { mergeMinSumPair(nums); operations++; } return operations; } }; ```
2
1
['C++', 'Java', 'Python3']
0
minimum-pair-removal-to-sort-array-i
BEST AND SIMPLE SOLUTION
best-and-simple-solution-by-rishu_raj593-4l2h
IntuitionApproachComplexity Time complexity: Space complexity: Code
Rishu_Raj5938
NORMAL
2025-04-12T08:32:47.048477+00:00
2025-04-12T08:32:47.048477+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int n = nums.size(); bool nondec = false; int ans = 0; while(!nondec) { for(int i=1; i<nums.size(); i++) { if(nums[i] < nums[i-1]) { break; } if(i == nums.size()-1) nondec = true; } if(nums.size() == 1 || nondec == true) break; int idx = -1; int sum = INT_MAX; for(int i=1; i<nums.size(); i++) { if(nums[i]+nums[i-1] < sum) { sum = nums[i] + nums[i-1]; idx = i-1; } } if(idx != -1 && sum != INT_MAX) { nums.erase(nums.begin()+idx+1); nums[idx] = sum; } ans++; } return ans; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
๐Ÿš€ Best C++ Solution | 0ms Runtime | Time : O(nยฒ) | Easy to Understand.
best-c-solution-0ms-runtime-time-on2-eas-nfqv
๐Ÿ’กIntuitionIf the array is already sorted, we donโ€™t need to do anything.Otherwise, we keep removing the pair of neighbors with the smallest total, and replace it
Rakesh_Dey_007
NORMAL
2025-04-11T17:51:37.471640+00:00
2025-04-11T17:51:37.471640+00:00
34
false
# ๐Ÿ’กIntuition <!-- Describe your first thoughts on how to solve this problem. --> If the array is already sorted, we donโ€™t need to do anything. Otherwise, we keep removing the pair of neighbors with the smallest total, and replace it with their sum. This helps fix the "unsorted" parts of the array, step-by-step. # Approach <!-- Describe your approach to solving the problem. --> 1. Check if the array is sorted. 2. While itโ€™s not sorted: - Look at all side-by-side pairs. - Find the pair with the smallest sum, and if there are many, pick the first one. - Replace that pair with their sum (remove one element). - Count this as one operation. 3. Repeat until the array is sorted. 4. Return the total number of operations. # Complexity - Time complexity: `O(n^2)` <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: `0(1)` <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool isNonDecreasing(const vector<int>& nums) { for (int i = 1; i < nums.size(); ++i) { if (nums[i] < nums[i - 1]) return false; } return true; } int minimumPairRemoval(vector<int>& nums) { int operations = 0; while (!isNonDecreasing(nums)) { int minSum = INT_MAX; int minIndex = -1; // Find the leftmost adjacent pair with minimum sum for (int i = 0; i < nums.size() - 1; ++i) { int pairSum = nums[i] + nums[i + 1]; if (pairSum < minSum) { minSum = pairSum; minIndex = i; } } // Replace the pair with their sum nums[minIndex] = nums[minIndex] + nums[minIndex + 1]; nums.erase(nums.begin() + minIndex + 1); ++operations; } return operations; } }; ``` # ๐Ÿ” How the Code Works with Example `nums = [5, 2, 3, 1]` ## ๐Ÿ”„ Steps : 1. Not sorted โ†’ Find pair with smallest sum: - (3,1) โ†’ sum = 4 โ†’ Replace with 4 โ†’ `nums = [5, 2, 4]` - Operations = 1 2. Still not sorted โ†’ Find next smallest pair: - (2,4) โ†’ sum = 6 โ†’ Replace with 6 โ†’ `nums = [5, 6]` - Operations = 2 3. Now `[5, 6]` is sorted โ†’ Done โœ… - Return Number of Operations, Which is 2. Final Output : `2`
1
0
['Array', 'Simulation', 'C++']
0
minimum-pair-removal-to-sort-array-i
Super Easy and simple Solution for beginners | Beats 95%
super-easy-and-simple-solution-for-begin-f0ho
Please upvote if this helps you!Code
rajsekhar5161
NORMAL
2025-04-10T19:14:56.813751+00:00
2025-04-10T19:14:56.813751+00:00
51
false
# ***Please upvote if this helps you!*** # Code ```python [] class Solution(object): def minimumPairRemoval(self, nums): count=0 def check(nums): for i in range(1,len(nums)): if nums[i]<nums[i-1]: return False return True while not check(nums): mini=float('inf') for i in range(1,len(nums)): if (nums[i]+nums[i-1])<mini: mini=(nums[i]+nums[i-1]) index=i nums[index-1]+=nums[index] nums.pop(index) count+=1 return count ```
1
0
['Array', 'Simulation', 'Doubly-Linked List', 'Python']
0
minimum-pair-removal-to-sort-array-i
cpp โค๏ธ easy solution ๐ŸŒธ
cpp-easy-solution-by-varuntyagig-pqn5
Code
varuntyagig
NORMAL
2025-04-10T10:51:41.177586+00:00
2025-04-10T10:51:41.177586+00:00
78
false
# Code ```cpp [] class Solution { public: void checkforSortedArray(vector<int>& nums, bool& flag) { for (int i = 0; i < nums.size() - 1; i++) { // not sorted if (nums[i] > nums[i + 1]) { flag = 1; break; } } } int minimumPairRemoval(vector<int>& nums) { bool flag = 0; checkforSortedArray(nums, flag); if (!flag) { return 0; } // Now Sort the array int count = 0; while (flag) { count += 1; int mini = INT_MAX, indexi; for (int i = 0; i < nums.size() - 1; i++) { int sum = nums[i] + nums[i + 1]; if (mini > sum) { mini = sum; indexi = i; } } nums[indexi] = mini; nums.erase(nums.begin() + indexi + 1); flag = 0; checkforSortedArray(nums, flag); } return count; } }; ```
1
0
['Array', 'C++']
0
minimum-pair-removal-to-sort-array-i
Sorted Harmony, Through Pair Fusion Achieved
sorted-harmony-through-pair-fusion-achie-zp1n
IntuitionDisorder in the array, you sense? Fix it with minimum effort, we must. By merging the pair with the smallest sum, order we approach. Always the leftmos
x7Fg9_K2pLm4nQwR8sT3vYz5bDcE6h
NORMAL
2025-04-10T02:17:06.541370+00:00
2025-04-10T02:17:06.541370+00:00
49
false
# Intuition Disorder in the array, you sense? Fix it with minimum effort, we must. By merging the pair with the smallest sum, order we approach. Always the leftmost such pair, we choose. # Approach 1. While the array is not sorted in non-decreasing order: - Find the adjacent pair with the minimum sum. - Merge them into one element (replace with the sum), reduce array size. - Repeat, until peace (sorting) is achieved. 2. Count how many such operations are needed. Patience and precision, the path to order is. # Complexity - Time complexity: $$O(n^2)$$ - Space complexity: $$O(1)$$ # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int x=0,b; while (nums.size()>1){ b=1; for (int i=1;i<nums.size();i++){ if (nums[i-1]>nums[i]){b=0;} } if (b==1){break;} x++; int ma=INT_MAX; for (int i=1;i<nums.size();i++){ if (nums[i]+nums[i-1]<ma){ma=nums[i-1]+nums[i];} } for (int i=1;i<nums.size();i++){ if (nums[i]+nums[i-1]==ma){ nums[i-1]=nums[i-1]+nums[i]; nums.erase(nums.begin()+i); break; } } } return x; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Easy to understand In-place Solution | Beats 100% time and space | C++
easy-to-understand-in-place-solution-bea-a8hn
IntuitionThe core idea is to simulate the process directly as described, modifying the input array in-place. We repeatedly find the adjacent pair with the small
pratiiik_p
NORMAL
2025-04-08T07:15:02.595378+00:00
2025-04-08T07:15:02.595378+00:00
51
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The core idea is to simulate the process directly as described, modifying the input array in-place. We repeatedly find the adjacent pair with the smallest sum (prioritizing the leftmost), merge them by updating the left element's value and effectively removing the right element by shifting subsequent elements within the original array. This continues until the array becomes non-decreasing, and we count the operations. # Approach 1. **Loop Condition:** Continuously perform operations while the array, considering its current effective size, is not non-decreasing. Keep track of the operation count (`res`). 2. **Find Min Pair:** In each iteration, scan adjacent pairs `(nums[i-1], nums[i])` within the current effective size. Identify the pair with the minimum sum, prioritizing the leftmost pair (smallest `i`) in case of ties. Let `min_idx` be the index of the second element (`nums[i]`) in this pair. 3. **In-Place Merge & Shrink:** * Update the left element of the pair with the sum: `nums[min_idx-1] += nums[min_idx]`. * Effectively remove the right element (`nums[min_idx]`) by shifting all subsequent elements one position to the left. * Decrement the effective size of the array and increment the operation count `res`. 4. **Return Count:** When the loop terminates (array is non-decreasing), return the total count `res`. ## Example Walkthrough (`nums = [5, 2, 3, 1]`) 1. **Initial:** `nums = [5, 2, 3, 1]`, `current_size = 4`, `res = 0`. Array is not non-decreasing. 2. **Iteration 1:** * Pairs & Sums: `(5,2)` sum=7; `(2,3)` sum=5; `(3,1)` sum=4. * Minimum sum is 4 for pair `(3,1)`. `min_idx = 3` (index of `1`). * Merge: `nums[min_idx-1] = nums[2] += nums[3]`. `nums[2]` becomes `3 + 1 = 4`. Array state: `[5, 2, 4, 1]`. * Shift: Element at index `min_idx` (which is 3) needs to be overwritten. Since it's the last element, no shift is practically needed, but the effective size decreases. * `current_size` becomes 3. `res` becomes 1. * Check `is_increasing` for effective array `[5, 2, 4]`: Returns `false` (because 2 < 5). 3. **Iteration 2:** * Pairs & Sums (within effective size 3): `(5,2)` sum=7; `(2,4)` sum=6. * Minimum sum is 6 for pair `(2,4)`. `min_idx = 2` (index of `4`). * Merge: `nums[min_idx-1] = nums[1] += nums[2]`. `nums[1]` becomes `2 + 4 = 6`. Array state: `[5, 6, 4, 1]`. * Shift: Element at index `min_idx` (which is 2) needs to be overwritten. `nums[2] = nums[3]` (conceptually, as `current_size` will shrink). * `current_size` becomes 2. `res` becomes 2. * Check `is_increasing` for effective array `[5, 6]`: Returns `true`. 4. **Terminate:** The `while` loop condition `!is_increasing(nums, current_size)` is now false. 5. **Return:** `res = 2`. # Complexity - Time complexity: $$O(N^2)$$ - Where n -> size of nums. <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool is_increasing(vector <int> &arr, int curr_n){ for(int i=1; i<curr_n; i++){ if(arr[i]<arr[i-1])return false; } return true; } int minimumPairRemoval(vector<int>& nums) { int n = nums.size(); if(n==1) return 0; int res = 0; int current_size = n; // Loop until the array becomes non-decreasing while(!is_increasing(nums, current_size)){ int min_idx = 1; int min = nums[0]+nums[1]; int sum; // Find the leftmost adjacent pair with the minimum sum for(int i=1; i<current_size; i++){ sum = nums[i]+nums[i-1]; if(sum<min){ min_idx = i; min = sum; } } // Perform the merge: add the value of the second element to the first nums[min_idx-1]+=nums[min_idx]; // Shift elements to remove the second element of the pair for(int j=min_idx; j<(current_size-1); j++){ nums[j] = nums[j+1]; } res++; // Increment the operation count current_size--; // Decrease the effective size of the array } return res; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Modifying input Array O(1) space compelxity beats 100% with proof
modifying-input-array-o1-space-compelxit-vkui
IntuitionMODIFYING INPUT ARRAYApproachBRUTEComplexity Time complexity: O(N^2) Space complexity: O(1)// //Code
Dhanusubramanir
NORMAL
2025-04-08T02:50:15.173083+00:00
2025-04-08T02:50:15.173083+00:00
65
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> MODIFYING INPUT ARRAY # Approach <!-- Describe your approach to solving the problem. --> BRUTE # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(N^2) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) // ![Screenshot (20).png](https://assets.leetcode.com/users/images/d8e4dec9-7f92-469e-8db1-5092daabfdce_1744080556.7837198.png) // # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { int count=0; while(!issorted(nums)){ nums=min(nums); count++; } return count; } boolean issorted(int []nums){ for(int i=0;i<nums.length-1;i++){ if(nums[i]>nums[i+1])return false; } return true; } int [] min(int nums[]){ int i=0,j=1,min=Integer.MAX_VALUE,idx=-1; while(j<nums.length){ int sum=nums[i]+nums[j]; if(sum<min){ min=sum; idx=i; } i++; j++; } nums[idx]=min; for(i=idx+1;i<nums.length-1;i++){ nums[i]=nums[i+1]; } return Arrays.copyOfRange(nums,0,i); } } ```
1
0
['Java']
1
minimum-pair-removal-to-sort-array-i
Simple & Easy to understand code
simple-easy-to-understand-code-beats-100-2j1a
Approach Use a loop to check if the list and the sorted list are the same find the minimum sum (minsum) and the index (mini) remove the mini+1 set nums[mini] =
rishisdev
NORMAL
2025-04-07T17:11:45.918221+00:00
2025-04-08T06:39:32.389759+00:00
25
false
# Approach <!-- Describe your approach to solving the problem. --> 1. Use a loop to check if the list and the sorted list are the same 2. find the minimum sum (minsum) and the index (mini) 3. remove the mini+1 4. set nums[mini] = minsum 5. increment count 6. return count # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n^2) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```python3 [] class Solution: def findminsum(self, nums: List[int]): minsum,mini = float("inf"),0 for i in range(len(nums)-1): if minsum > nums[i] + nums[i+1] : minsum = nums[i] + nums[i+1] mini = i return minsum,mini def minimumPairRemoval(self, nums: List[int]) -> int: count = 0 while nums != sorted(nums): minsum,mini = self.findminsum(nums) nums.pop(mini+1) nums[mini] = minsum count +=1 return count ```
1
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Simple C++ Solution. Beats 100%
simple-c-solution-beats-100-by-user9127h-nh4x
IntuitionSince we need to make the array non-decreasing, combining adjacent elements with the smallest sum (often involving negative numbers or smaller values)
indefatigable05
NORMAL
2025-04-07T13:37:44.027015+00:00
2025-04-07T13:38:51.285479+00:00
44
false
# Intuition Since we need to make the array non-decreasing, combining adjacent elements with the smallest sum (often involving negative numbers or smaller values) will likely lead to the most efficient path toward a sorted array. # Approach Handle edge cases first: arrays of size 0 or 1 are already non-decreasing (I missed out on this when i first submitted the solution). Use a while loop to repeatedly perform operations until the array becomes non-decreasing: 1. Check if the array is already non-decreasing (return if true) 2. Find the adjacent pair with minimum sum 3. Replace the pair with their sum (set first element to sum, remove second element) 4. After each operation, recheck if the array is non-decreasing Continue until the array is sorted or only one element remains # Complexity - Time complexity: O(n^2) - Space complexity: O(n) # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int operations = 0; if (nums.size() <= 1) { return 0; } while(nums.size() > 1){ bool isNonDecreasing = true; for (int i = 1; i < nums.size(); i++) { if (nums[i] < nums[i-1]) { isNonDecreasing = false; break; } } if (isNonDecreasing) { return operations; // Already sorted } int minSum =nums[0] + nums[1]; int minIndex = 0; for(int i = 1; i< nums.size() -1 ; i+=1){ if(nums[i]+nums[i+1] < minSum){ minSum = nums[i]+nums[i+1]; minIndex = i; } } nums[minIndex] = minSum; nums.erase(nums.begin() + minIndex + 1); operations +=1; } return operations ; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Easy Java Solution - Beats 100%
easy-java-solution-beats-100-by-ruch21-ea7c
Code
ruch21
NORMAL
2025-04-07T12:37:12.297056+00:00
2025-04-07T12:37:12.297056+00:00
76
false
# Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { ArrayList<Integer> newNums = new ArrayList<>(); for(int i=0; i<nums.length; i++) { newNums.add(nums[i]); } int countOps = 0; while(!isSorted(newNums)) { int minSum = newNums.get(0) + newNums.get(1); int idx1 = 0; for(int i=2 ; i<newNums.size(); i++) { if(newNums.get(i-1)+newNums.get(i) < minSum) { minSum = newNums.get(i-1) + newNums.get(i); idx1 = i-1; } } newNums.remove(idx1); newNums.remove(idx1); newNums.add(idx1, minSum); countOps++; } return countOps; } public boolean isSorted(ArrayList<Integer> nums) { for(int i=1; i<nums.size(); i++) { if(nums.get(i-1) > nums.get(i)) { return false; } } return true; } public void printArr(ArrayList<Integer> nums) { for(int i=0; i<nums.size(); i++) { System.out.print(nums.get(i)); } System.out.println(); } } ```
1
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Java || Brute force
java-brute-force-by-pranav_1817-s0im
Intuition Simulate the entire process. Approach initialize the count variable to 0. traverse the array to find the array with minSum. let pair be [index1, index
pranav_1817
NORMAL
2025-04-07T08:48:31.917337+00:00
2025-04-07T08:48:31.917337+00:00
42
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> 1. Simulate the entire process. # Approach <!-- Describe your approach to solving the problem. --> 1. initialize the count variable to 0. 2. traverse the array to find the array with minSum. 3. let pair be `[index1, index2]`. put minSum at index1 and remove element at index2. and increment the count. 4. continue this until array is sorted or only one element is remaining in the array. 5. return count. # Complexity - Time complexity:$$O(n) + O((3*n)*n)$$ > *1. $$O(n)$$ for copying all the elements in list.* > *2. $$O(3*n)$$. one O(n) for `isSorted()` funciton, one O(n) for finding minSum index and one O(n) for removing elements in the list.* > *3. in worst case senario we will executed all three function (isSorted, findMin index, remove element in list) n-1 times.* > *here $$O((3*n)*n)$$ is not exact as for every subsequent loop size of list is decreasing.* <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n)$$ for creating list. > *we can perform all the operation on original list, but it is not encourage in interview process to mutate/chance the input data structure.* <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public boolean isSorted(List<Integer> list){ for(int i = 1; i< list.size(); i++){ if(list.get(i)<list.get(i-1)) return false; } return true; } public int minimumPairRemoval(int[] nums) { List<Integer> temp = new ArrayList<>(); for(int ele: nums) temp.add(ele); int count = 0; while(temp.size() > 1 && !isSorted(temp)){ int minSum = Integer.MAX_VALUE; int index1 = -1; int index2 = -1; for(int i = 0; i < temp.size()-1; i++){ int tempSum = temp.get(i)+temp.get(i+1); if(tempSum < minSum){ minSum = tempSum; index1 = i; index2 = i+1; } } temp.set(index2,minSum); temp.remove(index1); count++; } return count; } } ``` > ***if helpful please upvote. ๐Ÿ˜Š comment if you have any suggestions.***
1
0
['Array', 'Java']
0
minimum-pair-removal-to-sort-array-i
Highly Readable Code with 3 functions
highly-readable-code-with-3-functions-by-rsvv
IntuitionApproachGet min Pair returns the first index of the minimum pair. This index can be used to pop both values while also using the same index to insert t
uhyoob
NORMAL
2025-04-06T19:44:52.181528+00:00
2025-04-06T19:44:52.181528+00:00
16
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> Get min Pair returns the first index of the minimum pair. This index can be used to pop both values while also using the same index to insert the new sum. The reason the same index can be used for all 3 operations is that the array keeps shifting to that index of interest. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> In the worst case O(n^2) since array.pop takes n time and there is a while loop that could take n/2 time in the worst case (when max operations are needed) This worst case is unlikely though. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def isNotSorted(nums: List[int]): prev = nums[0] for n in nums: if prev>n: return True prev = n return False def getMinPair(nums: List[int]): mSum = sys.maxsize ind = -1 for i in range(len(nums)-1): sum = nums[i] + nums[i+1] if mSum > sum: mSum = sum ind = i return ind def minimumPairRemoval(self, nums: List[int]) -> int: ops = 0 while Solution.isNotSorted(nums): ind = Solution.getMinPair(nums) n1 = nums.pop(ind) n2 = nums.pop(ind) nums.insert(ind,n1+n2) ops +=1 return ops ```
1
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
dont overthink
dont-overthink-by-verciel-lb13
Approachsimple simulation of problem statementCode
verciel_
NORMAL
2025-04-06T19:44:48.960065+00:00
2025-04-06T19:44:48.960065+00:00
10
false
# Approach <!-- Describe your approach to solving the problem. --> simple simulation of problem statement # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int ans=0; while(true) { //check if array is non decreasing int n=nums.size(); bool flag=false; for(int i=0;i<n-1;i++) { if(nums[i]>nums[i+1]) { flag=true; break; } } if(!flag) break; //find the minimum and simulate int sum=INT_MAX,index; for(int i=0;i<n-1;i++) { if(nums[i]+nums[i+1] < sum) { sum=nums[i]+nums[i+1]; index=i; } } nums.erase(nums.begin()+index+1); nums[index]=sum; ans++; } return ans; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Clean Simulation Brute Force solution beats 100% runtime [C++]
clean-simulation-brute-force-solution-be-m9t0
Complexity Time complexity: O(n2) Space complexity: O(1) Code
khooinguyeen
NORMAL
2025-04-06T14:07:27.069118+00:00
2025-04-06T14:07:27.069118+00:00
35
false
# Complexity - Time complexity: $$ O(n^2)$$ - Space complexity: $$ O(1) $$ # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int operations = 0; while (!isSorted(nums)) { int minSum = minPair(nums); for (int i = 1; i < nums.size(); i++) { int sum = nums[i] + nums[i - 1]; if (sum == minSum) { nums[i - 1] = sum; nums.erase(nums.begin() + i); operations++; break; } } } return operations; } private: bool isSorted(vector<int>& nums) { for (int i = 1; i < nums.size(); i++) { if (nums[i] < nums[i - 1]) return false; } return true; } int minPair(vector<int>& nums) { int minSum = 100000; for (int i = 1; i < nums.size(); i++) { int sum = nums[i] + nums[i - 1]; minSum = min(minSum, sum); } return minSum; } }; ```
1
0
['Array', 'Simulation', 'C++']
0
minimum-pair-removal-to-sort-array-i
0ms 100% (Quad)
0ms-100-quad-by-michelusa-nwec
Keep enumerating until sorting is done. Remember to find the minimum sum for the entire current array.Time complexity is quadratic.Code
michelusa
NORMAL
2025-04-06T12:54:38.271996+00:00
2025-04-06T12:54:38.271996+00:00
41
false
Keep enumerating until sorting is done. Remember to find the minimum sum for the entire current array. Time complexity is quadratic. # Code ```cpp [] class Solution { int find_min_sum(const std::vector<int>& nums) { int min_sum = std::numeric_limits<int>::max(); int min_start = 0; for (int j = 0; j < nums.size() - 1; ++j) { const int sum = nums[j] + nums[j + 1]; if (sum < min_sum) { min_sum = nums[j] + nums[j + 1]; min_start = j; } } return min_start; } public: int minimumPairRemoval(vector<int>& nums) { int operations = 0; bool done = false; while (!done) { done = true; for (int i = 1; i < nums.size(); ++i) { if (nums[i] < nums[i - 1]) { done = false; ++operations; // Replace two elements with sum. const int merge_idx = find_min_sum(nums); nums[merge_idx] = nums[merge_idx] + nums[merge_idx + 1]; nums.erase(nums.begin() + merge_idx + 1); break; } } } return operations; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
100 percent Affective Code
100-percent-affective-code-by-anuragk2-n8in
IntuitionApproachComplexity Time complexity: O(n^2) Space complexity: O(n) Code
anuragk2
NORMAL
2025-04-06T11:43:23.544772+00:00
2025-04-06T11:43:23.544772+00:00
83
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n^2) - Space complexity: O(n) # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { int os = 0; while (true) { boolean sSted = true; for (int d = 1; d < nums.length; d++) { if (nums[d] < nums[d - 1]) { sSted = false; break; } } if (sSted) break; int mim = Integer.MAX_VALUE, ix = -1; for (int x = 0; x< nums.length - 1; x++) { int um = nums[x] + nums[x + 1]; if (um < mim) { mim = um; ix = x; } } int[] nems = new int[nums.length - 1]; for (int b = 0, z = 0; b< nums.length; b++) { if (b == ix) { nems[z++] = nums[b] + nums[b + 1]; b++; } else { nems[z++] = nums[b]; } } nums = nems; os++; } return os; } public static int[] parseInput(String ict) { ict = ict.replaceAll("[\\[\\]\\s]", ""); String[] pts = ict.split(","); int[] nums = new int[pts.length]; for (int s = 0; s < pts.length; s++) { nums[s] = Integer.parseInt(pts[s]); } return nums; } } ```
1
0
['Java']
0
minimum-pair-removal-to-sort-array-i
100 percent Affective Code
100-percent-affective-code-by-anuragk2-0lke
IntuitionApproachComplexity Time complexity: O(n^2) Space complexity: O(n) Code
anuragk2
NORMAL
2025-04-06T11:43:16.557159+00:00
2025-04-06T11:43:16.557159+00:00
20
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n^2) - Space complexity: O(n) # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { int os = 0; while (true) { boolean sSted = true; for (int d = 1; d < nums.length; d++) { if (nums[d] < nums[d - 1]) { sSted = false; break; } } if (sSted) break; int mim = Integer.MAX_VALUE, ix = -1; for (int x = 0; x< nums.length - 1; x++) { int um = nums[x] + nums[x + 1]; if (um < mim) { mim = um; ix = x; } } int[] nems = new int[nums.length - 1]; for (int b = 0, z = 0; b< nums.length; b++) { if (b == ix) { nems[z++] = nums[b] + nums[b + 1]; b++; } else { nems[z++] = nums[b]; } } nums = nems; os++; } return os; } public static int[] parseInput(String ict) { ict = ict.replaceAll("[\\[\\]\\s]", ""); String[] pts = ict.split(","); int[] nums = new int[pts.length]; for (int s = 0; s < pts.length; s++) { nums[s] = Integer.parseInt(pts[s]); } return nums; } } ```
1
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Simple C++ Solution | Weekly Contest 444
simple-c-solution-weekly-contest-444-by-t9s7i
IntuitionComplexity Time complexity: O(n2) Space complexity: O(1) Code
ipriyanshi
NORMAL
2025-04-06T10:48:50.410997+00:00
2025-04-06T10:48:50.410997+00:00
52
false
# Intuition https://youtu.be/35ay7vm2viY # Complexity - Time complexity: $$O(n^2)$$ - Space complexity: $$O(1)$$ # Code ```cpp [] class Solution { public: void shiftLeft(vector<int>& nums, int idx){ int n = nums.size(); for(int i = idx; i < n-1; i++){ nums[i] = nums[i+1]; } nums.pop_back(); } void mergePairs(vector<int>& nums){ int n = nums.size(); int minSum = INT_MAX, minIdx = -1; for(int i = 0; i < n-1; i++){ int sum = nums[i] + nums[i+1]; if(sum < minSum){ minSum = sum; minIdx = i; } } nums[minIdx] = minSum; shiftLeft(nums, minIdx+1); } bool isSorted(vector<int>& nums){ int n = nums.size(); for(int i = 0; i < n-1; i++){ if(nums[i+1] < nums[i]) return false; } return true; } int minimumPairRemoval(vector<int>& nums) { int result = 0; while(!isSorted(nums)){ mergePairs(nums); result++; } return result; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
โ˜• Java solution
java-solution-by-barakamon-xg6k
null
Barakamon
NORMAL
2025-04-06T10:39:16.917423+00:00
2025-04-06T10:39:16.917423+00:00
67
false
![Screenshot_1.png](https://assets.leetcode.com/users/images/7e7d101c-8001-45a1-b81e-16cc51d8440f_1743935952.9286087.png) ```java [] class Solution { public int minimumPairRemoval(int[] nums) { int n = nums.length; int ans = 0; while (!isSorted(nums, n)) { int minIdx = 0, minSum = Integer.MAX_VALUE; for (int i = 0; i < n - 1; i++) { int sum = nums[i] + nums[i + 1]; if (sum < minSum) { minSum = sum; minIdx = i; } } nums[minIdx] += nums[minIdx + 1]; for (int i = minIdx + 1; i < n - 1; i++) { nums[i] = nums[i + 1]; } n--; ans++; } return ans; } private boolean isSorted(int[] nums, int length) { for (int i = 0; i < length - 1; i++) { if (nums[i] > nums[i + 1]) return false; } return true; } } ```
1
0
['Java']
0
minimum-pair-removal-to-sort-array-i
it's work
its-work-by-bhav5sh-d9qg
IntuitionApproachComplexity Time complexity: Space complexity: Code
Bhav5sh
NORMAL
2025-04-06T08:18:37.272327+00:00
2025-04-06T08:18:37.272327+00:00
29
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: operation = 0 def is_non_decreasing(arr): return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) while not is_non_decreasing(nums): # find pair with min sum and left most index min_sum = float('inf') min_idx = 0 for i in range(len(nums) - 1): pair = nums[i] + nums[i + 1] if pair < min_sum: min_sum = pair min_idx = i merged = nums[min_idx] + nums[min_idx + 1] nums = nums[:min_idx] + [merged] + nums[min_idx + 2:] operation += 1 return operation ```
1
0
['Greedy', 'Simulation', 'Python3']
0
minimum-pair-removal-to-sort-array-i
Simplest Approach, Beats 100%
simplest-approach-beats-100-by-dhruv_003-e4wx
IntuitionApproachComplexity Time complexity: Space complexity: Code
Dhruv_0036
NORMAL
2025-04-06T04:42:21.535547+00:00
2025-04-06T04:42:21.535547+00:00
103
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int ans = 0; while(true) { vector<int> temp = nums; sort(temp.begin(),temp.end()); if(nums==temp) return ans; vector<vector<int>> arr; for(int i=0; i<nums.size()-1; i++) { int x = nums[i] + nums[i+1]; arr.push_back({x,i}); } sort(arr.begin(), arr.end()); int sum = arr[0][0]; int idx = arr[0][1]; nums[idx] = sum; nums.erase(nums.begin()+idx+1); ans++; } return ans; } }; ```
1
0
['Math', 'Greedy', 'C++']
0
minimum-pair-removal-to-sort-array-i
Easy Java Solution
easy-java-solution-by-vermaanshul975-8h65
IntuitionApproachComplexity Time complexity: Space complexity: Code
vermaanshul975
NORMAL
2025-04-06T04:42:02.245747+00:00
2025-04-06T04:42:02.245747+00:00
166
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { List<Integer> l = new ArrayList<>(); for(int num:nums) l.add(num); int count = 0; while(!solve(l)){ int minSum = Integer.MAX_VALUE; int index = 0; for(int i = 0 ;i<l.size()-1;i++){ int sum = l.get(i) + l.get(i+1); if(minSum>sum){ minSum = sum; index = i; } } int merg = l.get(index) + l.get(index+1); l.remove(index+1); l.set(index,merg); count++; } return count; } public boolean solve(List<Integer> l){ for(int i = 0;i<l.size()-1;i++){ if(l.get(i)>l.get(i+1)) return false; } return true; } } ```
1
0
['Java']
1
minimum-pair-removal-to-sort-array-i
Brute Force - Simple Solution - Easy to Understand - Python/Java/C++
brute-force-simple-solution-easy-to-unde-gk8w
IntuitionApproachComplexity Time complexity: Space complexity: Code
cryandrich
NORMAL
2025-04-06T04:38:36.631948+00:00
2025-04-06T04:38:36.631948+00:00
34
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] def is_sorted(arr): return all(arr[i] <= arr[i+1] for i in range(len(arr) - 1)) class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: ops = 0 while len(nums) > 1 and not is_sorted(nums): arr = nums[:] min_sum = float('inf') min_ind = 0 for i in range(len(arr) - 1): pair_sum = arr[i] + arr[i + 1] if pair_sum < min_sum: min_sum = pair_sum min_ind = i merged_val = arr[min_ind] + arr[min_ind + 1] new_arr = arr[:min_ind] + [merged_val] + arr[min_ind + 2:] nums = new_arr ops += 1 return ops ``` ```cpp [] class Solution { private: bool isSorted(const vector<int>& arr) { for (size_t i = 0; i < arr.size() - 1; ++i) { if (arr[i] > arr[i + 1]) { return false; } } return true; } public: int minimumPairRemoval(vector<int>& nums) { int ops = 0; while (nums.size() > 1 && !isSorted(nums)) { vector<int> arr = nums; int minSum = INT_MAX; int minInd = -1; for (size_t i = 0; i < arr.size() - 1; ++i) { int pairSum = arr[i] + arr[i + 1]; if (pairSum < minSum) { minSum = pairSum; minInd = i; } } int mergedVal = arr[minInd] + arr[minInd + 1]; vector<int> newArr; for (int i = 0; i < minInd; ++i) { newArr.push_back(arr[i]); } newArr.push_back(mergedVal); for (size_t i = minInd + 2; i < arr.size(); ++i) { newArr.push_back(arr[i]); } nums = newArr; ops += 1; } return ops; } }; ``` ```java [] class Solution { private boolean isSorted(List<Integer> arr) { for (int i = 0; i < arr.size() - 1; i++) { if (arr.get(i) > arr.get(i + 1)) { return false; } } return true; } public int minimumPairRemoval(int[] nums) { List<Integer> listNums = new ArrayList<>(); for (int num : nums) { listNums.add(num); } int ops = 0; while (listNums.size() > 1 && !isSorted(listNums)) { List<Integer> arr = new ArrayList<>(listNums); int minSum = Integer.MAX_VALUE; int minInd = -1; for (int i = 0; i < arr.size() - 1; i++) { int pairSum = arr.get(i) + arr.get(i + 1); if (pairSum < minSum) { minSum = pairSum; minInd = i; } } if (minInd != -1) { int mergedVal = arr.get(minInd) + arr.get(minInd + 1); List<Integer> newArr = new ArrayList<>(); for (int i = 0; i < minInd; i++) { newArr.add(arr.get(i)); } newArr.add(mergedVal); for (int i = minInd + 2; i < arr.size(); i++) { newArr.add(arr.get(i)); } listNums.clear(); listNums.addAll(newArr); ops += 1; } else { break; } } return ops; } } ```
1
0
['Array', 'C++', 'Java', 'Python3']
0
minimum-pair-removal-to-sort-array-i
Simple and Easy || Beats 100% ๐Ÿ’ฏ๐Ÿ’ช||Just follow the instructions and ur their ๐Ÿš€ || C++
simple-and-easy-beats-100-just-follow-th-5qtl
IntuitionApproachComplexity Time complexity: Space complexity: Code
CodeWithMithun
NORMAL
2025-04-06T04:23:41.090485+00:00
2025-04-06T04:23:41.090485+00:00
49
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] // class Solution { // public: // int minimumPairRemoval(vector<int>& nums) { // } // }; class Solution { public: bool isNonDecreasing(const vector<int>& nums) { for (int i = 0; i + 1 < nums.size(); ++i) if (nums[i] > nums[i + 1]) return false; return true; } int minimumPairRemoval(vector<int>& nums) { int ops = 0; while (!isNonDecreasing(nums)) { int minSum = INT_MAX; int index = -1; for (int i = 0; i + 1 < nums.size(); ++i) { int sum = nums[i] + nums[i + 1]; if (sum < minSum) { minSum = sum; index = i; } } // Merge nums[index] and nums[index + 1] int merged = nums[index] + nums[index + 1]; nums.erase(nums.begin() + index, nums.begin() + index + 2); nums.insert(nums.begin() + index, merged); ++ops; } return ops; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Iterators Abuse | O(N ^ 2) | Rust
iterators-abuse-on-2-rust-by-prog_jacob-a5jl
Complexity Time complexity: O(n2) Space complexity: O(n) I think.. Code
Prog_Jacob
NORMAL
2025-04-06T04:19:49.058425+00:00
2025-04-06T04:19:49.058425+00:00
23
false
# Complexity - Time complexity: $$O(n ^ 2)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n)$$ I think.. <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```rust [] impl Solution { pub fn minimum_pair_removal(mut nums: Vec<i32>) -> i32 { let mut ans = 0; while nums.len() > 1 { if nums.windows(2).all(|w| w[0] <= w[1]) { break }; let sums = nums.windows(2).map(|w| w[0] + w[1]).enumerate(); let (minn, minx) = sums.clone().min_by_key(|(_, x)| *x).unwrap(); nums = nums.iter().enumerate().filter(|&(i, x)| i != minn).map(|(i, &x)| { if i == minn + 1 { minx } else { x } }).collect::<Vec<i32>>(); ans += 1; } ans } } ```
1
0
['Rust']
0
minimum-pair-removal-to-sort-array-i
SIMPLE EASY APPROACH WITH BASIC IDEA USING PYTHON FUNCTIONS
simple-easy-approach-with-basic-idea-usi-f3gh
IntuitionApproachComplexity Time complexity: Space complexity: Code
Yathish_2006
NORMAL
2025-04-06T04:17:56.638693+00:00
2025-04-06T04:17:56.638693+00:00
54
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: count=0 while nums!=[] and sorted(nums)!=nums: min_sum=float('inf') min_ind=-1 for i in range(len(nums)-1): sum=nums[i]+nums[i+1] if(min_sum>nums[i]+nums[i+1]): min_sum=sum min_ind=i nums=nums[:min_ind]+[nums[min_ind]+nums[min_ind+1]]+nums[min_ind+2:] print(nums) count+=1 return count ```
1
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Python - solved during contest
python-solved-during-contest-by-kaitav-0x92
IntuitionDumb brute forceComplexity Time complexity: O(N2) Space complexity: O(1) Code
kaitav
NORMAL
2025-04-06T04:13:31.143489+00:00
2025-04-06T04:13:31.143489+00:00
35
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Dumb brute force # Complexity - Time complexity: O(N2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def minimumPairRemoval(self, nums): """ :type nums: List[int] :rtype: int """ ans = 0 sorted = False while not sorted: sorted = True idx = 0 min_sum = 100000000 for i in range(1, len(nums)): if nums[i-1] > nums[i]: sorted = False if nums[i-1] + nums[i] < min_sum: idx = i-1 min_sum = nums[i-1] + nums[i] if not sorted: nums[idx] = min_sum nums = nums[:idx+1] + nums[idx+2:] ans += 1 return ans ```
1
0
['Python']
0
minimum-pair-removal-to-sort-array-i
๐Ÿ”ฅClear & Concise Code | C++
clear-concise-code-c-by-leadingtheabyss-cr5o
C++
LeadingTheAbyss
NORMAL
2025-04-06T04:08:19.224397+00:00
2025-04-06T04:08:19.224397+00:00
32
false
# C++ ```cpp class Solution { public: int minimumPairRemoval(vector<int>& nums) { int n = nums.size(), ans = 0; while(!is_sorted(nums.begin(), nums.end())) { int curr = 0, sum = INT_MAX; for(int i = 0; i < n - 1; ++i) if(nums[i] + nums[i + 1] < sum) curr = i, sum = nums[i] + nums[i + 1]; vector<int> res; for(int i = 0; i < curr; ++i) res.push_back(nums[i]); res.push_back(nums[curr] + nums[curr + 1]); for(int i = curr + 2; i < n; ++i) res.push_back(nums[i]); swap(nums, res); --n, ++ans; } return ans; } }; ```
1
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Minimum Pair Removal to Sort Array I
minimum-pair-removal-to-sort-array-i-by-4ktle
IntuitionApproachComplexity Time complexity: Space complexity: Code
yogibhav777
NORMAL
2025-04-12T09:13:33.242612+00:00
2025-04-12T09:13:33.242612+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: def isAsc(nums): return all(nums[i]<=nums[i+1] for i in range(len(nums)-1)) cnt=0 while not isAsc(nums): min_sum = float('inf') min_index = -1 for i in range(len(nums)-1): if nums[i]+nums[i+1]<min_sum: min_sum = nums[i]+nums[i+1] min_index = i nums = nums[:min_index]+[min_sum]+nums[min_index+2:] cnt+=1 return cnt ```
0
0
['Array', 'Simulation', 'Python3']
0
minimum-pair-removal-to-sort-array-i
0ms - simple approach
0ms-simple-approach-by-bankachara999-87qh
IntuitionApproachComplexity Time complexity: O(n^2) Space complexity: O(1) Code
bankachara999
NORMAL
2025-04-12T08:19:34.761445+00:00
2025-04-12T08:19:34.761445+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n^2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {number[]} nums * @return {number} */ var minimumPairRemoval = function (nums) { function isNonDecreasingArray(nums) { for (let i = 0; i < nums.length - 1; i++) { if (nums[i] > nums[i + 1]) return false } return true } let count = 0; while (!isNonDecreasingArray(nums)) { let minIndex = 0; let minSum = Infinity; for (let i = 0; i < nums.length - 1; i++) { let pairSum = nums[i] + nums[i + 1]; if (pairSum < minSum) { minSum = pairSum; minIndex = i } } // nums[minIndex] = minSum; nums.splice(minIndex, 2, minSum); count++ } return count }; ```
0
0
['Array', 'Simulation', 'JavaScript']
0
minimum-pair-removal-to-sort-array-i
Simple Python solution
simple-python-solution-by-adripope-zgj3
Code
Adripope
NORMAL
2025-04-11T19:57:30.102049+00:00
2025-04-11T19:57:30.102049+00:00
2
false
# Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: if nums == sorted(nums): return 0 c=0 while nums != sorted(nums): lst = min([(i, j, idx) for idx, (i, j) in enumerate(zip(nums, nums[1:]))], key=lambda p: p[0] + p[1]) idx = lst[-1] nums = nums[:idx] + [lst[0] + lst[1]] + nums[idx + 2 :] c += 1 return c ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Minimum pair removal
minimum-pair-removal-by-ankitair-g50g
IntuitionApproachComplexity Time complexity: Space complexity: Code
AnkitAIR
NORMAL
2025-04-11T19:26:04.738818+00:00
2025-04-11T19:26:04.738818+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def minimumPairRemoval(self, nums): operations = 0 # Keep doing the operation until the array is non-decreasing while not self.isNonDecreasing(nums): min_sum = float('inf') min_index = -1 # Find the leftmost pair with the minimum sum for i in range(len(nums) - 1): pair_sum = nums[i] + nums[i + 1] if pair_sum < min_sum: min_sum = pair_sum min_index = i # Replace the pair with their sum nums = nums[:min_index] + [nums[min_index] + nums[min_index + 1]] + nums[min_index + 2:] operations += 1 return operations def isNonDecreasing(self, nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: return False return True # Example usage sol = Solution() print(sol.minimumPairRemoval([5, 2, 3, 1])) # Output: 2 print(sol.minimumPairRemoval([1, 2, 2])) # Output: 0 ```
0
0
['Python']
0
minimum-pair-removal-to-sort-array-i
VERY EASY SOLUTION(C++)
very-easy-solutionc-by-dogra_51-vjhi
IntuitionApproachFind the smallest consecutive pair by their sum.Merge this pair and repeat until the array is non-decreasing.Track the number of operations.Com
dogra_51
NORMAL
2025-04-11T17:45:40.461345+00:00
2025-04-11T17:45:40.461345+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> Find the smallest consecutive pair by their sum. Merge this pair and repeat until the array is non-decreasing. Track the number of operations. # Complexity - Time complexity:O(n^2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool decrese(vector<int>&nums){ for(int i = 1;i<nums.size();i++){ if(nums[i]<nums[i-1]){ return false; } } return true; } int minimumPairRemoval(vector<int>& nums) { int count= 0; while(!decrese(nums)){ int min = INT_MAX; int index= -1; for(int i = 0;i<nums.size()-1;i++){ int sum = nums[i]+nums[i+1]; if(sum<min){ min= sum; index=i; } } vector<int>temp; for(int i=0;i<nums.size();i++){ if(i==index){ temp.push_back(nums[i]+nums[i+1]); i++; } else temp.push_back(nums[i]); } nums=temp; count++; } return count; } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Beats 100.00% solution
beats-10000-solution-by-developersuserna-e18m
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n) Code
DevelopersUsername
NORMAL
2025-04-11T15:11:57.919040+00:00
2025-04-11T15:11:57.919040+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { int ans = 0; while (!isNonDecreasing(nums)) { nums = dropPair(nums); ans++; } return ans; } private static boolean isNonDecreasing(int[] nums) { int prev = Integer.MIN_VALUE; for (int num : nums) if (prev > num) return false; else prev = num; return true; } private static int[] dropPair(int[] nums) { int minIndex = getMinIndex(nums), n = nums.length; if (minIndex == -1) return nums; nums[minIndex] = nums[minIndex] + nums[minIndex + 1]; int[] copy = new int[n - 1]; System.arraycopy(nums, 0, copy, 0, minIndex + 1); System.arraycopy(nums, minIndex + 2, copy, minIndex + 1, n - minIndex - 2); return copy; } private static int getMinIndex(int[] nums) { int min = Integer.MAX_VALUE, minIndex = -1; for (int i = 0; i < nums.length - 1; i++) { int sum = nums[i] + nums[i + 1]; if (sum < min) { min = sum; minIndex = i; } } return minIndex; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
EASY C++ SOLUTION ๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜
easy-c-solution-by-complex_aayush-v1rh
IntuitionApproachComplexity Time complexity: Space complexity: Code
complex_aayush
NORMAL
2025-04-11T12:30:06.912482+00:00
2025-04-11T12:30:06.912482+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool isNondecreasing(const vector<int>& nums) { for (int i = 1; i < nums.size(); i++) { if (nums[i] < nums[i - 1]) return false; } return true; } int minimumPairRemoval(vector<int>& nums) { int ops = 0; while (!isNondecreasing(nums)) { int minSum = INT_MAX; int minIndex = -1; // Find the adjacent pair with the minimum sum for (int i = 0; i < nums.size() - 1; i++) { int pairSum = nums[i] + nums[i + 1]; if (pairSum < minSum) { minSum = pairSum; minIndex = i; } } // Replace nums[minIndex] and nums[minIndex+1] with their sum int combined = nums[minIndex] + nums[minIndex + 1]; vector<int> newNums; for (int i = 0; i < nums.size(); i++) { if (i == minIndex) { newNums.push_back(combined); i++; // Skip the next one (i+1) } else { newNums.push_back(nums[i]); } } nums = newNums; ops++; } return ops; } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
[Python/C++/C/Go] O(Nยฒ )
python-on2-by-lotceedoo-1fey
null
lotceedoo
NORMAL
2025-04-11T09:21:56.799190+00:00
2025-04-12T02:09:30.963728+00:00
4
false
```Python3 [] def minimumPairRemoval(self, nums): res = 0 while any(a > b for a, b in pairwise(nums)): sums = list(map(sum, pairwise(nums))) num = min(sums) i = sums.index(num) nums = nums[:i] + [num] + nums[i + 2 :] res += 1 return res ``` ```python3 [] def minimumPairRemoval(self, nums): n = len(nums) while any(a > b for a, b in pairwise(nums)): num, i = min((sum(p), i) for i, p in enumerate(pairwise(nums))) nums = nums[:i] + [num] + nums[i + 2 :] return n - len(nums) ``` ```Python3 [] def minimumPairRemoval(self, nums): if all(a <= b for a, b in pairwise(nums)): return 0 num, i = min((sum(p), i) for i, p in enumerate(pairwise(nums))) return self.minimumPairRemoval(nums[:i] + [num] + nums[i + 2 :]) + 1 ``` ```C++ [] int minimumPairRemoval(vector<int>& nums) { int res; for (res = 0; !is_sorted(nums.begin(), nums.end()); ++res) { int tot = 50001, cur, j; for (int i = 0; i < nums.size() - 1; ++i) if ((cur = nums[i] + nums[i + 1]) < tot) tot = cur, j = i; nums[j] = tot; for (int i = j + 1; i < nums.size() - 1; ++i) nums[i] = nums[i + 1]; nums.pop_back(); } return res; } ``` ```C [] int minimumPairRemoval(int* nums, int numsSize) { bool isSorted(int* nums, int n) { for (--n; n; --n) if (nums[n - 1] > nums[n]) return false; return true; } int res; for (res = 0; !isSorted(nums, numsSize); --numsSize, ++res) { int tot = 50001, cur, j; for (int i = 0; i < numsSize - 1; ++i) if ((cur = nums[i] + nums[i + 1]) < tot) tot = cur, j = i; nums[j] = tot; for (int i = j + 1; i < numsSize - 1; ++i) nums[i] = nums[i + 1]; } return res; } ``` ```Go [] func minimumPairRemoval(nums []int) int { var res int for res = 0; !sort.SliceIsSorted(nums, func(i, j int) bool { return nums[i] < nums[j] }); res++ { var ( tot = 50001 cur, j int ) for i := 0; i < len(nums)-1; i++ { cur = nums[i] + nums[i+1] if cur < tot { tot, j = cur, i } } nums[j] = tot nums = append(nums[:j+1], nums[j+2:]...) } return res } ```
0
0
['Simulation']
0
minimum-pair-removal-to-sort-array-i
Java Easy Solution - Runtime 3 ms Beats 62.75%
java-easy-solution-runtime-3-ms-beats-62-imzx
Code
iamsd_
NORMAL
2025-04-11T04:31:37.461336+00:00
2025-04-11T04:31:37.461336+00:00
3
false
# Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { List<Integer> l = new ArrayList<>(); for (int i : nums) { l.add(i); } int totalCount = 0; while (!checkSorted(l)) { int min = Integer.MAX_VALUE; int ind = 0; for (int i = 0; i < l.size() - 1; i++) { if (min > (l.get(i) + l.get(i + 1))) { min = (l.get(i) + l.get(i + 1)); ind = i; } } l.set(ind, min); l.remove(ind + 1); totalCount++; } return totalCount; } private boolean checkSorted(final List<Integer> list) { int len = list.size(); for (int i = 0; i < len - 1; i++) { if (list.get(i) > list.get(i + 1)) return false; } return true; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Easy Solution || Bruteforce
easy-solution-bruteforce-by-shrivarsha-b6wh
IntuitionApproachComplexity Time complexity: Space complexity: Code
Shrivarsha
NORMAL
2025-04-10T15:42:28.832959+00:00
2025-04-10T15:42:28.832959+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { int k=0; List<Integer> li = Arrays.stream(nums).boxed().collect(Collectors.toList()); while(!isSorted(li)) { k++; int minId=-1; int sum=0; int min=Integer.MAX_VALUE; for(int i=0;i<li.size()-1;i++) { sum=li.get(i)+li.get(i+1); if(sum<min) { min=sum; minId=i; } } li.remove(minId); li.remove(minId); li.add(minId,min); System.out.println("Step " + k + ": " + li); } return k; } public boolean isSorted(List<Integer>li) { int n=li.size(); for(int i=1;i<n;i++) { if(li.get(i-1)>li.get(i)) return false; } return true; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
3507. Minimum Pair Removal to Sort Array I
3507-minimum-pair-removal-to-sort-array-7cnoo
IntuitionApproachComplexity Time complexity: Space complexity: Code
MleZ4ajbHK
NORMAL
2025-04-10T09:17:30.068439+00:00
2025-04-10T09:17:30.068439+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] import java.util.*; class Solution { public static void main(String[] args) { Solution solution = new Solution(); int[] nums = {5, 2, 3, 1}; System.out.println(solution.minimumPairRemoval(nums)); } public int minimumPairRemoval(int[] nums) { int result = 0; List<Integer> newList = new ArrayList<>(); for (int num : nums) { newList.add(num); } while (!checkArray(newList)) { int maxSum = Integer.MAX_VALUE; int minIndex = -1; for (int j = 0; j < newList.size() - 1; j++) { int sum = newList.get(j) + newList.get(j + 1); if (sum < maxSum) { maxSum = sum; minIndex = j; } } int sum = newList.get(minIndex) + newList.get(minIndex + 1); newList.set(minIndex, sum); newList.remove(minIndex + 1); result++; } return result; } public boolean checkArray(List<Integer> nums) { int count = 0; for (int i = 0; i < nums.size() - 1; i++) { if (nums.get(i) <= nums.get(i + 1)) { count++; } else { break; } } return count == nums.size() - 1; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
The Burden of Order: A Melancholic Descent into Algorithmic Redemption
the-burden-of-order-a-melancholic-descen-erh2
IntuitionIn a world governed by entropy, man seeks order โ€” such is the nature of this undertaking. The list, disheveled and chaotic, yearns to find peace in a n
DostoevskyInDebug
NORMAL
2025-04-09T21:01:26.053656+00:00
2025-04-09T21:01:26.053656+00:00
7
false
# Intuition In a world governed by entropy, man seeks order โ€” such is the nature of this undertaking. The list, disheveled and chaotic, yearns to find peace in a non-decreasing sequence, much like a tormented soul yearning for redemption. One must, with grim determination and unwavering patience, sacrifice pairs โ€” plucking them from the ranks like condemned men โ€” merging them into something new, something possibly less destructive. Yet not all pairs are equal; one must choose wisely, for the one with the least sum is perhaps the least wicked, the most humble in its contribution to disorder. # Approach The method is neither fast nor merciful. It is deliberate โ€” a slow, brooding march toward harmony. We begin by observing, by inspecting the array for its afflictions. We do not rush. We look for the weakest link: the adjacent pair whose sum is minimal, for such a pair, by its very insignificance, can be torn apart and merged into one without disturbing the fragile fabric too much. And so the steps follow, like chapters in a dark novel: 1. Begin with no operations โ€” innocence. 2. While the list remains in turmoil, while it still declines where it should rise: - Search the depths of the list, with the care of a man leafing through old letters, to find the adjacent pair with the smallest sum. - Merge them, not unlike how sorrow and hope may merge into bitter understanding. - Remove one, absorb it into the other. - Count this act, tally the sin. 3. When the sequence becomes one of order, when the noise fades and ascension reigns โ€” we halt, and return the number of such transgressions. # Complexity - Time complexity: $$O(n^2)$$ Like revisiting the same regretful memory again and again โ€” each pass, each scan โ€” all until peace is finally reached. - Space complexity: $$O(1)$$ For in the end, we carry no burdens but those already within us. All is done in-place, within the soul of the list. # Code ```python3 from typing import List class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: operations = 0 while not self.isNonDecreasing(nums): # As though choosing which regret to face first min_sum = float('inf') min_index = -1 for i in range(len(nums) - 1): current_sum = nums[i] + nums[i + 1] if current_sum < min_sum: min_sum = current_sum min_index = i # Sacrifice the pair, merge them into one nums[min_index] = nums[min_index] + nums[min_index + 1] nums.pop(min_index + 1) operations += 1 return operations def isNonDecreasing(self, nums: List[int]) -> bool: for i in range(1, len(nums)): if nums[i] < nums[i - 1]: return False return True ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Minimum Pair removal to sort an array
minimum-pair-removal-to-sort-an-array-by-yifr
IntuitionApproachComplexity Time complexity: Best case (already sorted array): O(n log n) Worst case (needs multiple iterations to sort): O(n^2 log n) Space com
SswathiI18
NORMAL
2025-04-09T19:39:10.298339+00:00
2025-04-09T19:39:10.298339+00:00
5
false
# Intuition <!-- First I though to check the array is sorted or not, I created a function for that, and secondly if the array is not sorted we have to go to the function where it checks all the adjacent sums and returns minimum sum of adjacent pairs and its index, this helps in the final function to replace the values with its sum until the array becomes sorted. --> # Approach <!-- Split the total problem to small parts so that it is easy to analyse and get effective solution --> # Complexity - Time complexity: - Best case (already sorted array): O(n log n) Worst case (needs multiple iterations to sort): O(n^2 log n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) because of the additional space used by the sorted array and the list of adjacent sums. <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def adj_pair(self, arr): # Find the pair with the smallest sum of adjacent elements adj_sums = [arr[i] + arr[i+1] for i in range(len(arr)-1)] min_val = min(adj_sums) min_ind = adj_sums.index(min_val) min_pair = [arr[min_ind], arr[min_ind+1]] return min_pair, min_ind def check_arr(self, arr): # Check if the array is sorted in ascending order return arr == sorted(arr) def minimumPairRemoval(self, arr): output = 0 while not self.check_arr(arr): output += 1 # Find the pair with the smallest adjacent sum min_pair, min_ind = self.adj_pair(arr) sum_adj = sum(min_pair) # Replace the pair with the sum in the array arr = arr[:min_ind] + [sum_adj] + arr[min_ind+2:] return output # Example usage: solution = Solution() result = solution.minimumPairRemoval([2, 2, -1, 3, -2, 2, 1, 1, 1, 0, -1]) print(result) # Expected output: 9 ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Python3: Step Separation Approach (85.26 TC)
python3-step-separation-approach-8526-tc-j91l
IntuitionThe intuition for solving this problem is based on breaking down each operation from the task description and repeating them until the required conditi
alexxmagpie
NORMAL
2025-04-09T16:19:28.139137+00:00
2025-04-09T16:19:28.139137+00:00
5
false
# Intuition The intuition for solving this problem is based on breaking down each operation from the task description and repeating them until the required condition is met. # Approach 1. Move the logic for checking if the array is non-decreasing into a separate `is_decreasing` function. $$O(n)$$ 2. Move the logic for finding the adjacent pair with the minimum sum into an `adjacent_pair` function. $$O(n)$$ 3. Repeat the process: while the array is not non-decreasing, replace the selected adjacent pair with their sum and increment the `result` counter that tracks the number of performed actions. # Complexity - Time complexity: $$O(nยฒ)$$ - Space complexity: $$O(1)$$ # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: def is_decreasing(arr): for i in range(len(arr)-1, -1, -1): if i != 0 and arr[i-1] > arr[i]: return False return True def adjacent_pair(arr): min_sum = float('inf') min_index = float('inf') for i in range(len(arr)-1): adj_sum = arr[i] + arr[i+1] if adj_sum < min_sum: min_sum = adj_sum min_index = i return min_sum, min_index result = 0 non_decreasing = is_decreasing(nums) while non_decreasing is False: adj_sum, adj_index = adjacent_pair(nums) nums[adj_index:adj_index+2] = [adj_sum] non_decreasing = is_decreasing(nums) result += 1 return result ``` ![Screen Shot 2025-04-09 at 17.54.20.png](https://assets.leetcode.com/users/images/555386b5-5fed-4ca4-99cf-259c42c90077_1744215543.65682.png)
0
0
['Array', 'Simulation', 'Python3']
0
minimum-pair-removal-to-sort-array-i
Java Solution using DoublyLinkedList
java-solution-using-doublylinkedlist-by-4dj8f
null
yucan29
NORMAL
2025-04-09T13:27:35.774511+00:00
2025-04-09T13:27:35.774511+00:00
9
false
```java [] class ListNode { public int val; public ListNode prev; public ListNode next; ListNode(int val) { this.val = val; } } class Solution { boolean checkIfSorted(ListNode head) { if (head.next==null) return true; ListNode temp = head; while(temp.next!=null) { if(temp.val>temp.next.val) return false; temp = temp.next; } return true; } public int minimumPairRemoval(int[] nums) { ListNode dummyHead = new ListNode(-1001); ListNode curr = dummyHead; for(int i=0; i<nums.length; i++) { ListNode newNode = new ListNode(nums[i]); curr.next = newNode; newNode.prev =curr; curr = newNode; } curr = dummyHead.next; ListNode minSumFirstNode = curr; int minSum = Integer.MAX_VALUE; int count=0; int pairSum = 0; while(checkIfSorted(dummyHead.next)==false && curr.next!=null) { pairSum = curr.val + curr.next.val; if(pairSum<minSum) { minSum = pairSum; minSumFirstNode = curr; } curr = curr.next; if(curr.next==null) { minSumFirstNode.val = minSum; minSumFirstNode.next = minSumFirstNode.next.next; count++; curr = dummyHead.next; minSum = Integer.MAX_VALUE; } } return count; } } ```
0
0
['Doubly-Linked List', 'Java']
0
minimum-pair-removal-to-sort-array-i
Separation of Concerns Beats 96%
separation-of-concerns-beat-96-by-eugene-5gwv
IntuitionWe basically want to simulate the process demanded by the problem. First we make the module that will let us work on the problem: check if the current
eugenerw
NORMAL
2025-04-09T10:30:50.257515+00:00
2025-04-09T10:31:08.291304+00:00
4
false
# Intuition We basically want to simulate the process demanded by the problem. First we make the module that will let us work on the problem: - check if the current array is valid - merge minimum sum - put them together # Approach The idea is to repeatedly find and merge the pair of adjacent elements that have the smallest sum. This is a greedy approach where we assume merging the smallest-sum pair will bring us closer to a sorted array (non-decreasing order). 1. **is_valid**: Checks if the list is non-decreasing. 2. **aggregate**: Finds the adjacent pair with the smallest sum and merges them by replacing the left element with the sum and removing the right one. 3. We repeat this process until the array is sorted, and count how many merges were needed. # Complexity - Time complexity: $$O(n^2)$$ in the worst case. Each `aggregate` call takes $$O(n)$$ time to find and merge the smallest pair. In the worst case, you may do up to $$n - 1$$ merges. - Space complexity: $$O(n)$$ Each merge creates a new list (due to list comprehension), so at each step you're using additional space proportional to the size of the list. # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: def is_valid(nums): return all(nums[i - 1] <= nums[i] for i in range(1,len(nums))) def aggregate(nums): min_sum = float('inf') anchor = 0 for i in range(1, len(nums)): if nums[i] + nums[i - 1] < min_sum: min_sum = nums[i] + nums[i - 1] anchor = i ans = [x for i, x in enumerate(nums) if i != anchor] ans[anchor - 1] = min_sum return ans tries = 0 while not is_valid(nums): nums = aggregate(nums) tries += 1 return tries ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
BEST APPROCAH TO SOLVE THE PROBLEM | | EASY TO UNDERSTAND | | BEATS 100%
best-approcah-to-solve-the-problem-easy-atsi3
IntuitionApproachComplexity Time complexity: FOR THIS PROBLEM THE EFFICIENT WAY IS O(n^2) Space complexity: Code
HASAN_CHAUOSH
NORMAL
2025-04-09T09:49:55.117237+00:00
2025-04-09T09:49:55.117237+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> FOR THIS PROBLEM THE EFFICIENT WAY IS O(n^2) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { bool check1=is_sorted(nums.begin(),nums.end()); if(check1) return 0; int operation=0; while(!is_sorted(nums.begin(),nums.end())){ int k=0; int minsum=INT_MAX; for(int i=1;i<nums.size();i++){ int sum=nums[i]+nums[i-1]; if(minsum>sum){ minsum=sum; k=i; } } nums[k-1]=nums[k-1]+nums[k]; nums.erase(nums.begin()+k); operation++; } return operation; } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Prasad'sCODE
prasadscode-by-l957ugyu7z-p4zg
IntuitionApproachComplexity Time complexity: Space complexity: Code
L957UGyu7z
NORMAL
2025-04-09T06:40:43.699786+00:00
2025-04-09T06:40:43.699786+00:00
10
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def minimumPairRemoval(self, nums): def is_non_decreasing(arr): return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) operations = 0 while not is_non_decreasing(nums): min_sum = float('inf') min_index = -1 for i in range(len(nums) - 1): pair_sum = nums[i] + nums[i + 1] if pair_sum < min_sum: min_sum = pair_sum min_index = i # Replace the pair with their sum merged = nums[min_index] + nums[min_index + 1] nums = nums[:min_index] + [merged] + nums[min_index + 2:] operations += 1 return operations ```
0
0
['Python']
0
minimum-pair-removal-to-sort-array-i
100% beats
100-beats-by-shashwat321-gss1
IntuitionApproachComplexity Time complexity: Space complexity: Code
shashwat321
NORMAL
2025-04-08T18:26:38.681021+00:00
2025-04-08T18:26:38.681021+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int result = 0; while(!isSorted(nums)){ merge(nums); result++; } return result; } bool isSorted(vector<int>& nums){ for(int i=0;i<nums.size()-1;i++){ if(nums[i]>nums[i+1]) return false; } return true; } void shiftleft(vector<int>& nums,int idx){ for(int i = idx;i<nums.size()-1;i++){ nums[i]=nums[i+1]; } nums.pop_back(); } void merge(vector<int>& nums){ int min; int minValue = INT_MAX; for(int i=0;i<nums.size()-1;i++){ int sum = nums[i]+nums[i+1]; if(sum<minValue){ minValue = sum; min = i; } } nums[min]=minValue; shiftleft(nums,min+1); } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
100% beats
100-beats-by-shashwat321-4mkv
IntuitionApproachComplexity Time complexity: Space complexity: Code
shashwat321
NORMAL
2025-04-08T18:26:36.395501+00:00
2025-04-08T18:26:36.395501+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int result = 0; while(!isSorted(nums)){ merge(nums); result++; } return result; } bool isSorted(vector<int>& nums){ for(int i=0;i<nums.size()-1;i++){ if(nums[i]>nums[i+1]) return false; } return true; } void shiftleft(vector<int>& nums,int idx){ for(int i = idx;i<nums.size()-1;i++){ nums[i]=nums[i+1]; } nums.pop_back(); } void merge(vector<int>& nums){ int min; int minValue = INT_MAX; for(int i=0;i<nums.size()-1;i++){ int sum = nums[i]+nums[i+1]; if(sum<minValue){ minValue = sum; min = i; } } nums[min]=minValue; shiftleft(nums,min+1); } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
brute force
brute-force-by-user5285zn-5qea
null
user5285Zn
NORMAL
2025-04-08T09:31:17.016292+00:00
2025-04-08T09:31:17.016292+00:00
4
false
```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: i = 0 while nums != list(sorted(nums)): i += 1 k = 0 b = nums[0] + nums[1] for j in range(len(nums)-1): if nums[j] + nums[j+1] < b: b = nums[j] + nums[j+1] k = j nums[k] = b del nums[k+1] return i ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
โœ… Beats 100% Time & Space๐Ÿ’ฏ๐Ÿ”ฅ|| Clean Code + Step-by-Step Approach ๐Ÿš€
beats-100-time-space-clean-code-step-by-nyi79
IntuitionEverytime we have to check if the array is sorted or not, if not sorted we have to get minimum Sum of adjacent pair and have to add that Minimum sum in
sejalpuraswani
NORMAL
2025-04-08T09:23:23.550554+00:00
2025-04-08T09:23:23.550554+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Everytime we have to check if the array is sorted or not, if not sorted we have to get minimum Sum of adjacent pair and have to add that Minimum sum in place of that adjacent pair. ## **Things we have to Track** - Starting index of adjacent pair (with minimum sum) to replace it with Minimum Sum. - To Check if Array is sorted or not (for that we will use a helper Function) # Approach <!-- Describe your approach to solving the problem. --> - I used a helper function to check is array is sorted or not - if array is already sorted No need to do anything `return 0`; - if Array is not sorted, then we will Check for minimum sum of adjacent pair and replace it with Minimum sum. - While loop run until our array becomes sorted in ascending order. - Finally, `return count`. # Complexity - Time complexity: O(n2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {number[]} nums * @return {number} */ var minimumPairRemoval = function (nums) { let count = 0; function isSortedIncreasing(nums) { for (let i = 0; i < nums.length - 1; i++) { if (nums[i] > nums[i + 1]) return false; } return true; } while (!isSortedIncreasing(nums)) { let minSum = Infinity; let index = -1; for (let i = 0; i < nums.length - 1; i++) { let sum = nums[i] + nums[i + 1]; if (minSum > sum) { minSum = sum; index = i; } } nums.splice(index, 2, minSum); count++; } return count; }; ```
0
0
['JavaScript']
0
minimum-pair-removal-to-sort-array-i
I just shared because no other C solutions were shared.
i-just-shared-because-no-other-c-solutio-k7w8
The procedure is decsribed in problem definition. Uncomment print statements for debugging.
user0296oG
NORMAL
2025-04-08T09:07:42.704120+00:00
2025-04-08T09:07:42.704120+00:00
15
false
The procedure is decsribed in problem definition. Uncomment print statements for debugging. ```c [] bool isNonDecreasing(int* nums, int numsSize) { for (int i = 1; i < numsSize; i++) { if (nums[i] < nums[i - 1]) {return false;} } return true; } int minPairIndex(int* nums, int numsSize) { int index = 1; int sum = 1<<15; for (int i = 1; i < numsSize; i++) { if (nums[i] + nums[i - 1] < sum) { sum = nums[i] + nums[i - 1]; index = i; } } return index; } void removeElement(int *array, int index, int array_length) { for(int i = index; i < array_length - 1; i++) array[i] = array[i + 1]; } /* void printArray(int* nums, int numsSize) { for (int i = 0; i < numsSize; i++) { printf("%d ", nums[i]); } printf("\n"); } */ int minimumPairRemoval(int* nums, int numsSize) { int operations = 0; while (!isNonDecreasing(nums, numsSize)) { operations++; int ind = minPairIndex(nums, numsSize); int swap = nums[ind] + nums[ind - 1]; // printf("ind = %d, swap = %d\n", ind, swap); // printArray(nums, numsSize); nums[ind - 1] = swap; removeElement(nums, ind, numsSize); numsSize--; } return operations; } ```
0
0
['C']
0
minimum-pair-removal-to-sort-array-i
Swift๐Ÿ’ฏ Brute Force+Recursion
swift-brute-forcerecursion-by-upvotethis-0lci
Brute Force (accepted answer)
UpvoteThisPls
NORMAL
2025-04-08T06:10:35.610574+00:00
2025-04-08T06:10:35.610574+00:00
3
false
**Brute Force (accepted answer)** ``` class Solution { func minimumPairRemoval(_ nums: consuming [Int], _ ops: Int = 0) -> Int { var minSum = Int.max var minSumIndex = -1 var isSorted = true for i in nums.indices.dropLast(1) { isSorted = isSorted && nums[i] <= nums[i+1] let sum = nums[i] + nums[i+1] guard sum < minSum else { continue } minSum = sum minSumIndex = i } guard !isSorted else { return ops } nums[minSumIndex...minSumIndex+1] = [minSum] return minimumPairRemoval(nums, ops+1) } } ```
0
0
['Swift']
0
minimum-pair-removal-to-sort-array-i
Python3 solution
python3-solution-by-alex72112-0zdn
Code
alex72112
NORMAL
2025-04-07T21:45:10.727197+00:00
2025-04-07T21:45:10.727197+00:00
5
false
# Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: count = 0 while not self.is_array_increasing(nums): index = self.get_min_pair(nums) s = nums[index] + nums[index + 1] count = count + 1 nums[index] = s nums.pop(index + 1) return count def get_min_pair(self, nums): smallest = 99999 index = -1 for i in range(len(nums) - 1): s = nums[i] + nums[i + 1] if s < smallest: index = i smallest = s return index def is_array_increasing(self, nums): for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: return False return True ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Naive and intuitive simulation
naive-and-intuitive-simulation-by-mnjk-w83l
IntuitionWe'll simulate the process by running a loop in which we check nums against whether it's sorted and perform the pairwise check as stated.ApproachWe'll
mnjk
NORMAL
2025-04-07T18:10:04.370135+00:00
2025-04-07T18:10:04.370135+00:00
5
false
# Intuition We'll simulate the process by running a loop in which we check `nums` against whether it's sorted and perform the pairwise check as stated. # Approach We'll run an outer loop that we'll break as soon as our input is sorted (we'll use variable `xs` that we'll use as the ne new list in the next iteration): ```py ops = 0 xs = nums while True: mv = math.inf j = -1 if (all(xs[k] <= xs[k + 1] for k in range(len(xs) - 1))): break for i in range(len(xs) - 1): if mv > (xs[i] + xs[i + 1]): j = i mv = xs[i] + xs[i + 1] xs = xs[:j] + xs[j + 1:] xs[j] = mv ops = ops + 1 return ops ``` The inner for-loop finds the leftmost index `j` that gives us the min-pair and we concatenate the new list for the next iteration and assign it to `xs`: ```py xs = xs[:j] + xs[j + 1:] xs[j] = mv ``` We'll use `ops` to count the necessary operations. # Complexity - Time complexity: $$O(n!)$$ - Space complexity: $$O(n)$$ # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: ops = 0 xs = nums while True: mv = math.inf j = -1 if (all(xs[k] <= xs[k + 1] for k in range(len(xs) - 1))): break for i in range(len(xs) - 1): if mv > (xs[i] + xs[i + 1]): j = i mv = xs[i] + xs[i + 1] xs = xs[:j] + xs[j + 1:] xs[j] = mv ops = ops + 1 return ops ```
0
0
['Array', 'Sorting', 'Python3']
0
minimum-pair-removal-to-sort-array-i
C++ short and concise brute force solution
c-solution-short-brute-force-by-oleksam-mwtw
Please, upvote if you like it. Thanks :-)Complexity Time complexity: O(n * n) Space complexity: O(n) Code
oleksam
NORMAL
2025-04-07T17:40:18.560122+00:00
2025-04-07T17:43:08.183718+00:00
3
false
Please, upvote if you like it. Thanks :-) # Complexity - Time complexity: O(n * n) - Space complexity: O(n) # Code ```cpp [] int minimumPairRemoval(vector<int>& nums) { int res = 0; while (!ranges::is_sorted(nums) && ++res) { int minSum = INT_MAX, startInd = -1; for (int j = 0; j + 1 < nums.size(); j++) { if (nums[j] + nums[j + 1] < minSum) { minSum = nums[j] + nums[j + 1]; startInd = j; } } nums[startInd] += nums[startInd + 1]; nums.erase(nums.begin() + startInd + 1); } return res; } ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
3507. Minimum Pair Removal to Sort Array I
3507-minimum-pair-removal-to-sort-array-1sbxp
IntuitionSimulation - do that is ask in the questionApproachCreate new list and add all the elements and performs all the operationComplexity Time complexity:
kumar_amit931063
NORMAL
2025-04-07T16:14:14.120014+00:00
2025-04-07T16:14:14.120014+00:00
6
false
# Intuition Simulation - do that is ask in the question # Approach Create new list and add all the elements and performs all the operation # Complexity - Time complexity:- 0(n^2) - Space complexity:-0(n) # Code ```java [] class Solution { public boolean isSorted(List<Integer> list) { for (int i = 0; i < list.size() - 1; i++) { if (list.get(i) > list.get(i + 1)) return false; } return true; } public int minimumPairRemoval(int[] nums) { int n = nums.length; List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(nums[i]); } int cnt = 0; while (isSorted(list) != true) { int min = Integer.MAX_VALUE; int minIdx = -1; for (int i = 0; i < list.size() - 1; i++) { if (min > (list.get(i) + list.get(i + 1))) { minIdx = i; min = (list.get(i) + list.get(i + 1)); } } list.set(minIdx, min); for (int i = minIdx + 1; i < list.size() - 1; i++) { list.set(i, list.get(i + 1)); } list.remove(list.size()-1); cnt++; } return cnt; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Python 3: Beats 100%. Easy solution.
python-3-beats-100-easy-solution-by-4272-igna
null
4272696D6579
NORMAL
2025-04-07T15:01:55.104222+00:00
2025-04-07T15:01:55.104222+00:00
3
false
```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: ops = 0 while True: if nums == sorted(nums): return ops s = [] for i, _ in enumerate(nums[:-1]): a, b = nums[i], nums[i + 1] s.append(a + b) mi = s.index(min(s)) nums[mi:mi + 2] = [s[mi]] ops += 1 ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Python || Beat 100% || Two Pointers solution
python-beat-100-two-pointers-solution-by-5dti
IntuitionApproachComplexity Time complexity: O(n log n) on average, O(nยฒ) in the worst case. Space complexity: O(1) Code
siro411
NORMAL
2025-04-07T14:24:50.337948+00:00
2025-04-07T14:28:50.374402+00:00
22
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n log n) on average, O(nยฒ) in the worst case. <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def findMinValueIndex(self, nums, lt, rt): minValue = float('inf') for i in range(lt, rt): if nums[i] + nums[i+1] < minValue: minValue = nums[i] + nums[i+1] minIndex = i return minIndex def isIncreasing(self, nums, lt, rt): return all([nums[i] <= nums[i+1] for i in range(lt,rt)]) def minimumPairRemoval(self, nums): """ :type nums: List[int] :rtype: int """ ans = 0 lt, rt = 0, len(nums) - 1 while lt < rt: minIndex = self.findMinValueIndex(nums,lt,rt) if minIndex == lt and self.isIncreasing(nums,lt,rt): lt += 1 else: nums[minIndex] += nums[minIndex+1] while minIndex<rt - 1: minIndex += 1 nums[minIndex] = nums[minIndex+1] rt - =1 ans + =1 return ans ```
0
0
['Array', 'Two Pointers', 'Python']
0
minimum-pair-removal-to-sort-array-i
Optimize Code Of Minimum Pair Removal To Sort Array-I....
optimize-code-of-minimum-pair-removal-to-c8ii
IntuitionApproachComplexity Time complexity: Space complexity: Code
Vakul19
NORMAL
2025-04-07T13:58:23.955672+00:00
2025-04-07T13:58:23.955672+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: bool isascend(vector<int>& nums) { for (int i = 0; i < nums.size()-1; i++) { if (nums[i] > nums[i + 1]) { return false; } } return true; } int minimumPairRemoval(vector<int>& nums) { int ans=0; while(!isascend(nums) && nums.size()>1){ int pos=-1; int minsum=INT_MAX; for(int i=0;i<nums.size()-1;i++){ int cursum=nums[i]+nums[i+1]; if(cursum<minsum){ minsum=cursum; pos=i; } } nums[pos]=nums[pos]+nums[pos+1]; nums.erase(nums.begin()+pos+1); ans++; } return ans; } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Python3 Straightforward Solution
python3-straightforward-solution-by-cure-fl2t
Code
curenosm
NORMAL
2025-04-07T13:48:36.431276+00:00
2025-04-07T13:48:36.431276+00:00
4
false
# Code ```python3 [] class Solution: def is_non_decreasing(self, nums) -> bool: for i in range(1, len(nums)): if nums[i - 1] > nums[i]: return False return True def minimumPairRemoval(self, nums: List[int]) -> int: operations_count = 0 while not self.is_non_decreasing(nums): min_sum = float('inf') for i in range(1, len(nums)): min_sum = min(min_sum, nums[i - 1] + nums[i]) for i in range(1, len(nums)): cur_sum = nums[i - 1] + nums[i] if cur_sum == min_sum: nums[i - 1] = cur_sum ; del nums[i] operations_count += 1 break return operations_count ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Recursive
recursive-by-ishibashijun-79x9
Code
ishibashijun
NORMAL
2025-04-07T11:46:42.128839+00:00
2025-04-07T11:46:42.128839+00:00
1
false
# Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int n = nums.size(); int minSum = INT_MAX; int idx = -1; bool sorted = true; for (int i = 1; i < n; i++) { int sum = nums[i - 1] + nums[i]; if (nums[i] < nums[i - 1]) sorted = false; if (sum < minSum) { minSum = sum; idx = i - 1; } } if (!sorted) { nums[idx] += nums[idx + 1]; nums.erase(nums.begin() + idx + 1); return minimumPairRemoval(nums) + 1; } return 0; } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Simple solution
simple-solution-by-ksnaghulpranav-s2il
IntuitionApproachComplexity Time complexity: Space complexity: Code
ksnaghulpranav
NORMAL
2025-04-07T09:02:56.607283+00:00
2025-04-07T09:02:56.607283+00:00
12
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { ArrayList<Integer> li=new ArrayList<>(); for(int i=0;i<nums.length;i++){ li.add(nums[i]); } int sum;//=li.get(0)+li.get(1); int min=Integer.MAX_VALUE; int index=0; int f=1,j=0; int count=0; while(f==1){ f=0; sum=0;min=Integer.MAX_VALUE; index=0; for(j=0;j<li.size()-1;j++){ if(li.get(j)>li.get(j+1)){ f=1; } sum=li.get(j)+li.get(j+1); if(sum<min){ min=sum; index=j; } } if(f==0) return count; li.set(index,min); //System.out.println(min+" "+index+" "+f); count++; li.remove(index+1); //System.out.println(li); } return count; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Java Solution
java-solution-by-sshruthii30-kzbk
IntuitionApproachComplexity Time complexity: Space complexity: Code
sshruthii30
NORMAL
2025-04-07T08:35:08.996068+00:00
2025-04-07T08:35:08.996068+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { boolean inc= false; List<Integer> li= new ArrayList<>(); for(int i: nums){ li.add(i); } int count=0; while(!inc){ inc= true; int min= Integer.MAX_VALUE; int ind=0; for(int i=0;i<li.size()-1;i++){ int sum= li.get(i) + li.get(i+1); if(sum< min){ min= sum; ind= i; } if(li.get(i)> li.get(i+1) ){ inc= false; } } if(inc) break; else{ count++; li.set(ind, min); li.remove(ind+1); } } return count; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
PYTHON BRUTE FORCE
python-brute-force-by-greg_savage-3fyp
IntuitionJust do all the operations until the array is non decreasing.Complexity Time complexity: doOperation is linear and checking the entire array for non d
greg_savage
NORMAL
2025-04-07T07:26:25.885253+00:00
2025-04-07T07:26:25.885253+00:00
6
false
# Intuition Just do all the operations until the array is non decreasing. # Complexity - Time complexity: doOperation is linear and checking the entire array for non decreasing state is linear. This is done up to the size of the array so n^2 - Space complexity: Linear extra spaced used to recreate the array each step. # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: def doOperation(): nonlocal nums n = len(nums) min_pairs = [] for i in range(n - 1): first = nums[i] second = nums[i + 1] pair_sum = first + second triplet = (pair_sum, i, i + 1) min_pairs.append(triplet) smallest_pair = min(min_pairs) new_pair_sum, first, second = smallest_pair new_nums = nums[:first] + [new_pair_sum] + nums[second + 1:] nums = new_nums last_good_index = 0 prev_val = nums[0] operation_count = 0 def isNonDecreasing() -> None: nonlocal nums n = len(nums) for i in range(n - 1): first = nums[i] second = nums[i + 1] if second < first: return False return True while not isNonDecreasing(): operation_count += 1 doOperation() return operation_count ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Greedy Minimum Sum Approach | Dart Solution | Time O(nยณ) | Space O(1)
greedy-minimum-sum-approach-dart-solutio-v0fu
ApproachThis solution uses a greedy strategy to merge pairs until the array becomes sorted: Sorting Check: Use a helper function _isSorted to verify if the ar
user4343mG
NORMAL
2025-04-07T05:48:27.959116+00:00
2025-04-07T05:48:27.959116+00:00
3
false
## Approach This solution uses a greedy strategy to merge pairs until the array becomes sorted: 1. **Sorting Check**: - Use a helper function `_isSorted` to verify if the array is already sorted 2. **Greedy Pair Selection**: - While the array isn't sorted: - Find the adjacent pair with the smallest sum - Replace this pair with a single element (their sum) - Increment the operation counter 3. **Termination**: - Continue until the array becomes sorted - Return the number of operations performed This approach merges elements that likely create inversions, gradually transforming the array into a sorted sequence. --- ## Complexity - **Time Complexity**: $$O(n^3)$$ - Each iteration checks if sorted $$O(n)$$ and finds minimum sum pair $$O(n)$$ - Could require up to $$O(n)$$ iterations in worst case - **Space Complexity**: $$O(1)$$ - Modifies the input array in-place - Uses constant extra space regardless of input size --- # Code ```dart [] class Solution { int minimumPairRemoval(List<int> nums) { int removeOperationCounter = 0; bool _isSorted(List<int> nums) { for (var i = 0; i < nums.length - 1; i++) { if (nums[i] > nums[i + 1]) return false; } return true; } while (!_isSorted(nums)) { int minSumPos = 0; int minSumValue = 1000000; for (var i = 0; i < nums.length - 1; i++) { if (nums[i] + nums[i + 1] < minSumValue) { minSumValue = nums[i] + nums[i + 1]; minSumPos = i; } } nums.replaceRange(minSumPos, minSumPos + 2, [ nums[minSumPos] + nums[minSumPos + 1], ]); removeOperationCounter++; } return removeOperationCounter; } } ```
0
0
['Array', 'Greedy', 'Sorting', 'Dart']
0
minimum-pair-removal-to-sort-array-i
Simulation | Easy to Understand
simulation-easy-to-understand-by-saurabh-kcnq
IntuitionApproachComplexity Time complexity: O(n^2) Space complexity:O(1) Code
SaurabhYadav_45
NORMAL
2025-04-07T05:22:38.269457+00:00
2025-04-07T05:26:41.979698+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n^2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimumPairRemoval(vector<int>& nums) { int minOp = 0; while(true){ int n = nums.size(); bool sorted = true; // Check if array is sorted for(int i=0; i<n-1; i++){ if(nums[i] > nums[i+1]){ sorted = false; break; } } if(sorted){ break; } // find minSum and index int minSum = INT_MAX; int index = 0; for(int i = 0; i<n-1; i++){ if(nums[i] + nums[i+1] < minSum){ minSum = nums[i]+nums[i+1]; index = i; } } // delete index+1 element nums.erase(nums.begin()+index+1); // replace the element at index with the minSum nums[index] = minSum; minOp++; } return minOp; } }; ```
0
0
['Array', 'Simulation', 'C++']
0
minimum-pair-removal-to-sort-array-i
Java
java-by-sumeetrayat-ekqo
Code
sumeetrayat
NORMAL
2025-04-07T04:53:57.522068+00:00
2025-04-07T04:53:57.522068+00:00
7
false
# Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { ArrayList<Integer> list = new ArrayList<>(); int count = 0; int sum = 0; int min = Integer.MAX_VALUE; int countm=0; // checking if already sorted for (int i = 0; i <= nums.length - 1; i++) { list.add(nums[i]); if(i==nums.length-1) { break; } if (nums[i] <= nums[i + 1]) { } else { count++; } } int one = 0; int two = 0; if (count == 0) { // already sorted countm=0; } else { while (true) { // finding the minimum sum and removing countm++; sum=0; min = Integer.MAX_VALUE; for (int i = 0; i <= list.size() - 1; i++) { if (i == list.size() - 1) { break; } sum = sum + (list.get(i) + list.get(i + 1)); if (sum < min) { min = sum; one = i; two = i + 1; } sum = 0; } // rempving min sum pair and adding their sum to list again //System.out.println("min sum pair is" + one + " " + two); int sum1 = list.get(one) + list.get(two); list.remove(two); list.remove(one); list.add(one, sum1); // System.out.print(list); //checking if its non Decreasing count=0; for (int i = 0; i<=list.size()-1; i++) { if(i==list.size()-1) { break; } if(list.get(i)<=list.get(i+1)) { } else { count++; } } if(count==0) { break; } } } return countm; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
C++ simulation solution
c-simulation-solution-by-nguyenchiemminh-jz17
null
nguyenchiemminhvu
NORMAL
2025-04-07T04:43:54.720289+00:00
2025-04-07T04:43:54.720289+00:00
7
false
``` class Solution { public: int minimumPairRemoval(vector<int>& nums) { int res = 0; while (true) { bool sorted = true; bool non_sorted_idx = -1; for (int i = 1; i < nums.size(); i++) { if (nums[i] < nums[i - 1]) { non_sorted_idx = i; sorted = false; break; } } if (sorted) { break; } res++; int min_idx = non_sorted_idx; int min_sum = nums[non_sorted_idx] + nums[non_sorted_idx - 1]; for (int i = non_sorted_idx; i < nums.size(); i++) { if (nums[i] + nums[i - 1] < min_sum) { min_idx = i; min_sum = nums[i] + nums[i - 1]; } } nums[min_idx - 1] = min_sum; for (int i = min_idx + 1; i < nums.size(); i++) { nums[i - 1] = nums[i]; } nums.pop_back(); } return res; } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Concise python code
concise-python-code-by-tet-2wuw
IntuitionSimply just follow the algorithm described in the problem statement and count the number of steps.It seems unlikely that there is an O(nlogn) solution.
tet
NORMAL
2025-04-07T02:59:12.231250+00:00
2025-04-07T02:59:12.231250+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Simply just follow the algorithm described in the problem statement and count the number of steps. It seems unlikely that there is an $O(nlogn)$ solution. I will think about this further. Heaps and linked lists seems somewhat helpful, but it doesn't seem to help reach a better complexity class. # Approach <!-- Describe your approach to solving the problem. --> Write a function that checks if the list is sorted. This is pretty standard; just check each pair of adjacent elements is sorted. Repeat until the array is sorted: 1. Find the minimal tuple `(nums[i] + nums[i+1], i)` for each i up to, but not including `len(nums)-1`. 2. Replace the entry at spot `i` with the sum of the `i` and `i+1` entries. 3. Remove the entry `i+1` for the list. 4. Increment a counter to track the number of operations. # Complexity - Time complexity: $O(n^2)$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> Checking if the array is sorted, finding the pair to replace, and `List.pop(i)` is $O(n)$ and in the worst case you have to perform these steps $O(n)$ times. - Space complexity: $O(1)$ or $O(n)$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> I destroy the input array, so if you actually need the original array, you would need to make a copy for use in this function, making it $O(n)$. There is only constant auxiliary space used for other parts, making it $O(1)$ if you don't consider the input array as part of the space complexity. # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: def is_sorted(a): return all(a[i] <= a[i+1] for i in range(len(a)-1)) ops = 0 while not is_sorted(nums): s, idx = min((nums[i] + nums[i+1], i) for i in range(len(nums)-1)) nums[idx] = s nums.pop(idx+1) ops += 1 return ops ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
scala solution
scala-solution-by-lyk4411-gafg
IntuitionApproachComplexity Time complexity: Space complexity: Code
lyk4411
NORMAL
2025-04-07T02:10:56.026009+00:00
2025-04-07T02:10:56.026009+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```scala [] object Solution { def minimumPairRemoval(nums: Array[Int]): Int = { @annotation.tailrec def f(nums: Array[Int], ops: Int): Int = { if (nums.sorted.sameElements(nums)) ops else { val idx = nums.sliding(2).map(_.sum).zipWithIndex.minBy(_._1)._2 val newNums = nums.take(idx) ++ Array(nums(idx) + nums(idx + 1)) ++ nums.drop(idx + 2) f(newNums, ops + 1) } } f(nums, 0) } } ```
0
0
['Scala']
0
minimum-pair-removal-to-sort-array-i
Java 100%
java-100-by-jaidevramakrishna-an7y
ApproachWe use helper functions to check whether the array is sorted and to get the index of the minimum pair.While the array is not sorted, replace the min pai
jaidevramakrishna
NORMAL
2025-04-07T01:52:47.665903+00:00
2025-04-07T01:52:47.665903+00:00
17
false
# Approach We use helper functions to check whether the array is sorted and to get the index of the minimum pair. While the array is not sorted, replace the min pair with their sum and increment the counter. When the array is sorted, return the counter. # Complexity - Time complexity: $O(N^2)$ - Space complexity: $O(N)$ # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { ArrayList<Integer> a = new ArrayList<>(nums.length); for(int x : nums) a.add(x); int c = 0; int minP; while(!isSorted(a)) { c++; minP = getMin(a); a.set(minP, a.get(minP)+a.get(minP+1)); a.remove(minP+1); } return c; } private boolean isSorted(ArrayList<Integer> a) { for(int p=a.get(0),i=1, l=a.size(); i<l; p=a.get(i++)) if(a.get(i)<p) return false; return true; } private int getMin(ArrayList<Integer> a) { int minP = 0; int minV = a.get(0) + a.get(1); for(int i=1, l=a.size(); i<l-1; i++) if(a.get(i) + a.get(i+1)<minV) { minV = a.get(i) + a.get(i+1); minP = i; } return minP; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
java solution
java-solution-by-kishoregantla777-4y7q
IntuitionApproachComplexity Time complexity:O(n^2) Space complexity:O(1) Code
kishoregantla777
NORMAL
2025-04-06T23:47:35.893583+00:00
2025-04-06T23:47:35.893583+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity:O(n^2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { int operation =0; int n=nums.length; int operations=0; while(!isNonDecreasing(nums)){ int minSum= Integer.MAX_VALUE; int minIndex=-1; for(int i=0;i<nums.length-1;i++){ int sum=nums[i]+nums[i+1]; if (sum <minSum){ minSum=sum; minIndex=i; } } nums[minIndex]=minSum; int[]newNums=new int [nums.length-1]; int j=0; for(int i=0;i<nums.length;i++){ if(i!=minIndex+1){ newNums[j++]=nums[i]; } } nums=newNums; operations++; } return operations; } private boolean isNonDecreasing(int[] nums){ int n=nums.length; for(int i=0;i<n-1;i++){ if(nums[i]>nums[i+1]){ return false; } } return true; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Java with O(n^2) Complexity.
java-with-on2-complexity-by-umapada-ys65
IntuitionIn each iteration find the minimum pair and replace with its sum until array is in increasing order.Approach Convert array to List. Check if it is in i
umapada
NORMAL
2025-04-06T22:55:28.762346+00:00
2025-04-06T22:55:28.762346+00:00
5
false
# Intuition In each iteration find the minimum pair and replace with its sum until array is in increasing order. # Approach <!-- Describe your approach to solving the problem. --> 1. Convert array to List. 2. Check if it is in increasing order, then return zero. 3. Until the list become in increasing order, find the pair with minimum sum and replace it with its sum. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(n^2)$$ Finding/replacing the pair then check if it is in increasing order. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(n)$$ Store the array in the List # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList()); var count = 0 ; if(isNonDecreasing(list)) return count; var pivot = 0; var min = 0; do{ min = Integer.MAX_VALUE; count++; for(var i=0; i< list.size() - 1; i++){ var temp = list.get(i) + list.get(i+1); if(temp < min){ min = temp; pivot = i; } } list.set(pivot, min); list.remove(pivot+1); }while(!isNonDecreasing(list)); return count; } boolean isNonDecreasing(List<Integer> list){ for(var i=0; i< list.size() - 1; i++){ if(list.get(i) > list.get(i+1)) return false; } return true; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Track Min Pair Sum And if It's InOrder
track-min-pair-sum-and-if-its-inorder-by-42aj
IntuitionApproachComplexity Time complexity: Space complexity: Code
linda2024
NORMAL
2025-04-06T22:45:11.650123+00:00
2025-04-06T22:45:11.650123+00:00
25
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```csharp [] public class Solution { public int MinimumPairRemoval(int[] nums) { int len = nums.Length, opt = 0; if(len < 2) return 0; List<int> sample = nums.ToList(); bool inOrder = false; while(true) { int[] preCheck = [int.MaxValue, -1]; int sum = sample[0]; bool checkValid = true; for(int i = 1; i < sample.Count; i++) { if(sample[i] < sample[i-1]) checkValid = false; sum += sample[i]; if(i >= 2) sum -= sample[i-2]; if(preCheck[0] > sum) preCheck = [sum, i-1]; } if(checkValid) return opt; sample[preCheck[1]] = preCheck[0]; sample.RemoveAt(preCheck[1]+1); opt++; } return opt; } } ```
0
0
['C#']
0
minimum-pair-removal-to-sort-array-i
C++ 0 ms
c-0-ms-by-eridanoy-ze7h
IntuitionApproachComplexity Time complexity: Space complexity: Code
eridanoy
NORMAL
2025-04-06T21:11:03.658789+00:00
2025-04-06T21:11:03.658789+00:00
10
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int min_sum(const vector<int>& v, const int len) { int pos = 0, min_sum = v[0] + v[1]; for(int i = 1; i < len - 1; ++i) { int sum = v[i] + v[i + 1]; if(sum < min_sum) { min_sum = sum; pos = i; } } return pos; } int minimumPairRemoval(vector<int>& nums) { int count = 0; int len = size(nums); while(len > 1) { if(is_sorted(begin(nums), begin(nums) + len)) break; int i = min_sum(nums, len); nums[i] += nums[i + 1]; rotate(begin(nums) + i + 1, begin(nums) + i + 2, begin(nums) + len); ++count; --len; } return count; } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Easy java solution with 100 percent .
easy-java-solution-with-100-percent-by-u-noeg
IntuitionApproachmain problem is to change the size of array after adding two minSum element . solution is as we add two element we have to increase the count o
u_aremdsufian
NORMAL
2025-04-06T20:58:02.463659+00:00
2025-04-06T20:58:02.463659+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach main problem is to change the size of array after adding two minSum element . solution is as we add two element we have to increase the count or result so by this we can decrese the size of array by 1 every time we increase the result. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { int result = 0; public int minimumPairRemoval(int[] nums) { while(!isSorted(nums)){ mergPairs(nums); result++; } return result; } boolean isSorted(int [ ] nums){ int n = nums.length-result; for(int i=0;i<n-1;i++){ if(nums[i]>nums[i+1]){ return false; } } return true; } void mergPairs(int [ ] nums){ int n = nums.length; int minSum = Integer.MAX_VALUE,minIndex = -1; for(int i=0;i<n-1-result;i++){ int sum = nums[i]+nums[i+1]; if(sum<minSum){ minSum=sum; minIndex = i; } } nums[minIndex] = minSum; shiftLeft(nums,minIndex+1); } void shiftLeft(int [] nums, int idx){ int n = nums.length-result; for(int i=idx;i<n-1;i++){ nums[i]= nums[i+1]; } } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Javascript On^2
javascript-on2-by-plumdot-exxy
null
plumdot
NORMAL
2025-04-06T20:04:41.062859+00:00
2025-04-06T20:04:41.062859+00:00
9
false
```javascript [] /** * @param {number[]} nums * @return {number} */ var minimumPairRemoval = function(nums) { let ans = 0 while (!isNonDecreasing(nums)) { const i = findMinSumPairIndex(nums) const merged = nums[i] + nums[i+1] nums.splice(i, 2, merged) ans += 1 } console.log("ans: ", ans) return ans }; function isNonDecreasing(arr) { for (let i = 1; i < arr.length; i++) { if (arr[i] < arr[i - 1]) return false; } return true; } function findMinSumPairIndex(arr) { let minSum = Infinity; let index = -1; for (let i = 0; i < arr.length - 1; i++) { let sum = arr[i] + arr[i + 1]; if (sum < minSum) { minSum = sum; index = i; } } return index; // index of the leftmost min-sum pair } ```
0
0
['JavaScript']
0
minimum-pair-removal-to-sort-array-i
Python || Easy to Understand || Simple Approach || Readability ||
python-easy-to-understand-simple-approac-b9ug
IntuitionApproachComplexity Time complexity: Space complexity: Code
sankeerthsirikonda
NORMAL
2025-04-06T19:55:54.601856+00:00
2025-04-06T19:55:54.601856+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: operations=0 while(self.is_sorted(nums)==False): self.reduce_minimum_pair(nums) operations+=1 return operations def is_sorted(self,nums): return nums==sorted(nums) def reduce_minimum_pair(self,nums): mini=float('inf') index=0 for i in range(1,len(nums)): if nums[i]+nums[i-1]<mini: mini=nums[i]+nums[i-1] index=i-1 combined = nums[index] + nums[index+1] nums[index:index+2] = [combined] ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Easy & simple
easy-simple-by-sumanth2328-thgk
Code
sumanth2328
NORMAL
2025-04-06T18:19:43.162416+00:00
2025-04-06T18:19:43.162416+00:00
8
false
# Code ```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: def check(n): prefix = [] for i in range(len(n) - 1): prefix.append(n[i] + n[i + 1]) mini = min(prefix) idx = prefix.index(mini) new_nums = n[:idx] + [n[idx] + n[idx + 1]] + n[idx + 2:] return new_nums count = 0 while any(nums[i] > nums[i + 1] for i in range(len(nums) - 1)): nums = check(nums) count += 1 return count ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
java - intutive - for beginners
java-intutive-for-beginners-by-kush888-82q7
Code
Kush888
NORMAL
2025-04-06T17:50:51.850228+00:00
2025-04-06T17:50:51.850228+00:00
5
false
# Code ```java [] import java.util.*; class Solution { public int minimumPairRemoval(int[] nums) { boolean sorted = true; for(int i=0; i<nums.length-1; i++) { if(nums[i] > nums[i+1]) { sorted = false; break; } } if(sorted) return 0; List<Integer> list = new ArrayList<>(); for(int num: nums) list.add(num); int cnt = 0; boolean inc = false; while(!inc) { cnt++; int min = Integer.MAX_VALUE; int idx = -1; for(int i=0; i<list.size()-1; i++) { int ps = list.get(i) + list.get(i+1); if(ps < min) { min = ps; idx = i; } } list.remove(idx); list.add(idx, min); list.remove(idx+1); sorted = true; for(int i=0; i<list.size()-1; i++) { if(list.get(i) > list.get(i+1)) { sorted = false; break; } } if(sorted) inc = true; } return cnt; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
0 ms runtime code with 100% beats!!!
0-ms-runtime-code-with-100-beats-by-arya-myeb
IntuitionApproachComplexity Time complexity: Space complexity: Code
aryankumarrai
NORMAL
2025-04-06T17:42:43.947661+00:00
2025-04-06T17:42:43.947661+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: void shiftLeft(vector<int>& nums, int idx){ int n = nums.size(); for(int i = idx; i < n-1; i++){ nums[i] = nums[i+1]; } nums.pop_back(); } void mergePairs(vector<int>& nums){ int n = nums.size(); int minSum = INT_MAX, minIdx = -1; for(int i = 0; i < n-1; i++){ int sum = nums[i] + nums[i+1]; if(sum < minSum){ minSum = sum; minIdx = i; } } nums[minIdx] = minSum; shiftLeft(nums, minIdx+1); } bool isSorted(vector<int>& nums){ int n = nums.size(); for (int i = 0; i < n-1; i++){ if(nums[i+1] < nums[i]) return false; } return true; } int minimumPairRemoval(vector<int>& nums) { int result = 0; while(!isSorted(nums)){ mergePairs(nums); result++; } return result; } }; ```
0
0
['C++']
0
minimum-pair-removal-to-sort-array-i
Java Solution "3ms" O(N^2) time complexity
java-solution-3ms-on2-time-complexity-by-dmte
IntuitionThe final arr/list should be in ASC orderApproachUpdate as per requirement & loop until it's orderedComplexity Time complexity: O(N^2) Space complex
srinivasvadige
NORMAL
2025-04-06T16:48:53.723330+00:00
2025-04-06T16:48:53.723330+00:00
6
false
# Intuition The final arr/list should be in ASC order # Approach Update as per requirement & loop until it's ordered # Complexity - Time complexity: O(N^2) - Space complexity: O(N) # Code ```java [] class Solution { public int minimumPairRemoval(int[] nums) { List<Integer> lst = new ArrayList<>(); for(int num: nums) lst.add(num); int c = 0; // if not ordered then loop untill it's ordered while(!isOrdered(lst)) { int addI = 0; int minSum = Integer.MAX_VALUE; for(int i=0; i<lst.size()-1; i++) { int currSum = lst.get(i) + lst.get(i+1); if (minSum > currSum) { addI=i; minSum = currSum; } } // update the list --> remove the i+1 element and add it to i element // e.g. [5,2,3,1] --> [5,2,4] --> [5,6] => now it's in order int temp = lst.get(addI+1); lst.remove(addI+1); lst.set(addI, lst.get(addI)+temp); // as we updated the lst then update the counter c++; } return c; } private boolean isOrdered(List<Integer> lst) { int n = lst.size(); if(n==1) return true; for (int i = 0; i< n-1; i++) { if(lst.get(i) > lst.get(i+1)) return false; } return true; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Python Solution
python-solution-by-hgalytoby-nr16
null
hgalytoby
NORMAL
2025-04-06T15:40:52.886928+00:00
2025-04-06T15:40:52.886928+00:00
7
false
```python3 [] class Solution: def minimumPairRemoval(self, nums: List[int]) -> int: count = 0 while not all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)): min_v = math.inf for i in range(len(nums) - 1): v = nums[i] + nums[i + 1] if v < min_v: min_v = v index = i else: nums = nums[:index] + [min_v] + nums[index + 2:] count += 1 return count ```
0
0
['Python3']
0
minimum-pair-removal-to-sort-array-i
Greedily merge the adjacent pair with the smallest sum until the array becomes non-decreasing
greedily-merge-the-adjacent-pair-with-th-zmnp
IntuitionApproachComplexity Time complexity: Space complexity: Code
raviram69358
NORMAL
2025-04-06T15:22:41.145562+00:00
2025-04-06T15:22:41.145562+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] import java.util.*; class Solution { public int minimumPairRemoval(int[] nums) { LinkedList<Integer> list = new LinkedList<>(); for (int num : nums) list.add(num); int operations = 0; while (!isSorted(list)) { int minSum = Integer.MAX_VALUE; int index = -1; for (int i = 0; i < list.size() - 1; i++) { int sum = list.get(i) + list.get(i + 1); if (sum < minSum) { minSum = sum; index = i; } } list.remove(index); list.remove(index); list.add(index, minSum); operations++; } return operations; } private boolean isSorted(List<Integer> list) { for (int i = 1; i < list.size(); i++) { if (list.get(i) < list.get(i - 1)) return false; } return true; } } ```
0
0
['Java']
0
minimum-pair-removal-to-sort-array-i
Beats 100% | C++| Easy
beats-100-c-easy-by-mr-ashutosh-maurya-g22n
Intuition The problem requires transforming an array into a non-decreasing one. The only allowed operation is to merge adjacent elements by replacing them with
mr-ashutosh-maurya
NORMAL
2025-04-06T14:56:41.321780+00:00
2025-04-06T14:56:41.321780+00:00
13
false
# Intuition - The problem requires transforming an array into a non-decreasing one. - The only allowed operation is to merge adjacent elements by replacing them with their sum. - To minimize operations, we remove the leftmost adjacent pair with the smallest sum in each iteration. - The idea is to cause minimal distortion to the overall ordering while steadily fixing violations. # Approach 1. Repeatedly check if the array is non-decreasing using a helper function. 2. If not, find the leftmost adjacent pair whose sum is the smallest. 3. Remove the first element of the pair and replace the second with the sum. 4. Count each such operation. 5. Continue this process until the array becomes non-decreasing. # Complexity - Time complexity: Worst-case: O(n^2), where n is the number of elements in the array. In each operation, we do an O(n) scan and a possible O(n) erase. - Space complexity: O(1) extra space (ignoring the input array), since we modify in place. # Code ```cpp class Solution { public: bool isNonDecreasing(vector<int>& nums) { for (int i = 1; i < nums.size(); i++) { if (nums[i] < nums[i - 1]) return false; } return true; } int minimumPairRemoval(vector<int>& nums) { int ops = 0; // Keep doing operations until the array is non-decreasing while (!isNonDecreasing(nums)) { int minSum = INT_MAX; int minIdx = -1; // Find the leftmost adjacent pair with the smallest sum for (int i = 0; i < nums.size() - 1; i++) { int sum = nums[i] + nums[i + 1]; if (sum < minSum) { minSum = sum; minIdx = i; } } // Replace the pair with their sum nums.erase(nums.begin() + minIdx); // Remove first of the pair nums[minIdx] = minSum; // Replace second with the sum ops++; // Count the operation } return ops; } };
0
0
['C++']
0
increment-submatrices-by-one
[Python3] Sweep Line (Range Addition w/ Visualization), Clean & Concise
python3-sweep-line-range-addition-w-visu-7xwq
Na\xEFve Approach\nFollowing the description of this problem, for each query, we update the every element covered in the submatrix defined by (r1, c1) and (r2,
xil899
NORMAL
2023-01-15T04:12:08.021313+00:00
2023-04-01T19:01:43.205096+00:00
7,084
false
# Na\xEFve Approach\nFollowing the description of this problem, for each query, we update the every element covered in the submatrix defined by `(r1, c1)` and `(r2, c2)`. However, it is pretty clear to know that the time complexity for this approach is $$O(n^2q)$$, which could be up to $$500 \\times 500 \\times 10^4 = 2.5 \\times 10^9$$ and result in TLE.\n\nSo, how can we come up with a better algorithm with improved time complexity?\n\n# Intuition\nThis problem is the 2-D version of [LC 370. Range Addition](https://leetcode.com/problems/range-addition/). Essentially, we are doing range addition for each query.\n\n# Visualization\nConsider the 1-D Range Addition problem and suppose we have `n = 5` and `queries = [[1,3],[2,4],[0,2]]`. Below is the visual illustration on the technique of `Range Caching`.\n\n![LC2536.jpeg](https://assets.leetcode.com/users/images/2db6189c-c45b-4246-b23b-3b679d40d82a_1673763280.9586592.jpeg)\n\n\n# Approach\nFor each query, denoted as `(r1, c1, r2, c2)`, we perform a preprocessing (range caching) on each row involved. Specifically, for each row within `[r1, r2]`, we add 1 at column `c1` and subtract 1 at the next column of `c2`.\n\nAfter preprocessing, we calculate the output by performing range addition (sweeping line) on all elements of the matrix, and output the answer.\n\n# Complexity\n- Time complexity: $$O(n^2 + nq) \\approx O(nq)$$, if $$q \\gg n$$;\n\n- Space complexity: $$O(1)$$, if not including the $$O(n^2)$$ space for output.\n\n**Please upvote if you find this solution helpful. Thanks!**\n\n# Solution (Range Caching)\n```\nclass Solution:\n def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:\n ans = [[0] * n for _ in range(n)]\n for r1, c1, r2, c2 in queries:\n for r in range(r1, r2 + 1):\n ans[r][c1] += 1\n if c2 + 1 < n: ans[r][c2 + 1] -= 1\n for r in range(n):\n for c in range(1, n):\n ans[r][c] += ans[r][c - 1]\n return ans\n```\n\n# Follow-up (Bonus)\nNow we know the concept of range caching technique to solve this problem, is there a even better solution to further improve the overall time complexity?\n\nThe answer is **yes** and the idea is straightforward as visualized below:\n\n![LC2536_2.jpeg](https://assets.leetcode.com/users/images/34c20906-9a2e-44cc-a92e-3a21f92aa688_1673806434.9392116.jpeg)\n\n\nIn brief, we can directly use 2-D range caching (previously we were using 1-D range caching in this 2-D problem). The difference here is that for each query, we now need to (1) cache the value at 4 cells (instead of 2 cells at each row); and (2) calculate the output by going through the full matrix twice, one by row and one by column (instead of once).\n\n- Time complexity: $$O(n^2 + q)$$, which is better than the solution above;\n\n- Space complexity: $$O(1)$$, if not including the $$O(n^2)$$ space for output.\n\n**Remark:** Personally, I feel that 2-D range caching is bit trickier to digest, but using 1-D range caching applied to this problem would be sufficient and easier to think & code.\n\n# Improved Solution (2-D Range Caching)\n```\nclass Solution:\n def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:\n ans = [[0] * n for _ in range(n)]\n for r1, c1, r2, c2 in queries:\n ans[r1][c1] += 1\n if r2 + 1 < n: ans[r2 + 1][c1] -= 1\n if c2 + 1 < n: ans[r1][c2 + 1] -= 1\n if r2 + 1 < n and c2 + 1 < n: ans[r2 + 1][c2 + 1] += 1\n for r in range(1, n):\n for c in range(n):\n ans[r][c] += ans[r - 1][c]\n for r in range(n):\n for c in range(1, n):\n ans[r][c] += ans[r][c - 1]\n return ans\n```
213
3
['Python3']
18
increment-submatrices-by-one
Prefix Sum | C++
prefix-sum-c-by-tusharbhart-7buo
\nclass Solution {\npublic:\n vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {\n vector<vector<int>> mat(n, vector<int>(n, 0
TusharBhart
NORMAL
2023-01-15T04:27:41.755686+00:00
2023-01-15T04:27:41.755730+00:00
8,817
false
```\nclass Solution {\npublic:\n vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {\n vector<vector<int>> mat(n, vector<int>(n, 0));\n \n for (auto q : queries) {\n int r1 = q[0], c1 = q[1], r2 = q[2], c2 = q[3];\n \n mat[r1][c1] += 1;\n if(r2 + 1 < n && c2 + 1 < n) mat[r2 + 1][c2 + 1] += 1;\n if(r2 + 1< n) mat[r2 + 1][c1] -= 1;\n if(c2 + 1 < n) mat[r1][c2 + 1] -= 1;\n }\n \n for(int i=0; i<n; i++) {\n for (int j=1; j<n; j++) {\n mat[i][j] += mat[i][j - 1];\n }\n }\n for(int i=1; i<n; i++) {\n for (int j=0; j<n; j++) {\n mat[i][j] += mat[i - 1][j];\n }\n }\n return mat;\n }\n};\n```
42
2
['Prefix Sum', 'C++']
9
increment-submatrices-by-one
Easy to Understand || Prefix Sum || With Explanation || Not brute force || C++ Solution
easy-to-understand-prefix-sum-with-expla-0g12
hint \n1) try to solve using some pre computation, like some variation in prefix sum. \n\n \n\n# Complexity\n- Time complexity: O(queries.size()n + nn)\n
bharat_bardiya
NORMAL
2023-01-15T06:53:23.876679+00:00
2023-01-20T16:38:31.524760+00:00
3,110
false
# hint \n1) try to solve using some pre computation, like some variation in prefix sum. \n\n \n\n# Complexity\n- Time complexity: $$O(queries.size()*n + n*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n*n)$$ (for storing answer)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {\n \n\n/*\napproach-\n let n = 3, queries = [[1,1,2,2],[0,0,1,1]]\n\n make a ans array of size n*(n+1)\n ans = 0 0 0 0\n 0 0 0 0\n 0 0 0 0\n for every query :\n make all row from x1 to x2 \n ans[i][y1]++; ans[i][y2+1]--;\n \n after first iteration:\n ans = 0 0 0 0\n 0 1 0 -1\n 0 1 0 -1\n after second iteration:\n ans = 1 0 -1 0\n 1 1 -1 -1\n 0 1 0 -1\n why ans[i][y1]++ and ans[i][y2+1]-- ??\n -> (i,y1) indicates that this perticular query contribute 1 from this index so we add 1 in ans.\n -> (i,y2+1) indicates that this perticular query no longer contributes any 1 so we subtract 1 in ans.\n\n\n now calculate prefix sum of every row;\n ans = 1 1 0 0\n 1 2 1 0\n 0 1 1 0\n delete the last column.\n return ans;\n*/\n\n vector<int>row1,row2;\n vector<int>fir(n+1,0),sec(n+1,0);\n vector<vector<int>>ans(n,vector<int>(n+1,0));\n \n for(auto x : queries){\n int x1 = x[0], x2 = x[2];\n int y1 = x[1], y2 = x[3];\n \n for(int i = x1; i<=x2; i++){\n ans[i][y1] +=1;\n ans[i][y2+1] -=1;\n }\n }\n \n for(int i = 0; i<n; i++){\n for(int j = 0; j<n; j++){\n if(j>0) ans[i][j] = ans[i][j]+ans[i][j-1];\n }\n }\n for(int i = 0; i<n; i++) ans[i].pop_back();\n\n return ans;\n }\n};\n```
38
3
['Matrix', 'Prefix Sum', 'C++']
8