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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
special-array-with-x-elements-greater-than-or-equal-x | java o(nlogn),step by step easy explain and intuition of hint | java-onlognstep-by-step-easy-explain-and-vnfb | \nclass Solution {\n private static int binSrc(int [] nums , int target){\n int low = 0 ; \n int high = nums.length - 1;\n // when targ | mrrp | NORMAL | 2020-10-05T17:49:33.543588+00:00 | 2020-10-05T18:02:37.014537+00:00 | 377 | false | ```\nclass Solution {\n private static int binSrc(int [] nums , int target){\n int low = 0 ; \n int high = nums.length - 1;\n // when target < min number in array\n if(target < nums[low])\n return low ;\n // when target > max number in array\n if(target > nums[high])\n return high + 1;\n while(low <= high){\n int mid = low + (high - low)/2;\n if(nums[mid] < target)\n low = mid + 1;\n else\n high = mid - 1;\n }\n return low ;\n }\n // pls consdier HINT 1 : very helpful and expand idea , the 1st hint really helped me to solve this .\n \n // this is hint comes from the idea that the min number of elt in the array can be 0 and max \n // number of elts in array can be n , so lets say when x == 0 , we need 0 elts >= x \n // OR when x == n , we need n elts >= x , so just think aboutt it for a minute\n \n // in any case x MUST lie in the range (0 , n) and when x >= n + 1 , we dont need to continue anymore \n // because it is evident we cannot satisfy the requiredd condition anymore\n \n \n // STEPS -> \n // 1 . sort nums \n // 2 . search for every x in range[0 , nums.length] number of elts strictly < x , we can do this by finding the \n // first occurence of x (if it exists) OR by finding the insert position of X (if it does not exist)\n // 3 . get the insert postion and calculate how many elts greater >= x , if condition satisfies return x \n // else return -1 \n \n public int specialArray(int[] nums) {\n // O(nlogn)\n Arrays.sort(nums);\n int n = nums.length ;\n // O(nlogn)\n for(int x = 0 ; x <= n ; x++){\n int elements_Smaller_thanX = binSrc(nums, x);\n if(n - elements_Smaller_thanX == x)\n return x ;\n }\n \n return -1 ;\n }\n}\n```\nhope this helps tysm | 5 | 0 | [] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Good explanation with simple approach. | good-explanation-with-simple-approach-by-q3bd | Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe problem seems to be about finding a "special" integer in an array. A special inte | aria_vikneesh | NORMAL | 2024-05-28T06:39:39.247470+00:00 | 2024-05-28T06:39:39.247494+00:00 | 31 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe problem seems to be about finding a "special" integer in an array. A special integer is one where the count of elements greater than or equal to it is exactly equal to the value of the integer itself.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis approach iterates through potential special integers, checks how many elements are greater than or equal to each potential special integer, and returns the first special integer found.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nint specialArray(int* nums, int numsSize) {\n int i, j, count;\n for (i = 0; i <= numsSize; ++i) {\n count=0;\n for (j = 0; j < numsSize; ++j) {\n if (nums[j] >= i) {\n count++;\n }\n }\n if (count == i) {\n return i;\n }\n }\n return -1;\n}\n``` | 4 | 0 | ['C'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Python✅ In-Built✅ Function.. Beats 100%🔥🔥 | python-in-built-function-beats-100-by-21-g0lf | Here we are using bisect concept that will tell us where the element is to fitted as a binary search parameter !! we just have to check from descending order w | 21eca01 | NORMAL | 2024-05-27T03:53:36.647014+00:00 | 2024-05-27T03:59:18.284536+00:00 | 923 | false | Here we are using bisect concept that will tell us where the element is to fitted as a binary search parameter !! we just have to check from descending order whether the value satisfies the condition or not!!\n# Code\n```\nimport bisect\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums=sorted(nums)\n n=len(nums)\n for i in range(n,0,-1):\n // It will find the ind at which the element is to be inserted\n k=bisect.bisect_left(nums,i)\n if(n-k==i):\n return i\n return -1\n\n\n``` | 4 | 0 | ['Python3'] | 3 |
special-array-with-x-elements-greater-than-or-equal-x | C++||beats 100%||0 ms|| binary search | cbeats-1000-ms-binary-search-by-jayasury-i25t | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | jayasurya1922 | NORMAL | 2023-04-10T08:04:37.752983+00:00 | 2023-04-10T08:04:57.742954+00:00 | 625 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int insert_pos(int x,vector<int>& nums){\n int low = 0;\n int high = nums.size()-1;\n while(low<= high){\n int mid = low +(high-low)/2;\n if(nums[mid]>=x){\n high = mid-1;\n }else{\n low = mid+1;\n }\n }\n return nums.size()-low; \n }\n int specialArray(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int low = 0;\n \n int high = nums.size();\n while(low <= high){\n int mid = low +(high-low)/2;\n int b = insert_pos(mid,nums);\n if(b == mid ){\n return mid; \n }\n if(b > mid){\n low = mid+1;\n }else{\n high = mid-1;\n }\n }\n return -1;}\n};\n``` | 4 | 0 | ['C++'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | Beats 100% Easy CPP SOL | beats-100-easy-cpp-sol-by-zenitsu02-x0vg | PLEASE UPVOTE ME\uD83E\uDD79\n# Complexity\n- Time complexity: NLog(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\npublic:\n\n\n // function f | Zenitsu02 | NORMAL | 2023-04-08T04:56:46.425658+00:00 | 2023-04-08T04:56:46.425691+00:00 | 342 | false | # **PLEASE UPVOTE ME\uD83E\uDD79**\n# Complexity\n- Time complexity: NLog(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n\n\n // function for find element \n int findElement(vector<int>&nums, int no){\n int ans = 0;\n for(int i = 0; i<nums.size(); i++){\n if(nums[i] >= no){\n ans += 1;\n }\n }\n return ans;\n }\n\n int specialArray(vector<int>& nums) {\n int si = 0;\n int ei = *max_element(nums.begin(), nums.end());\n\n while(si <= ei){\n int mid = si + (ei-si)/2;\n\n if(findElement(nums, mid) == mid){\n return mid;\n }\n\n else if(findElement(nums, mid) > mid){\n si = mid+1;\n }\n\n else{\n ei = mid-1;\n }\n }\n\n return -1;\n }\n};\n```\n\n**BEATS 100%**\n**PLEASE UPVOTE ME\uD83E\uDD79**\n | 4 | 0 | ['C++'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | 0ms || Faster || Easy C++ | 0ms-faster-easy-c-by-amit2024-e4z6 | Intuition\nBinary Search\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1) \n\n# Code\n\nclass Solution {\npublic:\n\n int specialAr | amit2024 | NORMAL | 2023-03-11T10:05:06.393297+00:00 | 2023-04-30T13:54:25.674866+00:00 | 560 | false | # Intuition\nBinary Search\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1) \n\n# Code\n```\nclass Solution {\npublic:\n\n int specialArray(vector<int>& nums) {\n int max = INT_MIN;\n for(auto x: nums){\n if(x>max){\n max=x;\n }\n }\n int l = 0;\n int h = max;\n\n sort(nums.begin(),nums.end());\n \n int ctr=0;\n while(l<=h){\n ctr=0;\n int mid = l+(h-l)/2;\n \n for(int i=0; i<nums.size(); i++){\n if(nums[i]>=mid){\n ctr++;\n }\n }\n if(ctr==mid){\n return mid;\n }\n if(ctr<mid){\n h = mid-1;\n }\n else{\n l = mid+1;\n }\n }\n\n return -1;\n }\n};\n``` | 4 | 0 | ['Binary Search', 'C'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | java || binary search | java-binary-search-by-bhardwajankit1412-emqr | \n\n# Code\n\nclass Solution {\n public int specialArray(int[] nums) {\n int end=nums.length;\n int start=0;\n while(start<=end){\n | bhardwajankit1412 | NORMAL | 2023-01-30T18:31:26.791015+00:00 | 2023-01-30T18:31:26.791064+00:00 | 442 | false | \n\n# Code\n```\nclass Solution {\n public int specialArray(int[] nums) {\n int end=nums.length;\n int start=0;\n while(start<=end){\n int mid=start+(end-start)/2;\n int count=0;\n for(int i=0;i<nums.length;i++){\n if(nums[i]>=mid) count++;\n }\n if(count==mid) \n return mid;\n if(count>mid)\n start=mid+1;\n else\n end=mid-1;\n }\n return -1;\n }\n}\n``` | 4 | 0 | ['Binary Search', 'Java'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | Two java solutions with explanation🔥|| Easy To Understand | two-java-solutions-with-explanation-easy-aeg3 | In this post I shall share two solutions in Java language but can be easily understood by any language user.\n1. Linear search of number of elements greater tha | anujpanchal2001 | NORMAL | 2022-10-20T14:34:30.422572+00:00 | 2022-10-22T13:21:26.445044+00:00 | 988 | false | In this post I shall share two solutions in Java language but can be easily understood by any language user.\n1. **Linear search of number of elements greater than x**\n\tTime Complexity: O(n * log(max(nums)))\n\tSpace Complexity: O(1)\n\tRuntime: 1ms\n\tBeats: 92.31%\n\tIn this method we binary search over the answer for getting x and then checking if the mid element satisfies the problem constraint.\n\t```\n\tclass Solution {\n\t\tpublic int specialArray(int[] nums) {\n\t\t\tint left = 0;\n\t\t\tint right = nums.length;\n\t\t\tint ans = -1;\n\t\t\t while(left <= right) {\n\t\t\t\tint mid = left + (right - left)/2;\n\t\t\t\tint count = 0;\n\t\t\t\tfor(int i: nums) {\n\t\t\t\t\tif(i >= mid) {\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(count == mid) {\n\t\t\t\t\tans = mid;\n\t\t\t\t\tbreak;\n\t\t\t\t}else if(count > mid) {\n\t\t\t\t\tleft = mid + 1;\n\t\t\t\t}else {\n\t\t\t\t\tright = mid - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t}\n\t```\n\t2.**Using prefix array**\n\t Time Complexity: O(n + max(nums))\n\t Space Complexity: O(max(nums))\n\t Runtime: 3ms\n\t Beats: 40.44%\n\t In this method we get the number of elements greater than particular element using prefix array and retreiving the count in constant time.\n\t ```\n\t class Solution {\n\t\tpublic int specialArray(int[] nums) {\n\t\t\tint left = 0;\n\t\t\tint right = nums.length;\n\t\t\tint ans = -1;\n\t\t\tint max = nums[0];\n\t\t\tfor(int i=0;i<nums.length;i++) {\n\t\t\t\tif(nums[i] > max)\n\t\t\t\t\tmax = nums[i];\n\t\t\t}\n\t\t\tint[] prefix = new int[max + 1];\n\t\t\tfor(int i=0;i<nums.length;i++) {\n\t\t\t\tprefix[nums[i]]++;\n\t\t\t}\n\t\t\tfor(int i=max - 1;i>=0;i--) {\n\t\t\t\tprefix[i] = prefix[i + 1] + prefix[i];\n\t\t\t}\n\t\t\twhile(left <= right) {\n\t\t\t\tint mid = left + (right - left)/2;\n\n\t\t\t\tint count = mid > max? 0: prefix[mid];\n\t\t\t\tif(count == mid) {\n\t\t\t\t\tans = mid;\n\t\t\t\t\tbreak;\n\t\t\t\t}else if(count > mid) {\n\t\t\t\t\tleft = mid + 1;\n\t\t\t\t}else {\n\t\t\t\t\tright = mid - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t}\n``` | 4 | 0 | ['Binary Tree', 'Java'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | Python Bucket sort O(n) | python-bucket-sort-on-by-xinyulrsm-gz86 | Since the possible value are less than 1000, we shoud consider bucket sort instead of quick sort or merge sort. Bucket sort nake the solution has time O(n) and | xinyulrsm | NORMAL | 2022-10-19T23:49:49.303581+00:00 | 2022-10-20T00:05:17.550972+00:00 | 512 | false | Since the possible value are less than 1000, we shoud consider bucket sort instead of quick sort or merge sort. Bucket sort nake the solution has time O(n) and space O(1). Hope the code is self explanatory.\n\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n \n N, MAX_SIZE = len(nums), 1001\n \n temp_sum, counts = 0, [0] * MAX_SIZE\n \n for num in nums:\n counts[num] += 1\n \n for i, cnt in enumerate(counts):\n \n if N - temp_sum == i:\n return i\n \n temp_sum += cnt\n \n return -1\n```\n\nAfter posted this, found another O(n) solution :) https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/2709600/Python-O(n)-Solution\n | 4 | 0 | ['Bucket Sort', 'Python'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | Java Binary Search! EASY 100% faster! | java-binary-search-easy-100-faster-by-de-4ugx | Just take the search space of 0 to length of array!\n\nclass Solution {\n public int specialArray(int[] nums) {\n int high=nums.length;\n int l | deity0503 | NORMAL | 2022-10-08T22:57:36.011429+00:00 | 2022-10-08T22:57:36.011466+00:00 | 809 | false | **Just take the search space of 0 to length of array!**\n```\nclass Solution {\n public int specialArray(int[] nums) {\n int high=nums.length;\n int low=0;\n while(low<=high){\n int mid=low+(high-low)/2;\n int count=0;\n for(int i=0;i<nums.length;i++){\n if(nums[i]>=mid) count++;\n }\n if(count==mid) return mid;\n if(count>mid)low=mid+1;\n else high=mid-1;\n }\n return -1;\n }\n}\n``` | 4 | 0 | ['Binary Tree', 'Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Java Solution with Detailed Explanation (Binary Search) | java-solution-with-detailed-explanation-li6oo | Please upvote if this helps you! :)\n\nAs per the description we need to find a value x which may/may not exist in the array that has exactly x numbers in the a | eshikarya | NORMAL | 2022-10-01T15:29:31.940369+00:00 | 2022-10-02T10:06:03.657302+00:00 | 426 | false | ### Please upvote if this helps you! :)\n\nAs per the description we need to find a value x which may/may not exist in the array that has exactly x numbers in the array greater than or equal to it.\n\n\n*Code Breakdown:*\n\nclass Solution {\n public int specialArray(int[] nums) {\n\n1.\tInititalise start and end variables.\n\t``` \t int start = 0, end =Integer.MIN_VALUE;```\n\t\n2. We set the value of end equal to the maximum value in the nums array.\n\t\t##### Reason for this?\n\t\tT*o find a value of x that may have values greater than or equal to it we start with the value of x = 0. Now, for the nums array, the maximum value existing will have no number that is greater than it in the array*.\n\t\t\n\t```nums = [0,2,4,1,5];```\n\t\tmax value is 5.\n\t\t\n\tThere is no number greater than it, therefore if we set x = 5, we can never find exactly 5 values in the array that are greater than or equal to it.\n\tThis implies that x can at max have a value of 5 according to this array (i.e the max value of array)\n\t\t\n\t\tfor(int num:nums){\n end = Math.max(num,end);\n }\n\t\t\n\n3. Start of while loop\n\t``` while(start<=end){```\n\n4. Initialising a mid value (this formula to avoid integer overflow)\n\t```int mid = start + (end-start)/2;```\n \n\n5. Count variable is used to keep a track of the values exisiting in the array that are greater than or equal to a certain x value in the range between start and end of x.\n\n```\n\tint count = 0;\n\tfor(int num:nums){\n\t\t\t\t\tif(num>=mid){\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t}\n```\n\n\t\t\t\t\n6. If there are exactly x values in the array (count) which are greater than or equal to a certain value of x (mid) we return this value.\n \n if(count==mid){\n return mid;\n }\n\n7. If count is greater than the current value of x (defined by mid here), we look for a greater value in the range of x which may provide us with the solution.\n```\n\telse if(count>mid){\n\t\t\t\t\tstart = mid+1;\n\t\t\t\t}\n```\n \n8. If count is less than the current value of x (defined by mid here), we look for a smaller value in the range of x which may provide us with the solution.\n ```\n\t\t\telse{\n end = mid-1;\n }\n } //while loop ends here\n```\n\n8. Return default value of -1 if ans not found.\n\t ```\n\treturn -1;\n\t\t } //specialArray method ends here\n\t\t } //Solution class ends here\n\t```\n\n\n-------------------------------------------------------------------------------------------\n *Entire Java Code*\n\n```\nclass Solution {\n public int specialArray(int[] nums) {\n int start = 0, end =Integer.MIN_VALUE;\n \n for(int num:nums){\n end = Math.max(num,end);\n }\n \n \n while(start<=end){\n int mid = start + (end-start)/2;\n int count = 0;\n \n for(int num:nums){\n if(num>=mid){\n count++;\n }\n }\n \n if(count==mid){\n return mid;\n }\n else if(count>mid){\n start = mid+1;\n }\n else{\n end = mid-1;\n }\n } \n return -1;\n }\n}\n``` | 4 | 0 | ['Binary Tree', 'Java'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | c++|| simple solution using binary search | c-simple-solution-using-binary-search-by-fb97 | \nclass Solution {\npublic:\n int count(int x,vector<int> nums){\n int index=lower_bound(nums.begin(),nums.end(),x)-nums.begin();\n return nums | ALS_Venky | NORMAL | 2022-07-22T07:52:23.884417+00:00 | 2022-07-22T07:52:23.884457+00:00 | 148 | false | ```\nclass Solution {\npublic:\n int count(int x,vector<int> nums){\n int index=lower_bound(nums.begin(),nums.end(),x)-nums.begin();\n return nums.size()-index;\n }\n int specialArray(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int max=nums[nums.size()-1],min=0,mid;\n while(min<=max){\n mid=min+(max-min)/2;\n if(mid==count(mid,nums)){\n return mid;\n }else if(mid<count(mid,nums)){\n min=mid+1;\n }else {\n max=mid-1;\n }\n }\n return -1;\n }\n};\n``` | 4 | 0 | ['Binary Search'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Runtime: 1 ms, easiest solution | runtime-1-ms-easiest-solution-by-rustee_-un6f | \npublic int specialArray(int[] nums) {\n int high=0;\n for(int i=0;i<nums.length;i++){\n if(high<nums[i]){\n high=nums[ | rustee_95 | NORMAL | 2021-12-04T10:50:53.266685+00:00 | 2021-12-04T10:50:53.266714+00:00 | 325 | false | ```\npublic int specialArray(int[] nums) {\n int high=0;\n for(int i=0;i<nums.length;i++){\n if(high<nums[i]){\n high=nums[i];\n }\n }\n \n for(int i=0;i<=high;i++){\n int count=0;\n for(int j=0;j<nums.length;j++){\n if(i<=nums[j]){\n count++;\n }\n }\n if(count==i){\n return i;\n }\n }\n \n return -1;\n \n}\n``` | 4 | 0 | ['Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Python binary search O(nLogn) faster than 95%. With explanation | python-binary-search-onlogn-faster-than-awy44 | Our goal is to find if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Lets say the special number is | akashveneno | NORMAL | 2021-07-20T16:24:18.416607+00:00 | 2021-08-08T13:47:00.444808+00:00 | 251 | false | Our goal is to find if there exists a number `x` such that there are exactly x numbers in `nums` that are greater than or equal to `x`. Lets say the special number is two, which means there are exactly two numbers greater than or equal to 2. The value of x can be between `0` and `max(nums)`. So we sort the array and use binary search to check if any such number exists. \n\n`bisect.bisect_left(nums,mid)`\nGives us the left most position for the number `mid` (Since we have the condition as greater than or equal to). If the number of elements to right of `mid` is equal to `mid`, it is the required number. Else, there are two possibilities,\n* If the number of elements to the right is less than `mid`, it means the value of `mid` must be higher. So we start the binary search from mid+1. \n* If the number of elements to the right is greater than `mid`, it means the value of `mid` must be lower. So we start the binary search up to mid-1. \nWe do this repeatedly until we find a suitable number that fits our condition, else we return -1. \n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n low , high = 0 , max(nums)\n nums.sort()\n while low <= high:\n mid = (low+high)//2\n pos = bisect.bisect_left(nums,mid)\n if len(nums) - pos == mid:\n return mid\n elif len(nums) - pos< mid:\n high = mid-1\n else:\n low = mid+1\n return -1\n``` | 4 | 0 | [] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | a few solutions | a-few-solutions-by-claytonjwong-pntj | Let N be the cardinality of A, then consider all possible values from 0..N inclusive as the ith special value. Return i if and only if the lower bound of i in | claytonjwong | NORMAL | 2020-10-04T04:00:40.091716+00:00 | 2023-05-16T02:08:53.364300+00:00 | 1,356 | false | Let `N` be the cardinality of `A`, then consider all possible values from `0..N` inclusive as the `i`<sup>th</sup> special value. Return `i` if and only if the lower bound of `i` in the sorted array `A` equals `N - i`, otherwise return `-1`.\n \n**Note:** Javascript does *not* have built-in language support for binary search, so [we can use this gist](https://gist.github.com/claytonjwong/53bd1c1489b12eccad176addb8afd8e0) from which I copy/pasted the `lowerBound` function.\n\n---\n\n*Javascript*\n```\nlet lowerBound = (A, T) => {\n let N = A.length,\n i = 0,\n j = N;\n while (i < j) {\n let k = Math.floor((i + j) / 2);\n if (A[k] < T)\n i = k + 1;\n else\n j = k;\n }\n return i;\n};\nlet specialArray = A => {\n let N = A.length;\n A.sort((a, b) => a - b);\n for (let i = 0; i <= N; ++i)\n if (lowerBound(A, i) == N - i)\n return i;\n return -1;\n};\n```\n\n*Python3*\n```\nclass Solution:\n def specialArray(self, A: List[int]) -> int:\n N = len(A)\n A.sort()\n for i in range(N + 1):\n if bisect_left(A, i) == N - i:\n return i\n return -1\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using VI = vector<int>;\n int specialArray(VI& A) {\n int N = A.size();\n sort(A.begin(), A.end());\n for (auto i{ 0 }; i <= N; ++i)\n if (distance(A.begin(), lower_bound(A.begin(), A.end(), i)) == N - i)\n return i;\n return -1;\n }\n};\n``` | 4 | 0 | [] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Beats 100% | Most elaborative solution | JAVA || | beats-100-most-elaborative-solution-java-18yk | Intuition\nThe problem is about finding a special integer x such that there are exactly x elements in the array nums that are greater than or equal to x. To ach | theDummy | NORMAL | 2024-09-07T05:31:48.706060+00:00 | 2024-09-07T05:31:48.706083+00:00 | 57 | false | # Intuition\nThe problem is about finding a special integer x such that there are exactly x elements in the array nums that are greater than or equal to x. To achieve this, the approach checks every possible value of x (from 0 to nums.length) and counts how many elements in the array are greater than or equal to x.\n\n# Approach\nInitialize a counting array countHold of size nums.length + 1. This array is used to count how many numbers are greater than or equal to each possible value of x.\nIterate through each possible value of x (from 0 to nums.length):\nFor each x, the isGreaterOrEqual method is used to check how many elements in nums are greater than or equal to x.\nIf the count of elements is equal to x, return x as the special value.\nReturn -1 if no special value is found after checking all possible values.\n# Complexity\n- Time complexity: O(n\xB2).\n\n- Space complexity: O(n)\n\n# Code\n```java []\nclass Solution {\n public int specialArray(int[] nums) {\n int[] countHold=new int[nums.length+1];\n\n for(int x=0;x<countHold.length;x++)\n {\n if(isGreaterOrEqual(countHold,nums,x)){return x;}\n } \n return -1;\n } \n\n\n\n public static boolean isGreaterOrEqual(int[] countHold,int[] nums,int i){\n countHold[i]=0;\n for(int j=0;j<nums.length;j++)\n {\n if(nums[j]>=i){countHold[i]=countHold[i]+1;}\n }\n if(i==countHold[i]){return true;}\n return false;\n }\n} \n``` | 3 | 0 | ['Array', 'Binary Search', 'Sorting', 'Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | How to Quickly find if the Array is Speacial or not | how-to-quickly-find-if-the-array-is-spea-zyxp | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | vansh0123 | NORMAL | 2024-08-06T18:07:21.806783+00:00 | 2024-08-06T18:07:21.806816+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int specialArray(int[] nums) {\n for(int i=1;i<=nums.length;i++)\n {\n if(i==check(nums,i))\n {\n return i;\n }\n }\n return -1;\n \n }\n public int check(int nums[],int number)\n {\n int cnt=0;\n for(int i=0;i<nums.length;i++)\n {\n if(nums[i]>=number)\n cnt++;\n }\n return cnt;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | ✅EASY AND SIMPLE SOLUTION✅(Beats 100.00% of users with C++) | easy-and-simple-solutionbeats-10000-of-u-us3h | \n\n# Code\n\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n\n int start = 0;\n i | deleted_user | NORMAL | 2024-05-27T15:23:50.393616+00:00 | 2024-05-27T15:26:40.451439+00:00 | 443 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n\n int start = 0;\n int end = nums.size();\n\n while (start <= end) {\n int mid = start + (end - start) / 2;\n int ans = 0;\n\n for (int num : nums) {\n if (num >= mid){\n ans++; \n } \n }\n if (ans == mid){\n return mid;\n } \n else if (ans > mid){\n start = mid + 1;\n } \n else {\n end = mid - 1;\n }\n \n }\n\n return -1;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Use Prefix Sum Over Frequencies of the Numbers To Find X | Java | C++ | use-prefix-sum-over-frequencies-of-the-n-76o4 | Intuition, approach, and complexity dicussed in video solution in detail.\nhttps://youtu.be/YU4NKz6Yd4w\n# Code\nC++\n\nclass Solution {\npublic:\n int speci | Lazy_Potato_ | NORMAL | 2024-05-27T15:04:38.597336+00:00 | 2024-05-27T15:04:38.597358+00:00 | 308 | false | # Intuition, approach, and complexity dicussed in video solution in detail.\nhttps://youtu.be/YU4NKz6Yd4w\n# Code\nC++\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int size = nums.size();\n \n vector<int> freq(size + 1, 0);\n for (int indx = 0; indx < size; indx++) {\n freq[min(size, nums[indx])]++;\n }\n \n int numGreaterThanOrEqual = 0;\n for (int indx = size; indx >= 1; indx--) {\n numGreaterThanOrEqual += freq[indx];\n if (indx == numGreaterThanOrEqual) {\n return indx;\n }\n }\n \n return -1;\n }\n};\n```\nJava\n```\nclass Solution {\n public int specialArray(int[] nums) {\n int size = nums.length;\n \n int[] freq = new int[size + 1];\n for (int indx = 0; indx < size; indx++) {\n freq[Math.min(size, nums[indx])]++;\n }\n \n int numGreaterThanOrEqual = 0;\n for (int indx = size; indx >= 1; indx--) {\n numGreaterThanOrEqual += freq[indx];\n if (indx == numGreaterThanOrEqual) {\n return indx;\n }\n }\n \n return -1;\n }\n}\n\n``` | 3 | 0 | ['Hash Table', 'Prefix Sum', 'C++', 'Java'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Using Binary Search beats 100% | using-binary-search-beats-100-by-anoop_g-0ird | Intuition\n Binary Search : Lower_bound function use\n\n# Approach\n- Firstly we sorted a array took a largest element as the upper limit to check if there exis | anoop_ghimire08 | NORMAL | 2024-05-27T11:22:09.205368+00:00 | 2024-05-27T11:22:09.205387+00:00 | 15 | false | # Intuition\n Binary Search : Lower_bound function use\n\n# Approach\n- Firstly we sorted a array took a largest element as the upper limit to check if there exist a solution.\n- In for loop we are checking through all the value from 0 to maxm\n- We used lower bound for finding the minimum index at which value is just equal or greater than i.\n- Then after that we are checking our required condition , if there no any value of i then return -1.\n\n# Complexity\n- Time complexity:\n o(mlog(n))\nwhere m is largest number and n is size of nums\n\n- Space complexity:\n O(1);\n\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n for(int i = 0 ; i <= nums[nums.size()-1];i++){\n int j = lower_bound(nums.begin(),nums.end(),i) - nums.begin();\n if(i == nums.size()-j){\n return i;\n }\n }\n return -1;\n }\n};\n``` | 3 | 0 | ['Binary Search', 'C++'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Java Easy to Understand Solution with Explanation || 100% beats | java-easy-to-understand-solution-with-ex-wv9a | Intuition\n> This approach involves creating a hash table to store the count of each number in the array. If a number is greater than the size of the array, its | leo_messi10 | NORMAL | 2024-05-27T10:25:48.818234+00:00 | 2024-05-27T10:25:48.818251+00:00 | 154 | false | # Intuition\n> This approach involves creating a hash table to store the count of each number in the array. If a number is greater than the size of the array, its count is stored in a separate hash slot at index \'size + 1\'. After building the hash table, we iterate through it in reverse order to identify any special numbers. \n\n# Approach\n\n1. **Initialization**:\n - `size` is set to the length of the array `nums`.\n - An array `hash` of size `size + 1` is initialized to keep count of the numbers. The extra element handles cases where numbers are greater than the length of the array.\n2. **Count Frequencies**:\n - Iterate through each number `i` in `nums`.\n - If i is greater than `size`, increment `hash[size]` to count numbers greater than size.\n - Otherwise, increment `hash[i]` to count occurrences of i.\n3. **Initialize Answer Variable**:\n - `ans` is initialized to 0. This variable will be used to accumulate counts of numbers greater than or equal to the current index.\n4. **Check Special Property**:\n - Iterate from `size` down to 1. For each index `i`, add the count of numbers that are `i` or greater `(hash[i])` to `ans`.\n5. **Determine if Special**:\n - If `ans` equals `i`, return `i` because it means there are exactly `i` numbers in the array that are greater than or equal to `i`.\n - If `ans` exceeds `i`, return -`1` because having more than `i` numbers greater than or equal to i invalidates i as a special number.\n6. **Return -1**:\n - If no such number `x` is found, return `-1`.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity \n- Time complexity: $$O(n)$$, where n is the length of the array nums.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$, as we use an additional hash array of size n + 1.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int specialArray(int[] nums) {\n int size = nums.length;\n int[] hash = new int[size + 1];\n\n for (int i : nums) {\n if (i > size) {\n hash[size]++;\n } else {\n hash[i]++;\n }\n }\n\n int ans = 0;\n\n for (int i = size; i > 0; i--) {\n ans += hash[i];\n\n if (ans == i) {\n return i;\n }\n\n if (ans > i) {\n return -1;\n }\n }\n\n return -1;\n }\n}\n```\n\n\n | 3 | 0 | ['Array', 'Hash Table', 'Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Easy C++ Solution | Beats 100 💯✅ | easy-c-solution-beats-100-by-shobhitkush-kb6u | Intuition and Approach\n\n### Problem Understanding\nThe problem is to find a special integer x such that there are exactly x numbers in the array that are grea | shobhitkushwaha1406 | NORMAL | 2024-05-27T10:19:32.489705+00:00 | 2024-05-27T10:19:32.489723+00:00 | 285 | false | ## Intuition and Approach\n\n### Problem Understanding\nThe problem is to find a special integer `x` such that there are exactly `x` numbers in the array that are greater than or equal to `x`. If such an `x` does not exist, return `-1`.\n\n### Approach\nTo solve this problem, we need to determine a value of `x` that satisfies the given condition. Here\u2019s a step-by-step breakdown of the approach:\n\n1. **Sorting the Array**: First, we sort the array. This helps us efficiently determine how many elements are greater than or equal to any given number using binary search.\n\n2. **Binary Search**: We employ binary search to find the value of `x`. The possible values for `x` range from `0` to the length of the array (inclusive).\n\n3. **Counting Elements**: For each midpoint `mid` in our binary search, we count the number of elements in the array that are greater than or equal to `mid`. This is done using a helper function `count`.\n\n4. **Checking Conditions**: If the count equals `mid`, we return `mid` as the special value. If the count is greater than `mid`, we know we need a larger `x`, so we move the start of our binary search range to `mid + 1`. If the count is less than `mid`, we move the end of our binary search range to `mid - 1`.\n\n5. **Return Result**: If we exit the binary search without finding a valid `x`, we return `-1`.\n\n### Time Complexity\n- **Sorting**: `O(n log n)` where `n` is the number of elements in the array.\n- **Binary Search**: `O(log n)` iterations.\n- **Counting Elements**: Each counting operation is `O(n)`.\n\nSince the counting operation is called within the binary search, the overall time complexity is `O(n log n)` due to the initial sorting.\n\n### Space Complexity\n- **Sorting**: `O(1)` extra space if we sort the array in place.\n- **Binary Search and Counting**: `O(1)` extra space.\n\nTherefore, the overall space complexity is `O(1)` (ignoring the input array space).\n\n### Implementation\n\n```cpp\nclass Solution {\nprivate:\n int count(vector<int>& nums, int target) {\n int ans = 0;\n for (int num : nums) {\n if (num >= target) ans++;\n }\n return ans;\n }\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n\n int start = 0;\n int end = nums.size();\n\n while (start <= end) {\n int mid = start + (end - start) / 2;\n int ans = count(nums, mid);\n\n if (ans == mid) return mid;\n else if (ans > mid) start = mid + 1;\n else end = mid - 1;\n }\n return -1;\n }\n};\n | 3 | 0 | ['Array', 'Binary Search', 'Sorting', 'C++'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | simple python solution beats 99%. | simple-python-solution-beats-99-by-utkar-qt05 | \n\n# Code\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n=len(nums)\n for i in range(n+1):\n | Utkarshydv | NORMAL | 2024-05-27T08:36:09.547956+00:00 | 2024-05-27T08:36:09.547998+00:00 | 378 | false | \n\n# Code\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n=len(nums)\n for i in range(n+1):\n c=i\n for j in nums:\n if j>=i:\n c-=1\n if c<0:\n break\n if c==0:\n return i\n return -1\n\n\n\n``` | 3 | 0 | ['Python3'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | 0ms - Beats 100% ✅🔥🔥🔥| Python, C++💻 | EASY, CLEAR Explanation📗 | 0ms-beats-100-python-c-easy-clear-explan-iicq | 0ms - Beats 100% \u2705\uD83D\uDD25\uD83D\uDD25\uD83D\uDD25| Python, C++\uD83D\uDCBB | EASY, CLEAR Explanation\uD83D\uDCD7\n\n## 1. Proof\n Describe your first | kcp_1410 | NORMAL | 2024-05-27T07:11:45.476760+00:00 | 2024-05-27T07:11:45.476786+00:00 | 81 | false | # 0ms - Beats 100% \u2705\uD83D\uDD25\uD83D\uDD25\uD83D\uDD25| Python, C++\uD83D\uDCBB | EASY, CLEAR Explanation\uD83D\uDCD7\n\n## 1. Proof\n<!-- Describe your first thoughts on how to solve this problem. -->\n### 1.1. C++\n\n\n### 1.2. Python3\n\n\n\n## 2. Algorithms\n* Sorting\n\n## 3. Code (with explanation each line)\n```python3 []\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n N = len(nums)\n nums.sort()\n for i in range(N):\n x = N - i # The number of elements on the right and including current, and possibly the result `x` up to this `i` index if this `x` is valid\n # Check for validity\n # nums[i] >= x: There\'re \'x\' elements on the right & current, so if `current >= x` that means there\'re `x` numbers on the right & current greater than `x` (sorted array)\n # max_of_left: max number on the left - we need to make sure there\'s no number greater than `x` on the left, thus `x > greatest_num_on_the_left` (sorted array)\n max_of_left = nums[i - 1] if i - 1 >= 0 else 0\n if nums[i] >= x and x > max_of_left:\n return x\n return -1\n```\n\n```cpp []\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int N = nums.size();\n sort(nums.begin(), nums.end());\n int x, max_of_left;\n for (int i=0; i < N; i++) {\n x = N - i;\n max_of_left = (i - 1 >= 0) ? nums[i - 1] : 0;\n if ((nums[i] >= x) && (x > max_of_left)) {\n return x;\n }\n }\n return -1;\n }\n};\n```\n\n## 4. Complexity\n- Time complexity: $$O(N + Nlog(N))$$ sorting & array traversing\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n### Upvote if you find this solution helpful, thank you \uD83E\uDD0D | 3 | 0 | ['Array', 'Sorting', 'C++', 'Python3'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | EASY ASS✅✅69_BEATS_100%✅✅🔥Easy Solution🔥With Explanation🔥 | easy-ass69_beats_100easy-solutionwith-ex-hwwk | Intuition\n Describe your first thoughts on how to solve this problem. \nwe need to find out a number x suxh that there are exactly x numbers in nums that are > | srinivas_bodduru | NORMAL | 2024-05-27T05:11:56.367186+00:00 | 2024-05-27T05:11:56.367205+00:00 | 405 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe need to find out a number x suxh that there are exactly x numbers in nums that are >= x\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe need to sort nums\nfrom then if the number x was to be the max which is length of nums\nthen the first element in our sorted arr should be equal to or greater\nthan length \nsubsequently the next element should be greater than or equal to len-1\nso on .....\n# Complexity\n- Time complexity:O(NlogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```javascript []\nvar specialArray = function(nums) {\n let len=nums.length\n nums.sort((a,b)=>a-b)\n if(nums[0]>=len)return len\n len--\n for(let i=1;i<nums.length;i++){\n if(nums[i]>=len && nums[i-1]<len){\n return len\n }\n len--\n }\n return -1\n};\n```\n```python []\ndef specialArray(nums):\n nums.sort()\n length = len(nums)\n if nums[0] >= length:\n return length\n length -= 1\n for i in range(1, len(nums)):\n if nums[i] >= length and nums[i - 1] < length:\n return length\n length -= 1\n return -1\n\n# Example usage\nnums = [3, 5, 2, 0, 4]\nprint(specialArray(nums))\n\n```\n```java []\nimport java.util.Arrays;\n\npublic class SpecialArray {\n\n public static int specialArray(int[] nums) {\n int len = nums.length;\n Arrays.sort(nums);\n if (nums[0] >= len) return len;\n len--;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] >= len && nums[i - 1] < len) {\n return len;\n }\n len--;\n }\n return -1;\n }\n\n public static void main(String[] args) {\n int[] nums = {3, 5, 2, 0, 4};\n System.out.println(specialArray(nums)); // Example usage\n }\n}\n\n```\n```c []\n#include <stdio.h>\n\nint specialArray(int nums[], int size) {\n int len = size;\n for (int i = 0; i < len; i++) {\n for (int j = i + 1; j < len; j++) {\n if (nums[i] > nums[j]) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n }\n }\n if (nums[0] >= len) return len;\n len--;\n for (int i = 1; i < size; i++) {\n if (nums[i] >= len && nums[i - 1] < len) {\n return len;\n }\n len--;\n }\n return -1;\n}\n\nint main() {\n int nums[] = {3, 5, 2, 0, 4};\n int size = sizeof(nums) / sizeof(nums[0]);\n printf("%d\\n", specialArray(nums, size)); // Example usage\n return 0;\n}\n\n```\n | 3 | 0 | ['C', 'Python', 'Java', 'Python3', 'JavaScript'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | 0 ms everytime solution... | 0-ms-everytime-solution-by-zen-ghost1-zkxj | Approach\nThe solution is simple enough. Just read the comments in code to understand it.\n\n# Code\n\nclass Solution {\npublic:\n int specialArray(vector<in | zen-ghost1 | NORMAL | 2024-05-27T03:51:07.812249+00:00 | 2024-05-27T03:51:07.812271+00:00 | 181 | false | # Approach\nThe solution is simple enough. Just read the comments in code to understand it.\n\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n // because of constraints specified take array of 1001\n vector<int> c(1001, 0);\n\n // flag is for edge case, we\'ll come to it.\n int flag = 0;\n\n // take a count of each element in array\n for(auto it : nums){\n c[it]++;\n if(it) flag = 1;\n }\n\n // use a flag to handle the second edge case\n if(!flag) return -1;\n\n // Now we will iterate from backwards and count all elements\n int sum = 0;\n\n // for each x we will put the number of elements greater than or equal to it\n for(int i=1000; i>=0; i--){\n sum += c[i];\n c[i] = sum;\n } \n\n // Now check where the elements are exactly equal to index\n for(int i=1000; i>=0; i--){\n if(c[i] == i) return i;\n } \n\n // if no such element found return -1\n\n return -1;\n }\n};\n``` | 3 | 0 | ['C++'] | 3 |
special-array-with-x-elements-greater-than-or-equal-x | Using Hash Map | Python | using-hash-map-python-by-pragya_2305-vjb0 | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n count | pragya_2305 | NORMAL | 2024-05-27T03:27:35.649311+00:00 | 2024-05-27T03:27:35.649334+00:00 | 428 | false | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n count = Counter(nums)\n total_so_far = 0\n\n for i in range(max(nums),-1,-1):\n total_so_far += count[i]\n if total_so_far==i:\n return i\n \n return -1\n``` | 3 | 0 | ['Array', 'Hash Table', 'Python', 'Python3'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Easy || Java || Binary Search || Fully Explained || Please Upvote | easy-java-binary-search-fully-explained-gsfds | The problem is to find a special number $ x $ in an array ${nums}$ such that there are exactly $ x $ numbers in ${nums}$ that are greater than or equal to$ x $. | va-run-6626 | NORMAL | 2024-05-27T01:02:48.455761+00:00 | 2024-05-27T01:13:30.456193+00:00 | 472 | false | The problem is to find a special number $ x $ in an array ${nums}$ such that there are exactly $ x $ numbers in ${nums}$ that are greater than or equal to$ x $. If such a number $ x $ exists, return it; otherwise, return $-1$. It\'s proven that if $ x $ exists, it is unique.\n\n### Intuition\n1. **Sorting Insight**: By sorting the array, we can easily determine how many elements are greater than or equal to any given number by using the properties of a sorted array.\n2. **Binary Search**: We can leverage binary search to efficiently find the special number $ x $. Given a mid-point in the range of possible$ x $ values, we can count the number of elements greater than or equal to $ x $ and compare it to $ x $.\n\n### Approach\n1. **Sort the Array**: Start by sorting the array ${nums}$.\n2. **Binary Search on Possible $ x $ Values**:\n - Use binary search to test potential values for $ x $ in the range from $0$ to ${length of nums}$ $(inclusive)$.\n - For each mid-point $ x $, count the number of elements in ${nums}$ that are greater than or equal to $ x $.\n - If this count equals $ x $, then $ x $ is the special number.\n - If the count is greater than $ x $, it means $ x $ might be smaller than the required special number, so adjust the search range accordingly.\n - If the count is less than $ x $, adjust the search range in the opposite direction.\n\n3. **Return Result**: If no such $ x $ is found during the binary search, return $-1$.\n\n### Example Walkthrough\nConsider the example ${nums} = [0, 4, 3, 0, 4]$:\n- After sorting: $[0, 0, 3, 4, 4] $\n- Using binary search:\n - Check $x = 2$: Count of elements $ \\geq 2 $ is 3 (3, 4, 4), which is not equal to 2.\n - Adjust range and check $x = 3 $: Count of elements $ \\geq 3 $ is 3 (3, 4, 4), which is equal to 3.\n - Return $ 3 $ since it satisfies the condition.\n\n### Complexity Analysis\n- **Time Complexity**:\n - Sorting the array: $ O(n \\log n) $\n - Binary search: $ O(\\log n) $\n - Counting elements during each binary search step: $ O(n) $\n - Total: $ O(n \\log n + n \\log n) = O(n \\log n) $\n\n- **Space Complexity**: $ O(1) $ if sorting is done in-place, otherwise $ O(n) $ for the space used by the sorting algorithm.\n\n### Detailed Code Implementation\n```java []\nimport java.util.Arrays;\n\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums); // Sort the array\n int s = 0;\n int e = nums.length;\n \n // Perform binary search\n while (s <= e) {\n int mid = s + (e - s) / 2;\n int ans = cnt(nums, mid);\n \n if (ans == mid) {\n return mid; // Found the special number\n } else if (ans > mid) {\n s = mid + 1; // Adjust the lower bound\n } else {\n e = mid - 1; // Adjust the upper bound\n }\n }\n return -1; // No special number found\n }\n\n private int cnt(int[] nums, int mid) {\n int count = 0;\n for (int i : nums) {\n if (i >= mid) {\n count++; // Count elements >= mid\n }\n }\n return count;\n }\n}\n```\nThis code efficiently determines the special number $ x $ by combining sorting and binary search techniques, ensuring optimal performance.\n\n\n | 3 | 0 | ['Array', 'Binary Search', 'Sorting', 'Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | ✅ Easy C++ Solution | easy-c-solution-by-moheat-4e02 | Code\n\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int n = nums.size();\n\n sort(nums.begin(),nums.end());\n\n | moheat | NORMAL | 2024-05-27T00:46:50.964272+00:00 | 2024-05-27T00:46:50.964288+00:00 | 2,227 | false | # Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int n = nums.size();\n\n sort(nums.begin(),nums.end());\n\n for(int i=1;i<=n;i++)\n {\n int count = 0;\n for(int j=n-1;j>=0;j--)\n {\n if(nums[j] >= i)\n {\n count++;\n }\n else\n {\n break;\n }\n }\n if(count == i)\n {\n return i;\n }\n }\n return -1;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Binary Search easy solution Beats 100% 🚀🚀🔥 | binary-search-easy-solution-beats-100-by-i31b | Intuition\n Describe your first thoughts on how to solve this problem. \nOur aims is to find a number x such that there are exactly x elements in the input arr | skill_improve | NORMAL | 2024-04-26T12:20:27.085730+00:00 | 2024-04-26T12:20:27.085769+00:00 | 165 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOur aims is to find a number x such that there are exactly x elements in the input array nums that are greater than or equal to x.Here searching so directly think of binary Search on ans.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We start by initializing the range [l, h] as [1, nums.size()].\n1. We then enter a loop where we calculate the middle element mid of the current range.\n1. We count the number of elements in nums that are greater than or equal to mid and store the count in cnt.\n1. If mid is equal to cnt, it means we have found our answer, so we return mid.\n1. If mid is greater than cnt, it means there are more than mid elements greater than or equal to mid, so we need to search in the left half of the range, i.e., we set h = mid - 1.\n1. If mid is less than cnt, it means there are fewer than mid elements greater than or equal to mid, so we need to search in the right half of the range, i.e., we set l = mid + 1.\n1. We repeat this process until l is no longer less than or equal to h.\n1. If we haven\'t found a valid x in the range [1, nums.size()], we return -1.\n\n# Complexity\n- **Time complexity**:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this approach is O(n log n), where n is the size of the input array nums. This is because we are using binary search which takes O(log n) iterations, and in each iteration, we are counting the elements in nums, which takes O(n) time.\n\n- **Space complexity**:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this approach is O(1) because we are using a constant amount of extra space regardless of the input size.\n\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int l=1,h=nums.size();\n while(l<=h){\n int mid=(l+h)/2,cnt=0;\n for(int i=0;i<nums.size();i++){\n if(nums[i]>=mid) cnt++;\n }\n if(mid==cnt) return mid;\n if(mid>cnt) h=mid-1;\n else l=mid+1;\n }\n return -1;\n }\n};\n```\n\nHappy Coding \uD83D\uDE0A\uD83D\uDE0A\n(\u25CF\'\u25E1\'\u25CF)(\u2741\xB4\u25E1`\u2741)(\u25CF\'\u25E1\'\u25CF) | 3 | 0 | ['Array', 'Binary Search', 'Sorting', 'C++'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Kotlin binary search solution without sorting | kotlin-binary-search-solution-without-so-6xbn | \n\n# Code\n\nclass Solution {\n fun specialArray(nums: IntArray): Int {\n var low = 0\n var high = nums.size\n while(low <= high) {\n | chayangkoon | NORMAL | 2024-04-02T14:19:49.855609+00:00 | 2024-04-02T17:28:42.471584+00:00 | 35 | false | \n\n# Code\n```\nclass Solution {\n fun specialArray(nums: IntArray): Int {\n var low = 0\n var high = nums.size\n while(low <= high) {\n val middle = low + (high - low) / 2\n val count = nums.count { it >= middle }\n if(count == middle) {\n return middle\n } else if(count < middle) {\n high = middle - 1\n } else {\n low = middle + 1\n }\n }\n return -1\n }\n}\n``` | 3 | 0 | ['Kotlin'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Easiest Solution using Binary Search | easiest-solution-using-binary-search-by-w001p | Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem can be solved using Binary Search + Linear Search.\n\n# Approach\n Describ | saket_1 | NORMAL | 2023-07-25T08:35:52.647562+00:00 | 2023-07-25T08:35:52.647582+00:00 | 61 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem can be solved using **Binary Search + Linear Search.**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn Binary search we do search on a range of values. So first think that the answer will always lies between [0-array_size].Suppose array size is 5 then answer cant be 6 because there is only 5 elements and it will not satisfy the condition.\n\nDo a Binary Search on [0-array_size].\nFor each iteration see that how many elements are there in array and is it satisfying the solution.\n\nYou can use the lower_bound concept for that.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nIt would be O(array_size*nlogn).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nIt would be O(1)\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n //optimized solution \n //answer ranges between 0 and array length.\n //sort the array to use Binary Search. --> O(nlogn);\n sort(nums.begin(),nums.end());\n int low= 0;\n int high = nums.size(); \n\n while(low<=high){\n int mid = (low+high)/2;\n int lb=lower_bound(nums.begin(),nums.end(),mid)-nums.begin();\n int count = nums.size()-lb;\n if(count == mid) //satisfying the condition\n return mid;\n else if(count>mid) low=mid+1; \n else high = mid-1;\n \n }\n return -1;\n\n }\n};\n``` | 3 | 0 | ['Binary Search', 'Sorting', 'C++'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | Easy two for loops in java | easy-two-for-loops-in-java-by-bhupendra0-cwv0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | bhupendra082002 | NORMAL | 2023-04-07T14:08:42.882024+00:00 | 2023-04-07T14:08:42.882058+00:00 | 264 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int specialArray(int[] nums) {\n for(int i =0; i<=1000; i++){\n int count = 0;\n for(int num : nums){\n if(num>= i)count++;\n }\n if(i==count) return i;\n }\n return -1;\n \n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | JAVA | Simple Solution | Sorting & BinarySearch | java-simple-solution-sorting-binarysearc-zw6j | Complexity\n- Time complexity: O(n * log(n))\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) | ilyastuit | NORMAL | 2023-04-07T06:16:13.512469+00:00 | 2023-05-28T06:08:00.257610+00:00 | 1,010 | false | # Complexity\n- Time complexity: $$O(n * log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n for (int num = 0; num <= nums[n - 1]; num++) {\n int index = findFirstGreaterOrEqual(nums, num);\n if (n - index == num) {\n return num;\n }\n }\n\n return -1;\n }\n\n private int findFirstGreaterOrEqual(int[] nums, int target) {\n int left = 0;\n int right = nums.length - 1;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] >= target) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return left;\n }\n}\n``` | 3 | 0 | ['Array', 'Binary Search', 'Sorting', 'Java'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | EASY JAVA Solution | Beats 100% | easy-java-solution-beats-100-by-kunal_ka-5qyr | \n# Code\n\nclass Solution {\n public int specialArray(int[] nums) {\n int start=0;\n int end=nums.length;\n while(start<=end){\n | kunal_kamble | NORMAL | 2023-03-27T05:43:44.582486+00:00 | 2023-03-27T05:43:44.582530+00:00 | 361 | false | \n# Code\n```\nclass Solution {\n public int specialArray(int[] nums) {\n int start=0;\n int end=nums.length;\n while(start<=end){\n int mid=start+(end-start)/2;\n int count=0;\n for(int i=0;i<nums.length;i++){\n if(nums[i]>=mid){\n count++;\n }\n }\n if(count==mid) return mid;\n if(count>mid) start=mid+1;\n else end=mid-1; \n }\n return -1;\n }\n}\n``` | 3 | 0 | ['Binary Search', 'Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Python - O(n) Solution | python-on-solution-by-prateekgoel7248-qmk5 | \tclass Solution:\n\t\tdef specialArray(self, nums: List[int]) -> int:\n\t\t\tfreq=[0 for _ in range(max(nums)+1)]\n\t\t\tfor i in nums:\n\t\t\t\tfreq[i]+=1\n\t | prateekgoel7248 | NORMAL | 2022-10-16T09:41:51.686520+00:00 | 2022-10-16T09:41:51.686565+00:00 | 1,138 | false | \tclass Solution:\n\t\tdef specialArray(self, nums: List[int]) -> int:\n\t\t\tfreq=[0 for _ in range(max(nums)+1)]\n\t\t\tfor i in nums:\n\t\t\t\tfreq[i]+=1\n\t\t\tsuff=[freq[-1]]\n\t\t\tfor i in freq[::-1][1:]:\n\t\t\t\tsuff.append(suff[-1]+i)\n\t\t\tsuff=suff[::-1]\n\t\t\tfor i in range(max(nums)+1):\n\t\t\t\tif suff[i]==i:\n\t\t\t\t\treturn i\n\t\t\treturn -1\n\n | 3 | 0 | ['Python', 'C++', 'Java', 'Python3'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | C++ | Binary Search | c-binary-search-by-nikhil1947-313f | \nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n\t\n sort(nums.begin(),nums.end());\n int i=nums.size();\n\t\t\n wh | nikhil1947 | NORMAL | 2022-10-03T20:09:12.825429+00:00 | 2022-10-19T21:04:21.862931+00:00 | 1,060 | false | ```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n\t\n sort(nums.begin(),nums.end());\n int i=nums.size();\n\t\t\n while(i>0){\n int start=0,end=nums.size()-1;\n int count=0;\n while(start<=end){\n int mid=start+(end-start)/2;\n if(nums[mid]>=i){\n count+=end-mid+1; // no. of element greater than nums[mid] \n end=mid-1;\n }\n else{\n start=mid+1;\n }\n }\n if(count==i){\n return i;\n }\n i--; \n }\n return -1;\n\t\t\n }\n};\n```\nAnother same approach\n\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(),nums.end()); // sorting so that we can use binary search\n int i=0;\n while(i<=nums.size()){ // to find number of element greater than i\n int start=0,end=nums.size()-1;\n int count=0;\n while(start<=end){\n int mid=start+(end-start)/2;\n if(nums[mid]>=i){ // no. of element greater than nums[mid]\n count+=end-mid+1; // storing the numbers \n end=mid-1;\n }\n else{\n start=mid+1;\n }\n }\n if(count==i){ // after storing if its == i return i\n return i;\n }\n i++; \n }\n return -1;\n }\n};\n | 3 | 0 | ['C', 'Binary Tree'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Simple binary search + Inbuilt sorting | simple-binary-search-inbuilt-sorting-by-aapem | ```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n\t\t//Count the number of elements greater than or equal to x for | Abhinav_0561 | NORMAL | 2022-06-15T10:06:25.429909+00:00 | 2022-06-15T10:06:25.429944+00:00 | 246 | false | ```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n\t\t//Count the number of elements greater than or equal to x for each x in the range [0, nums.length].\n int start = 0 , end = nums.length;\n while (start<=end){\n int mid = start + (end - start)/2;\n if (mid == greaterOrEqualTo(nums,mid)) return mid; //If for any x, the condition satisfies, return that x. \n else if (mid<greaterOrEqualTo(nums,mid)) start = mid+1;\n else end = mid-1;\n }\n return -1;//Otherwise, there is no answer.\n }\n public int greaterOrEqualTo(int[] nums, int mid){\n\t//Method to check the count of numbers greater than or equal to x\n int count = 0;\n for (int i = 0; i < nums.length ; i++) {\n if (nums[i]>=mid) count++;\n }\n return count;\n }\n} | 3 | 0 | ['Sorting', 'Binary Tree', 'Java'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Python O(n) Soln, short and fast | python-on-soln-short-and-fast-by-archit_-0mze | \nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n count, nums = 0, Counter(nums)\n for i in range(max(nums), -1, -1):\n | Archit_Sharma | NORMAL | 2022-04-13T12:25:58.493668+00:00 | 2022-04-13T12:25:58.493711+00:00 | 212 | false | ```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n count, nums = 0, Counter(nums)\n for i in range(max(nums), -1, -1):\n count += nums[i]\n if count == i: \n return count\n return -1 \n``` | 3 | 0 | ['Python'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Java | 2 methods | Explained | java-2-methods-explained-by-prashant404-qdp8 | Method 1: Sort and Binary Search\n>T/S: O(n lg n)/O(n), where n = size(nums)\n\npublic int specialArray(int[] nums) {\n\tvar n = nums.length;\n\treverseSort(num | prashant404 | NORMAL | 2022-01-18T06:16:50.868250+00:00 | 2024-05-27T01:21:39.332878+00:00 | 422 | false | **Method 1:** Sort and Binary Search\n>**T/S:** O(n lg n)/O(n), where n = size(nums)\n```\npublic int specialArray(int[] nums) {\n\tvar n = nums.length;\n\treverseSort(nums, n);\n\treturn binarySearch(nums, n);\n}\n\n// O(n lg n)/O(n)\nprivate void reverseSort(int[] nums, int n) {\n\tArrays.sort(nums);\n\t\n\tfor (var i = 0; i < n / 2; i++)\n\t\tswap(n - i - 1, i, nums);\n}\n\nprivate void swap(int i, int j, int[] nums) {\n\tvar temp = nums[i];\n\tnums[i] = nums[j];\n\tnums[j] = temp;\n}\n\n// O(lg n)/O(1)\nprivate int binarySearch(int[] nums, int n) {\n\tvar high = n;\n\n\tfor (var low = 0; low < high;) {\n\t\tvar mid = low + (high - low) / 2;\n\t\t\n\t\tif (mid < nums[mid])\n\t\t\tlow = mid + 1;\n\t\telse\n\t\t\thigh = mid;\n\t}\n\t\n\treturn low < n && low == nums[low] \n\t\t ? - 1 \n\t\t : low;\n}\n```\n**Method 2:** Count and Search\n* Utilize the constraint that nums[i] \u2208 [0, 1000]\n* Count the frequency of each nums[i] in an array (`numCounts`). Store this count in an array, with frequency of i stored in `numCounts[i]`\n* Now iterate down `numCounts` and reduce total elements (n) by frequency of numbers till this point\n* When n becomes equal to i, you\'ve found the required x\n* If no such x is found, return -1\n\nE.g.\n```\nnums = [0, 4, 3, 0, 4], n = 5\nnumCounts = [2, 0, 0, 1, 2] represents frequency of 0 = 2, 1 = 0, 2 = 0, 3 = 1, 4 = 2\n\nIterate down numCounts\n\n5 elements \u2265 0\n(5 - 2) elements \u2265 1\n(5 - 2 - 0) elements \u2265 2\n(5 - 2 - 0 - 0) elements \u2265 3\n=> 3 elements \u2265 3 \n=> x = 3 [Ans]\n```\n>**T/S:** O(n)/O(1)\n```\nprivate static final int NUM_MAX = 1001;\n\npublic int specialArray(int[] nums) {\n\tvar n = nums.length;\n\tvar numCounts = new int[NUM_MAX];\n\t\n\tfor (var num : nums)\n\t\tnumCounts[num]++;\n\t\n\tfor (var i = 0; i < NUM_MAX; i++) {\n\t\tif (n == i)\n\t\t\treturn i;\n\t\tn -= numCounts[i];\n\t}\n\t\n\treturn -1;\n}\n```\n***Please upvote if this helps*** | 3 | 0 | ['Binary Search', 'Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Intuitive java solution | Binary Search on size array | 100% faster | intuitive-java-solution-binary-search-on-czf3 | ```\nclass Solution {\n public int specialArray(int[] nums) {\n int l = nums.length;\n int lo = 0, hi = l - 1;\n while(lo <= hi)\n | white_harmony | NORMAL | 2021-09-28T07:55:23.241605+00:00 | 2021-09-28T07:55:23.241644+00:00 | 107 | false | ```\nclass Solution {\n public int specialArray(int[] nums) {\n int l = nums.length;\n int lo = 0, hi = l - 1;\n while(lo <= hi)\n {\n int mid = (lo + hi) / 2;\n int diff = special(nums, mid + 1);\n if(diff < 0)\n {\n hi = mid - 1;\n }\n else if(diff > 0)\n {\n lo = mid + 1;\n }\n else\n return mid + 1;\n }\n return -1;\n }\n int special(int[] nums, int x)\n {\n int c = 0;\n for(int i = 0; i < nums.length; i++)\n {\n if(nums[i] >= x)\n c++;\n }\n return c - x;\n }\n}\n | 3 | 0 | [] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Java || Sorting + Binary Search + Counting || 0ms || beats 100% || T.C - O(n) S.C - O(n) | java-sorting-binary-search-counting-0ms-a6heq | \n\t// Linear Search + Sorting\n\t// O(n^2) O(1)\n\tpublic int specialArray1(int[] nums) {\n\n\t\tint len = nums.length;\n\n\t\tfor (int i = 1; i <= len; i++) { | LegendaryCoder | NORMAL | 2021-07-05T11:58:38.789925+00:00 | 2021-07-05T11:58:38.789962+00:00 | 110 | false | \n\t// Linear Search + Sorting\n\t// O(n^2) O(1)\n\tpublic int specialArray1(int[] nums) {\n\n\t\tint len = nums.length;\n\n\t\tfor (int i = 1; i <= len; i++) {\n\t\t\tint count = 0;\n\t\t\tfor (int j = len - 1; j >= 0; j--) {\n\t\t\t\tif (nums[j] >= i)\n\t\t\t\t\tcount++;\n\t\t\t}\n\t\t\tif (count == i)\n\t\t\t\treturn i;\n\t\t}\n\n\t\treturn -1;\n\t}\n\n\t// Binary Search + Sorting\n\t// O(nlogn) O(1)\n\tpublic int specialArray2(int[] nums) {\n\n\t\tint len = nums.length;\n\t\tArrays.sort(nums);\n\n\t\tfor (int i = 1; i <= len; i++) {\n\t\t\tint idx = binarySearch(nums, i) - 1;\n\t\t\tif (idx != -2 && len - idx - 1 == i)\n\t\t\t\treturn i;\n\t\t}\n\n\t\treturn -1;\n\t}\n\n\t// Binary Search\n\t// O(nlogn) O(1)\n\tpublic int binarySearch(int[] nums, int target) {\n\n\t\tint lo = 0, hi = nums.length - 1, ans = -1;\n\n\t\twhile (lo <= hi) {\n\n\t\t\tint mid = (lo + hi) / 2;\n\t\t\tif (nums[mid] >= target) {\n\t\t\t\tans = mid;\n\t\t\t\thi = mid - 1;\n\t\t\t} else\n\t\t\t\tlo = mid + 1;\n\t\t}\n\n\t\treturn ans;\n\t}\n\n\t// Counting\n\t// O(n) O(n)\n\tpublic int specialArray3(int[] nums) {\n\n\t\tint len = nums.length;\n\t\tint[] count = new int[1001];\n\n\t\tfor (int i = 0; i < len; i++)\n\t\t\tcount[nums[i]]++;\n\n\t\tint right = nums.length;\n\t\tfor (int i = 0; i <= len; i++) {\n\n\t\t\tif (i == right)\n\t\t\t\treturn i;\n\t\t\t\n\t\t\tright -= count[i];\n\t\t}\n\n\t\treturn -1;\n\t} | 3 | 0 | [] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | 98% :: Python | Binary Search (Very similar to H- Index) | 98-python-binary-search-very-similar-to-9i8aq | \nimport bisect\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n for i in range(1, len(nums) + 1):\n | tuhinnn_py | NORMAL | 2021-05-20T15:41:26.093814+00:00 | 2021-05-20T15:41:26.093856+00:00 | 386 | false | ```\nimport bisect\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n for i in range(1, len(nums) + 1):\n startIndex = bisect.bisect_left(nums, i)\n if len(nums) - startIndex == i:\n return i\n return -1\n``` | 3 | 0 | ['Binary Tree', 'Python'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Very simple/intuitive python solution | very-simpleintuitive-python-solution-by-54g1u | \nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n \n for i in range(len(nums), -1, -1):\n if [j >= i for j in nu | loag | NORMAL | 2021-02-13T14:34:55.363524+00:00 | 2021-02-13T14:34:55.363548+00:00 | 140 | false | ```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n \n for i in range(len(nums), -1, -1):\n if [j >= i for j in nums].count(True) == i:\n return i\n return -1\n``` | 3 | 0 | [] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Python, sort. Time: O(N log N), Space: O(N) | python-sort-time-on-log-n-space-on-by-bl-f5ms | \nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n for i in range(len(nums)):\n x = len(nums) - i \ | blue_sky5 | NORMAL | 2020-11-08T00:15:20.751762+00:00 | 2020-11-08T00:16:39.543050+00:00 | 421 | false | ```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n for i in range(len(nums)):\n x = len(nums) - i \n if (i == 0 or nums[i-1] < x) and x <= nums[i]:\n return x\n \n return -1\n``` | 3 | 0 | ['Python', 'Python3'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | sort explained (with pictures)^^ | sort-explained-with-pictures-by-andrii_k-htb7 | Idea and pictures\n\nNote that that possible outcomes of the algorithm are 0...size(n) (and -1). \nThus we should check these numbers only.\nIf we sort the arra | andrii_khlevniuk | NORMAL | 2020-10-04T22:09:13.318203+00:00 | 2020-10-06T11:52:52.266528+00:00 | 382 | false | **Idea and pictures**\n\nNote that that possible outcomes of the algorithm are `0...size(n)` (and `-1`). \nThus we should check these numbers only.\nIf we sort the array in the ascending order we aim to find an index `i` from interval `[0, size(n)]` such that `n[i-1] >= i and n[i] < i`.\nThus we traverse the array from left to right and check for this condition. \n\n\nTake a look at the picture (your program should return `2`)\n\n\n\nNote you could also encounter following corner testcases.\nHere your program should return `0`.\n\n\n\n\n\nHere your program should return `6`.\n\n\n\nHere is the testcase where the algo sould return `-1`.\nNote that it\'s possible if `n[i-1]` **<** `i and n[i] < i`. \nThis is possible only if `n[i-1]==i-1` because if we traverse the array from left to right we\'ve already checked that `n[i-1]>=i-1` at the previous iteration.\nThis is important cause it enables early return.\n\n\n\n\n**Code**\n\n```\nint specialArray(vector<int>& n) \n{\n\tsort(begin(n), end(n), greater{});\n\n\tif(n.front() < 0) return 0;\n\tif(n.back() >= size(n)) return size(n);\n\n\tfor(auto i{1}; i<size(n); ++i)\n\t\t if(n[i] < i) return (n[i-1] == i-1) ? -1 : i;\n\n\treturn -2; //impossible\n}\n```\nor introducing `INT_MAX` and `INT_MIN` values to deal with corner cases\n\n\n\n\n```\nint specialArray(vector<int>& n) \n{\n\tsort(begin(n), end(n), greater{});\n\n\tfor(auto i{0}, prev{INT_MAX}; i<size(n); prev = n[i++])\n\t\tif(n[i] < i) return (prev == i-1) ? -1 : i;\n\n\treturn n.back() >= size(n) ? size(n) : -1;\n}\n```\nor\n```\nint specialArray(vector<int>& n) \n{\n\tsort(begin(n), end(n), greater{});\n\n\tn.push_back(INT_MIN);\n\n\tfor(auto i{0}, prev{INT_MAX}; i<size(n); prev = n[i++])\n\t\t if(n[i] < i) return (prev == i-1) ? -1 : i;\n\n\treturn -2; //impossible\n}\n```\n\n | 3 | 0 | ['C', 'C++'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Beats 100% | C++ | No-Sort Solution to Special Array With X Elements Greater Than or Equal X | beats-100-c-no-sort-solution-to-special-3qjny | IntuitionThe problem requires finding a value x such that there are exactly x elements in the array greater than or equal to x. The key observation is that sort | anorangefalcon | NORMAL | 2025-01-14T18:23:50.827404+00:00 | 2025-01-14T18:23:50.827404+00:00 | 97 | false | # Intuition
The problem requires finding a value `x` such that there are exactly `x` elements in the array greater than or equal to `x`. The key observation is that sorting the array is unnecessary since we only need to count occurrences and aggregate values efficiently. By maintaining a frequency array for elements less than the size of the input array and a count of elements greater or equal to the size, we can solve the problem in linear time.
# Approach
1. **Frequency Array**: Create a `limiter` array of size `nums.size()` to count the occurrences of numbers less than the size of the array.
2. **Count Large Numbers**: Use a variable `outies` to count numbers greater than or equal to `nums.size()`.
3. **Immediate Check**: If `outies` (the count of large numbers) equals the size of the array (`limiter.size()`), return `outies`. This is because the number of elements greater than or equal to the size of the array exactly matches the potential special value.
4. **Reverse Traversal**: Traverse the `limiter` array in reverse to accumulate counts (`outies`) and check if the condition `i == outies` holds. If it does, return `i` as the special value.
5. **Edge Case**: If no valid `x` is found after the loop, return `-1`.
# Complexity
- Time complexity: $$O(n)$$
We traverse the input array once to populate the frequency array and another pass through `limiter` in reverse.
- Space complexity: $$O(n)$$
The `limiter` array requires additional space proportional to the size of the input array.
# Code
```cpp []
class Solution {
public:
int specialArray(vector<int>& nums) {
int greaters = 0;
vector<int> limiter(nums.size(), 0);
for(int &n: nums){
if(n < nums.size()) limiter[n]++;
else greaters += 1;
}
if(limiter.size() == greaters) return greaters;
for(int i = limiter.size() - 1; i >= 0; i--){
greaters += limiter[i];
if(i == greaters) return i;
}
return -1;
}
};
``` | 2 | 0 | ['Array', 'C++'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Binary Search Approach for Finding | binary-search-approach-for-finding-by-ha-2tp8 | Intuition\nTo find the special value x such that there are exactly x numbers in the array that are greater than or equal to x, we can leverage the properties of | hamzawp404 | NORMAL | 2024-05-27T15:33:45.885834+00:00 | 2024-05-27T15:33:45.885862+00:00 | 10 | false | # Intuition\nTo find the special value x such that there are exactly x numbers in the array that are greater than or equal to x, we can leverage the properties of a sorted array to efficiently determine the count of such elements.\n\n# Approach\n1. Sort the Array: Sorting helps to efficiently count the elements greater than or equal to any value x.\n2. Iterate Over Possible Values of x: Loop through all potential values of x from 0 to the length of the array n.\n3. Count Elements Greater Than or Equal to x: For each x, use the lower_bound function to find the position where x could be inserted to keep the array sorted. The count of elements greater than or equal to x is then n minus this position.\n4. Check the Condition: If the count equals x, return x. If no such x is found, return -1.\n\n# Complexity\n- Time complexity: O(nlogn)\n1. Sorting the array takes O(nlogn)\n2. Finding the lower bound and checking the condition for each x takes O(logn), and we do this n times, making it O(nlogn) overall.\n\n\n- Space complexity: O(1)\nNo extra space is used apart from a few variables.\n\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n \n for (int x = 0; x <= n; ++x) {\n int count = n - (lower_bound(nums.begin(), nums.end(), x) - nums.begin());\n if (count == x) {\n return x;\n }\n }\n \n return -1;\n }\n};\n``` | 2 | 0 | ['Binary Search', 'C++'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Easy Approach in JS 90% | easy-approach-in-js-90-by-machip3r-0335 | Intuition\nI only think in the for loop to iterate from 0 to nums.length checking each numbers of nums. But viewing the best times in JS, I can do it better wit | MacHip3r | NORMAL | 2024-05-27T14:49:37.549631+00:00 | 2024-05-27T14:49:37.549652+00:00 | 149 | false | # Intuition\nI only think in the *for loop* to iterate from 0 to *nums.length* checking each numbers of *nums*. But viewing the best times in JS, I can do it better with binary search.\nIt is what it is.\n\n# Approach\nReading the intuition is easy to do the approach, so that is.\nIterate from 0 to *nums.length*, then iterate in nums to check if the variable (*x*) in the first loop meets the requirements sum to the variable *counter* and if *counter* equals to *x* return *counter*.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nconst specialArray = (nums) => {\n for (let x = 0; x < (nums.length + 1); x++) {\n let counter = 0;\n for (const n of nums)\n if (n >= x)\n counter++;\n\n if (counter === x)\n return counter;\n }\n\n return -1;\n};\n``` | 2 | 0 | ['Array', 'JavaScript'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Beats 20.04% of users with Python3 | beats-2004-of-users-with-python3-by-kawi-epag | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | KawinP | NORMAL | 2024-05-27T14:34:27.893654+00:00 | 2024-05-27T14:34:27.893673+00:00 | 14 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- **Time Complexity** : \\(O(n^2)\\)\n- **Space Complexity** : \\(O(1)\\)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n for x in range(1, n + 1):\n count = 0\n for num in nums:\n if num >= x:\n count += 1\n if count == x:\n return x\n return -1\n```\n | 2 | 0 | ['Python3'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Only (N) Without sorting 🚀 || concise 🎗️|| newbie friendly 🔥|| simple explanation 🧩|| 4 lang 🎉 | only-n-without-sorting-concise-newbie-fr-y779 | Screenshot \uD83C\uDF89\n\n\n\n---\n# Intuition \uD83E\uDD14\n This is a pretty good problem ... Let\'s discuss first-->\n\nGiven --> \n\n1. We are given an | Prakhar-002 | NORMAL | 2024-05-27T14:25:25.570170+00:00 | 2024-05-27T20:25:06.920520+00:00 | 189 | false | # Screenshot \uD83C\uDF89\n\n\n\n---\n# Intuition \uD83E\uDD14\n This is a pretty good problem ... Let\'s discuss first-->\n\n`Given -->` \n\n`1.` We are given `an array` with `some positive values` only\n\n`To return -->`\n\n`1.` A number `X` which `can be a part of our nums array or not`\n\n`2.` And there `must present` **exactly** `x numbers in nums` that `are >= X`.\n\n Ex.\n nums = [1, 2, 4, 5, 6]\n\n Ans will be (3) -> Although it is not present in array\n\n Ex. \n nums = [5, 6]\n\n Ans will be (2) -> Although it is alse not present in array\n\n Ex. \n nums = [0, 0, 3, 4, 4]\n\n Ans will be (3) -> it is present in array\n\n---\n\n# Approach \uD83E\uDD73\n<!-- Describe your approach to solving the problem. -->\n\n It\'s a observation -->\n\n that number X can\'t be greater then the length of nums\n\n X = [1, N] within this arra \n\n<h1 align="center"> \n\n--------`Step 1`-------- \n</h1>\n\n - We will `make array` which will `count the frequency`all the elem. \n \n - which will `store all the freq of nums\'s element`\n\n<h1 align="center"> \n\n--------`Step 2`-------- \n</h1>\n\n - Now the `catch is our Constraints` `0 <= nums[i] <= 1000`\n \n - we **can\'t make an array with this length**\n \n - now `we\'ll use our observation` That is `X = [1, N]`\n \n - so we\'ll make array with `length of N + 1` \n \n - yaa you guess right `last index will store all rest count of elem`\n\n<h1 align="center"> \n\n--------`Step 3`-------- \n</h1>\n\n Have a Example --> \n\n Nums = [1, 2, 4, 5, 6] \n\n x = [1, 5] --> 5 will store all the rest elem\'s freq \n\n count = no greater than X.\n\n X count freq count from freq\n \n 1 5 1 > 5 --> \n 2 4 1 | > 4 --> \n 3 3 0 | | > 3 --> X = 3 ==> our Ans\n 4 3 1 | | | > 3 --> \n 5 2 2 | | | | > 2 --> \n\n\n\n<h1 align="center"> \n\n--------`I guess all of you got the idea`-------- \n</h1>\n\n---\n\n# understand with code \uD83D\uDE0D\n We will have steps to do our job\n\n Step 1. make an arr count\n\n Step 2. Count freq of elem \n\n Step 3. CountFreq from end and if equal i return countFreq else -1\n\n---\n \n`Step 1.` **make tha arr (countNo) and `count the freq` of all elem in nums**\n\n**--> Store the element at last index If it is greater than length**\n\n`index = nums[i] < nums.length ? nums[i] : nums.length`\n\n```JAVA []\n\n int countNo[] = new int[nums.length + 1];\n\n for (int el : nums) {\n countNo[Math.min(el, nums.length)]++;\n }\n```\n```JAVASCRIPT []\n let countNo = new Array(nums.length + 1).fill(0);\n\n for (const el of nums) {\n countNo[Math.min(el, nums.length)]++;\n }\n};\n```\n```PYTHON []\n countNo = [0] * (len(nums) + 1)\n\n for el in nums:\n countNo[min(el, len(nums))] += 1\n\n```\n```C []\n int countNo[numsSize + 1];\n\n for (int i = 0; i <= numsSize; i++) {\n countNo[i] = 0;\n }\n```\n\n---\n\n`Step 2 - 3` **-->** `make TotalRight and return it or -1`\n\n**Make a totalRight variable that will store our number greater than X and if i == totalRight then totalRight else -1**\n\n```JAVA []\n\n int totalRight = 0;\n\n for (int i = nums.length; i >=0 ; i--) {\n totalRight += countNo[i];\n\n if (i == totalRight) {\n return totalRight;\n }\n }\n\n return -1;\n```\n```JAVASCRIPT []\n let rightTotal = 0;\n\n for (let i = nums.length; i >= 0; i--) {\n rightTotal += countNo[i];\n if (i == rightTotal) {\n return rightTotal;\n }\n }\n\n return -1;\n```\n``` PYTHON []\n total_right = 0\n\n for i in reversed(range(len(nums) + 1)):\n total_right += countNo[i]\n\n if i == total_right:\n return total_right\n \n return -1\n```\n```C []\n int totalRight = 0;\n\n for (int i = numsSize; i >= 0; i--) {\n totalRight += countNo[i];\n\n if (i == totalRight) {\n return totalRight;\n }\n }\n\n return -1;\n}\n```\n---\n\n# Complexity \uD83D\uDD25\n- Time complexity: $$O(n)$$ \uD83D\uDCAF\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ \uD83E\uDE77\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n---\n# Code \uD83C\uDF41\n\n```JAVA []\nclass Solution {\n public int specialArray(int[] nums) {\n int countNo[] = new int[nums.length + 1];\n\n for (int el : nums) {\n countNo[Math.min(el, nums.length)]++; // This will count all numbers in array\n }\n\n int totalRight = 0;\n\n for (int i = nums.length; i >=0 ; i--) {\n totalRight += countNo[i];\n\n if (i == totalRight) {\n return totalRight;\n }\n }\n\n return -1;\n\n }\n}\n```\n```JAVASCRIPT []\nvar specialArray = function (nums) {\n let countNo = new Array(nums.length + 1).fill(0);\n\n for (const el of nums) {\n countNo[Math.min(el, nums.length)]++;\n }\n\n let rightTotal = 0;\n\n for (let i = nums.length; i >= 0; i--) {\n rightTotal += countNo[i];\n if (i == rightTotal) {\n return rightTotal;\n }\n }\n\n return -1;\n};\n```\n```PYTHON []\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n countNo = [0] * (len(nums) + 1)\n\n for el in nums:\n countNo[min(el, len(nums))] += 1\n\n total_right = 0\n\n for i in reversed(range(len(nums) + 1)):\n total_right += countNo[i]\n\n if i == total_right:\n return total_right\n \n return -1\n```\n```C []\nint specialArray(int* nums, int numsSize) {\n int countNo[numsSize + 1];\n\n for (int i = 0; i <= numsSize; i++) {\n countNo[i] = 0;\n }\n\n for (int i = 0; i < numsSize; i++) {\n countNo[nums[i] < numsSize ? nums[i] : numsSize]++;\n }\n\n int totalRight = 0;\n\n for (int i = numsSize; i >= 0; i--) {\n totalRight += countNo[i];\n\n if (i == totalRight) {\n return totalRight;\n }\n }\n\n return -1;\n}\n```\n<h1 align="center"> \n\n--------------------[\u2603\uFE0FPrakhar-002\u2603\uFE0F](https://github.com/Prakhar-002/LEETCODE)--------------------\n</h1>\n\n I have wrote some other solutions too \n\n and also solve daily problems --> Check out GIT\n\n\n\n\n-----\n | 2 | 0 | ['Array', 'Binary Search', 'C', 'Sorting', 'Java', 'Python3', 'JavaScript'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | simple solution | simple-solution-by-abhishekd1163-g5hc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | abhishekd1163 | NORMAL | 2024-05-27T10:31:00.445045+00:00 | 2024-05-27T10:31:00.445061+00:00 | 21 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int n=nums.size();\n for(int i=0;i<=n;i++){\n int count=0;\n for(int j: nums){\n if(j>=i) count++;\n }\n if(count==i)return i;\n }\n return -1;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
minimum-number-of-operations-to-make-array-continuous | [Python] Binary Search - Clean & Concise | python-binary-search-clean-concise-by-hi-9rcn | Idea\n- Store the original length, n = len(nums).\n- Firstly, make elements in nums unique and sort nums array.\n- Try elements in nums as the start of the cont | hiepit | NORMAL | 2021-09-18T16:00:34.530195+00:00 | 2021-10-01T08:16:31.115426+00:00 | 9,456 | false | **Idea**\n- Store the original length, `n = len(nums)`.\n- Firstly, **make** elements in `nums` **unique** and **sort** `nums` array.\n- Try elements in `nums` as the start of the continuous array, let say `start`.\n\t- Elements in the continuous array must in range `[start, end]`, where `end = start + n - 1`.\n\t- Binary search to find the index of the right insert position of `end` in `nums`, let say `idx`.\n\t- Then we can calculate the number of unique numbers in range `[start, end]` by `uniqueLen = n - idx`.\n\t- The cost to make coninuous array is `cost = n - uniqueLen`.\n\t- We update the best answer so far, `ans = min(ans, cost)`\n- Then return the best `ans` we have.\n\n```python\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums)) # Make `nums` as unique numbers and sort `nums`.\n\n ans = n\n for i, start in enumerate(nums):\n end = start + n - 1 # We expect elements of continuous array must in range [start..end]\n idx = bisect_right(nums, end) # Find right insert position\n uniqueLen = idx - i\n ans = min(ans, n - uniqueLen)\n return ans\n```\n\n**Complexity**\n- Time: `O(NlogN)`\n- Space: `O(N)`\n\nIf you think this **post is useful**, I\'m happy if you **give a vote**. Any **questions or discussions are welcome!** Thank a lot. | 144 | 6 | [] | 12 |
minimum-number-of-operations-to-make-array-continuous | C++ Sliding Window | c-sliding-window-by-lzl124631x-a14t | See my latest update in repo LeetCode\n## Solution 1. Sliding Window\n\nCheck out "C++ Maximum Sliding Window Cheatsheet Template!" which can help you solve all | lzl124631x | NORMAL | 2021-09-18T16:00:48.170437+00:00 | 2021-10-02T22:21:03.896365+00:00 | 13,910 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n## Solution 1. Sliding Window\n\nCheck out "[C++ Maximum Sliding Window Cheatsheet Template!](https://leetcode.com/problems/frequency-of-the-most-frequent-element/discuss/1175088/C%2B%2B-Maximum-Sliding-Window-Cheatsheet-Template!)" which can help you solve all sliding window problems.\n\n**Intuition**: Sort and only keep unique elements. The problem is the same as "get the length of the longest subarray whose difference between min and max elements is `N - 1`".\n\n**Algorithm**:\n\nThe brute force way is to pick each `A[i]` as the start of the subarray and count the number of elements that are `<= A[i] + N - 1`, which takes `O(N^2)` time.\n\nSince the array is already sorted, we can use sliding window so that we only traverse the entire array once.\n\n```cpp\n// OJ: https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/\n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(1)\nclass Solution {\npublic:\n int minOperations(vector<int>& A) {\n int N = A.size(), ans = N, j = 0;\n sort(begin(A), end(A));\n A.erase(unique(begin(A), end(A)), end(A)); // only keep unique elements\n int M = A.size();\n for (int i = 0; i < M; ++i) {\n while (j < M && A[j] < A[i] + N) ++j; // let `j` point to the first element that is out of range -- `>= A[i] + N`.\n ans = min(ans, N - j + i); // The length of this subarray is `j - i`. We need to replace `N - j + i` elements to make it continuous.\n }\n return ans;\n }\n};\n```\n\nUse Shrinkable Sliding Window Template: \n\n```cpp\n// OJ: https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/\n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(1)\nclass Solution {\npublic:\n int minOperations(vector<int>& A) {\n int N = A.size(), i = 0, j = 0, ans = 0;\n sort(begin(A), end(A));\n A.erase(unique(begin(A), end(A)), end(A)); // only keep unique elements\n for (int M = A.size(); j < M; ++j) {\n while (A[i] + N <= A[j]) ++i; // let `i` point to the first element that is in range -- `A[i] + N > A[j]`\n ans = max(ans, j - i + 1);\n }\n return N - ans;\n }\n};\n```\n\nUse Non-shrinkable Sliding Window Template:\n\n```cpp\n// OJ: https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/\n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(1)\nclass Solution {\npublic:\n int minOperations(vector<int>& A) {\n int N = A.size(), i = 0, j = 0;\n sort(begin(A), end(A));\n A.erase(unique(begin(A), end(A)), end(A)); // only keep unique elements\n for (int M = A.size(); j < M; ++j) {\n if (A[i] + N <= A[j]) ++i;\n }\n return N - j + i;\n }\n};\n``` | 131 | 1 | [] | 7 |
minimum-number-of-operations-to-make-array-continuous | 【Video】Give me 15 minutes - How we think about a solution | video-give-me-15-minutes-how-we-think-ab-1edl | Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains | niits | NORMAL | 2023-10-10T08:54:30.152063+00:00 | 2023-10-11T10:25:55.641141+00:00 | 3,994 | false | Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nSorting input array.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/9DLAvMurzbU\n\n\u25A0 Timeline of the video\n`0:00` Read the question of Minimum Number of Operations to Make Array Continuous\n`0:42` How we think about a solution\n`4:33` Demonstrate solution with an example\n`8:10` Why the window has all valid numbers?\n`8:36` We don\'t have to reset the right pointer to 0 or something\n`10:36` Why we need to start window from each number?\n`12:24` What if we have duplicate numbers in input array?\n`14:50` Coding\n`17:11` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 2,643\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n\n# Approach\n\n### How we think about a solution\nWe have two constraints.\n\n\n---\n- All elements in nums are unique.\n- The difference between the maximum element and the minimum element in nums equals nums.length - 1.\n---\n\nFor example, `nums = [1,2,3,4,5]` need `0` opearation because \n\n```\nminimum number is 1\nmaximum number is 5 \u2192 1 + len(nums) - 1(= 4) \n```\nHow about `nums = [4,1,3,2,5]`? we need `0` operation because The array `[4,1,3,2,5]` is simply a shuffled version of `[1,2,3,4,5]`. But shuffuled version makes us feel more diffucult and seems hard to solve the question.\n\nThat\'s why it\'s good idea to sort input array first then try to solve the question. Because we know that we create an array and value range should be `len(nums) - 1`. Seems sorting make the question easy.\n\n---\n\n\u2B50\uFE0F Points\n\nSort input array at first.\n\n---\n\n\nLet\'s think about this input\n```\nInput: [1,2,3,5]\n```\nIn this case, it\'s easy.\n```\n[1,2,3] is good, becuase they are in range 1 to 4.\n[5] should be changed to 4\n\nCalculation is 4 - 3 = 1\n4: length of nums\n3: length of [1,2,3]\n\nOutput: 1 (operation)\n```\nHow about this.\n```\nInput: [1,2,3,5,6]\n\nCalculation is 5 - 3 = 2\n5: length of nums\n3: length of [1,2,3]\n\nOutput: 2 (operations)\n\n```\n##### This is a wrong answer.\n\nThat\'s because if we change `1` to `4` or `6` to `4`, we can create `[2,3,4,5,6]` or `[1,2,3,4,5]`, so just one operation instead of two operations.\n\nFrom those examples, problem is we don\'t know which numbers we should keep and which number we should change.\n\n---\n\n\u2B50\uFE0F Points\n\nSo, we\'re determining the length of a subarray where all numbers are valid. The starting point of subarray should be each respective number.\n\nSince we check length of valid subarray, seems like we can use `sliding window` technique.\n\n---\n\n### How it works\n\nLet\'s see how it works. Initialize a left pointer and a right pointer with `0`.\n```\nInput: nums = [1,2,3,5,6]\n\nleft = 0\nright = 0\noperations = 5 (= len(nums))\n```\nEvery time we check like this.\n```\nnums[right] < nums[left] + length\n```\nBecuase `left pointer` is current starting point of window and valid numbers for current staring point should be `nums[left] + length - 1`.\n\nIf the condition is `true`, increament `right pointer` by `1`.\n\n```\nInput: nums = [1,2,3,5,6]\n\nvalid number is from 1 to 5.\nleft = 0\nright = 4 (until index 3, they are valid)\noperations = 5 (= len(nums)), we don\'t calcuate yet.\n```\nNow `right pointer` is index `4` and we don\'t meet \n```\nnums[right] < nums[left] + length\n= 6 < 1 + 5\n```\nThen, it\'s time to compare mininum operations. Condition should be\n```\n min_operations = min(min_operations, length - (right - left))\n```\n`right - left` is valid part, so if we subtract it from whole length of input array, we can get invalid part which is places where we should change. \n\n\n---\n\n\u2B50\uFE0F Points\n\nThat\'s because we sorted input array at first, so when we find invalid number which means later numbers are also invalid. we are sure that they are out of valid range.\n\n---\n\n\n```\nmin(min_operations, length - (right - left))\n= min(5, 5 - 4)\n= 1 \n```\nWe repeated this process from each index.\n\nBut one more important thing is \n\n---\n\n\u2B50\uFE0F Points\n\nWe can continue to use current right pointer position when we change staring position. we don\'t have to reset right pointer to 0 or something. Because previous starting point number is definitely smaller than current number.\n\n[1,2,3,5,6]\n\nLet\'s say current starting point is at index 1(2). In this case, index 0(1) is smaller than index 1(2) because we sorted the input array.\n\nWhen we start from index 0, we reach index 4(6) and index 4 is invalid. That means we are sure that at least until index 3, we know that all numbers are valid when we start from index 1 becuase\n\nfrom value 1, valid max number is 5 (1 + len(nums) - 1)\nfrom value 2, valid max number is 6 (2 + len(nums) - 1)\n\nIn this case, 6 includes range 2 to 5 from 1 to 5.\n\nThat\'s why we can use current right position when starting point is changed.\n\n---\n\n### Why do we need to start from each number?\n\nAs I told you, problem is we don\'t know which numbers we should keep and which number we should change. But there is another reason.\n\nLet\'s think about this case.\n```\nInput: [1,10,11,12]\n```\nWhen start from index `0`\n```\nvalid: [1]\ninvalid: [10,11,12]\n\n4 - 1 = 3\n\n4: total length of input\n1: valid length\n\nwe need 3 operations.\n```\nWhen start from index `1`\n```\nvalid: [10,11,12]\ninvalid: [1]\n\n4 - 3 = 1\n\n4: total length of input\n3: valid length\n\nwe need 1 operation.\n```\n\n---\n\n\u2B50\uFE0F Points\n\nStarting index 0 is not always minimum operation.\n\n---\n\n### What if we have duplicate numbers in input array?\n\nOne more important point is when we have duplicate numbers in the input array.\n```\nInput: [1,2,3,5,5]\n```\nLet\'s start from index 0, in this case, valid max value is \n```\n1 + (5 - 1) = 5\n```\nWe go through entire array and reach out of bounds from index 0. So output is `0`?\n\nIt\'s not. Do you rememeber we have two constraints and one of them says "All elements in nums are unique", so it\'s a wrong answer.\n\nHow can we avoid this? My idea is to remove duplicate by `Set` before interation.\n\n```\n[1,2,3,5,5]\n\u2193\n[1,2,3,5]\n```\nAfter removing duplicate number, valid range from index 0 should be from `1` to `4`\n\n```\nvalid: [1,2,3]\ninvalid: [5]\n\noperation = 4 - 3 = 1\n```\n\nIf we change one of 5s to 4, we can create `[1,2,3,4,5]` from `[1,2,3,5,5]`.\n\n---\n\n\u2B50\uFE0F Points\n\nRemove duplicate numbers from input array.\n\n---\n\nThat is long thought process. I spent 2 hours to write this.\nI felt like crying halfway through LOL.\n\nOkay, now I hope you have knowledge of important points. Let\'s see a real algorithm!\n\n### Algorithm Overview:\n\n1. Calculate the length of the input array.\n2. Initialize `min_operations` with the length of the array.\n3. Create a sorted set of unique elements from the input array.\n4. Initialize a variable `right` to 0.\n5. Iterate through the sorted unique elements:\n - For each element, find the rightmost index within the range `[element, element + length]`.\n - Calculate the minimum operations needed for the current element.\n6. Return the minimum operations.\n\n### Detailed Explanation:\n\n1. Calculate the length of the input array:\n - `length = len(nums)`\n\n2. Initialize `min_operations` with the length of the array:\n - `min_operations = length`\n\n3. Create a sorted set of unique elements from the input array:\n - `unique_nums = sorted(set(nums))`\n - This ensures that we have a sorted list of unique elements to work with.\n\n4. Initialize a variable `right` to 0:\n - `right = 0`\n - This will be used to keep track of the right pointer in our traversal.\n\n5. Iterate through the sorted unique elements:\n - `for left in range(len(unique_nums)):`\n\n - For each element, find the rightmost index within the range `[element, element + length]`:\n - While `right` is within bounds and the element at `right` is less than `element + length`, increment `right`.\n\n - Calculate the minimum operations needed for the current element:\n - Update `min_operations` as the minimum of its current value and `length - (right - left)`.\n\n6. Return the minimum operations:\n - `return min_operations`\n\n\n---\n\n\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n\nFor just in case, somebody might think this is $$O(n^2)$$ because of nested loop.\n\nActually the left pointer and the right pointer touch each number once because the left pointer is obvious and we don\'t reset the right pointer with 0 or something. we continue to use the right pointer from previous loop.\n\nSo, this nested loop works like $$O(2n)$$ instead of $$O(n^2)$$. That\'s why time complexity of this nested loop is $$O(n)$$.\n\n- Space complexity: $$O(n)$$\n\n\n```python []\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n length = len(nums)\n min_operations = length\n unique_nums = sorted(set(nums))\n right = 0\n \n for left in range(len(unique_nums)):\n while right < len(unique_nums) and unique_nums[right] < unique_nums[left] + length:\n right += 1\n \n min_operations = min(min_operations, length - (right - left))\n\n return min_operations\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minOperations = function(nums) {\n const length = nums.length;\n let minOperations = length;\n const uniqueNums = new Set(nums);\n const sortedUniqueNums = Array.from(uniqueNums).sort((a, b) => a - b);\n let right = 0;\n\n for (let left = 0; left < sortedUniqueNums.length; left++) {\n while (right < sortedUniqueNums.length && sortedUniqueNums[right] < sortedUniqueNums[left] + length) {\n right++;\n }\n\n minOperations = Math.min(minOperations, length - (right - left));\n }\n\n return minOperations; \n};\n```\n```java []\nclass Solution {\n public int minOperations(int[] nums) {\n int length = nums.length;\n int minOperations = length;\n Set<Integer> uniqueNums = new HashSet<>();\n for (int num : nums) {\n uniqueNums.add(num);\n }\n Integer[] sortedUniqueNums = uniqueNums.toArray(new Integer[uniqueNums.size()]);\n Arrays.sort(sortedUniqueNums);\n int right = 0;\n\n for (int left = 0; left < sortedUniqueNums.length; left++) {\n while (right < sortedUniqueNums.length && sortedUniqueNums[right] < sortedUniqueNums[left] + length) {\n right++;\n }\n\n minOperations = Math.min(minOperations, length - (right - left));\n }\n\n return minOperations; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int length = nums.size();\n int minOperations = length;\n sort(nums.begin(), nums.end());\n nums.erase(unique(nums.begin(), nums.end()), nums.end());\n int right = 0;\n\n for (int left = 0; left < nums.size(); left++) {\n while (right < nums.size() && nums[right] < nums[left] + length) {\n right++;\n }\n\n minOperations = min(minOperations, length - (right - left));\n }\n\n return minOperations; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u2B50\uFE0F Next daily coding challenge post and video\n\nPost\n\nhttps://leetcode.com/problems/number-of-flowers-in-full-bloom/solutions/4156243/video-give-me-15-minutes-how-we-can-think-about-a-solution-python-javascript-java-c/\n\n\nhttps://youtu.be/kiIYG6drNZo\n\nMy previous post for daily coding challenge\n\nPost\nhttps://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/solutions/4147878/video-give-me-10-minutes-how-we-think-about-a-solution-binary-search/\n\n\u2B50\uFE0F Yesterday\'s daily challenge video\n\nhttps://youtu.be/441pamgku74\n | 99 | 0 | ['C++', 'Java', 'Python3', 'JavaScript'] | 4 |
minimum-number-of-operations-to-make-array-continuous | Simple Solution || Beginner Friendly || Easy to Understand ✅ | simple-solution-beginner-friendly-easy-t-pkim | Approach\n Describe your approach to solving the problem. \n- Sort the input array nums in ascending order.\n- Traverse the sorted array to remove duplicates an | Anirban_Pramanik10 | NORMAL | 2023-10-10T01:46:08.213985+00:00 | 2023-10-10T03:52:11.606213+00:00 | 14,721 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n- Sort the input array `nums` in ascending order.\n- Traverse the sorted array to remove duplicates and count unique elements in `uniqueLen`.\n- Initialize `ans` to the length of the input array, representing the maximum operations initially.\n- Iterate over unique elements using an outer loop.\n- Use an inner while loop with two pointers to find subarrays where the difference between the maximum and minimum element is within the array\'s length.\n- Calculate the number of operations needed to make all elements distinct within each subarray.\n- Update `ans` with the minimum operations found among all subarrays.\n- Return the minimum operations as the final result.\n# Complexity\n- Time complexity: `O(N*lgN + N + N*lgN)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minOperations(int[] nums) {\n Arrays.sort(nums);\n int uniqueLen = 1;\n for (int i = 1; i < nums.length; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[uniqueLen++] = nums[i];\n }\n }\n \n int ans = nums.length;\n for (int i = 0, j = 0; i < uniqueLen; ++i) {\n while (j < uniqueLen && nums[j] - nums[i] <= nums.length - 1) {\n ++j;\n }\n ans = Math.min(ans, nums.length - (j - i));\n }\n \n return ans;\n }\n}\n```\n```python3 []\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums))\n\t\t\n answer = float("+inf")\n for i, start in enumerate(nums):\n \n search = start + n - 1 # number to search\n start, end = 0, len(nums)-1\n \n while start <= end:\n mid = start + (end - start) // 2\n if nums[mid] <= search:\n idx = mid\n start = mid + 1\n else:\n end = mid - 1\n \n changes = idx - i + 1\n answer = min(answer, n - changes)\n return answer\n \n```\n```python []\nclass Solution(object):\n def minOperations(self, nums):\n # Sort the input list in ascending order.\n nums.sort()\n \n # Initialize variables to keep track of unique elements and minimum operations.\n unique_len = 1\n ans = len(nums)\n \n # Traverse the sorted list to remove duplicates and count unique elements.\n for i in range(1, len(nums)):\n if nums[i] != nums[i - 1]:\n nums[unique_len] = nums[i]\n unique_len += 1\n \n # Initialize pointers for calculating operations within subarrays.\n i, j = 0, 0\n \n # Iterate over unique elements to find minimum operations.\n for i in range(unique_len):\n while j < unique_len and nums[j] - nums[i] <= len(nums) - 1:\n j += 1\n ans = min(ans, len(nums) - (j - i))\n \n return ans\n\n```\n```C++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n // Sort the vector in ascending order\n sort(nums.begin(), nums.end());\n\n // Initialize variables\n int n = nums.size(); // Number of elements in the vector\n int left = 0; // Left pointer for the sliding window\n int maxCount = 1; // Initialize the maximum count of distinct elements\n int currentCount = 1; // Initialize the count of distinct elements in the current window\n\n // Iterate through the vector to find the minimum operations\n for (int right = 1; right < n; ++right) {\n // Check if the current element is equal to the previous one\n if (nums[right] == nums[right - 1]) {\n continue; // Skip duplicates\n }\n\n // Check if the current window size is less than or equal to the difference between the maximum and minimum values\n while (nums[right] - nums[left] > n - 1) {\n // Move the left pointer to shrink the window\n if(left<n && nums[left+1]==nums[left]){\ncurrentCount++;\n}\n left++;\n currentCount--;\n }\n\n // Update the count of distinct elements in the current window\n currentCount++;\n\n // Update the maximum count\n maxCount = max(maxCount, currentCount);\n }\n\n // Calculate the minimum operations\n int minOps = n - maxCount;\n\n return minOps;\n }\n};\n```\n```C []\n// Function prototype for the comparison function\nint compare(const void* a, const void* b);\n\nint minOperations(int* nums, int numsSize) {\n // Define the maximum size of the sliding window\n int k = numsSize - 1;\n\n // Sort the array in ascending order\n qsort(nums, numsSize, sizeof(int), compare);\n\n // Remove adjacent duplicates\n int newLen = 1;\n for (int i = 1; i < numsSize; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[newLen++] = nums[i];\n }\n }\n\n int l = 0, r = 0, fin = 1;\n\n while (r < newLen) {\n if (l == r)\n r++;\n else if (nums[r] - nums[l] > k)\n l++;\n else {\n fin = (fin > r - l + 1) ? fin : r - l + 1;\n r++;\n }\n }\n\n return k - fin + 1;\n}\n\nint compare(const void* a, const void* b) {\n return (*(int*)a - *(int*)b);\n}\n```\n# If you like the solution please Upvote !!\n\n\n | 91 | 5 | ['Binary Search', 'C', 'Sliding Window', 'Python', 'C++', 'Java', 'Python3'] | 7 |
minimum-number-of-operations-to-make-array-continuous | [Python] Explanation with Pictures, Binary Search | python-explanation-with-pictures-binary-j2dme | For any valid result, we can focus on the minimum number a in that list, since there are n unique numbers, all the numbers are: a, a + 1, a + 2, ... , a + n - 1 | Bakerston | NORMAL | 2021-09-18T16:02:21.872858+00:00 | 2021-09-25T17:49:34.479126+00:00 | 2,632 | false | For any valid result, we can focus on the minimum number ```a``` in that list, since there are ```n``` unique numbers, all the numbers are: ```a, a + 1, a + 2, ... , a + n - 1```. Traverse the list ```A```, for the current number a, if the result list has ```a``` as the smallest number, we need to find out how many unique numbers in the range ```[a, a + n - 1]``` (inclusively), are in ```A```.\n\nTake the sorted list below as an example, if we pick ```1``` as the smallest number, we expect to have the list ```[1, 2, 3, ... 8]``` as the sorted result.\n\n\nUse binary search to find the right boundary of the range. Apparently all the numbers to the right of the boundary will be discarded.\n\n\nThe next task is find out how many **unique** numbers within this range?\nWe use prefix number of unique numbers, start from ```index = 0``` and count how many unique number in the list **so far**. Like how we bulid pre sum list of an array.\n\nTherefore, we find ```3``` unique numbers in this range, meaning we need to change the rest ```8 - 3 = 5``` numbers.\n\n\nIn the second example, suppose we let ```3``` to be the smallest number is the final result, thus we expect to have ```[3, 4, 5,... 10]``` as the sorted final result.\n\nUse binary search to find the right boundary. Notice in this case we shall discard all the numbers smaller than ```3``` as well since ```3``` is the smallest number.\n\n\n\n```\ndef minOperations(self, A: List[int]) -> int:\n A.sort()\n n = len(A)\n ans = n - 1\n uniq, cur = [1], 1\n \n for i in range(1, n):\n if A[i] != A[i - 1]: \n cur += 1\n uniq.append(cur)\n \n for i in range(n):\n a = A[i]\n idx = bisect.bisect_right(A, a + n - 1)\n cur_uniq = max(0, uniq[idx - 1] - uniq[i]) + 1\n ans = min(ans, n - cur_uniq)\n\n return ans\n```\n\n\n\n | 63 | 0 | [] | 4 |
minimum-number-of-operations-to-make-array-continuous | [Java] Sort + sliding window | java-sort-sliding-window-by-tobias2code-cxr0 | The intuition is to find the maximum number of distinct elements fitting in a window of length maxNumsInWindow, by iterating over the sorted array. \n=> The rem | tobias2code | NORMAL | 2021-09-18T18:04:02.368715+00:00 | 2021-10-23T10:34:44.550130+00:00 | 4,385 | false | The intuition is to find the maximum number of distinct elements fitting in a window of length `maxNumsInWindow`, by iterating over the sorted array. \n=> The remaining `N - maxNumsInWindow` elements need to be replaced.\n\n\n\nFor example, if we have `in = [1, 2, 8, 9, 11]`, the window has length 5. As we iterate, the window contains:\n- [1]\n- [1,2]\n- [8] (we removed 1 and 2, because more distant than 5)\n- [8,9]\n- [8,9,11] (=> `maxNumsInWindow = 3` => `N - maxNumsInWindow = 2` elements to replace)\n\nThe code:\n```\n public int minOperations(int[] nums) {\n Arrays.sort(nums); // Sort the array\n \n int n = nums.length;\n int maxNumsInWindow = 0;\n \n Deque<Integer> numsInWindow = new ArrayDeque<>();\n for (int num : nums) {\n // Advance the window\n while (numsInWindow.size() > 0 && num - numsInWindow.peekFirst() >= n) {\n numsInWindow.poll();\n }\n \n // Add the new number to the window (if it\'s not a duplicate)\n if(numsInWindow.size() == 0 || ! numsInWindow.peekLast().equals(num)) {\n numsInWindow.offer(num); \n }\n \n maxNumsInWindow = Math.max(maxNumsInWindow, numsInWindow.size());\n }\n \n return n - maxNumsInWindow;\n }\n```\n\nComplexity\n- Time: `O(N logN)`\n- Space: `O(N)`\n\nNote that it\'s also possible to use pointers instead of the queue.\n\nQuestions and discussions are welcome! | 55 | 2 | ['Sliding Window', 'Java'] | 7 |
minimum-number-of-operations-to-make-array-continuous | C++ Binary Search , Understandable to Beginners as well | c-binary-search-understandable-to-beginn-36p8 | Explanation: If You are not able to understand handwriting ,look in the code, Your doubts will get cleared.\n\n\n\n\n\nclass Solution {\npublic:\n int minOpe | yogeshagarwal123 | NORMAL | 2021-09-18T16:55:37.110784+00:00 | 2022-01-08T20:02:22.202036+00:00 | 2,491 | false | **Explanation**: If You are not able to understand handwriting ,look in the code, Your doubts will get cleared.\n\n\n\n\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size();\n \n //set for finding unique element \n set<int>s;\n for(int i=0;i<nums.size();i++)\n {\n s.insert(nums[i]);\n }\n vector<int>unique;\n for(int item:s){\n unique.push_back(item);\n }\n \n //sort the array(let unique.size= m m*log(m))\n sort(unique.begin(),unique.end());\n \n int ans = INT_MAX;\n for(int i=0;i<unique.size();i++)\n {\n int start = unique[i];\n int last = start+n-1;\n \n //search for element just grater than last\n vector<int>::iterator upper=upper_bound(unique.begin(),unique.end(),last);\n int len = upper- unique.begin();\n ans = min(ans,n-(len-i));\n \n }\n return ans;\n }\n};\n```\n\nIf You have any Query feel free to ask.\nIf you have understood then please upvote. | 35 | 3 | ['Binary Tree'] | 6 |
minimum-number-of-operations-to-make-array-continuous | [Python] 2 solutions: BIT and binary search, explained. | python-2-solutions-bit-and-binary-search-k0ym | Reformulate the problems: found the range [x, x + n - 1], such that we have maximum number of values from nums.\nThis problem can be solved with use of binary i | dbabichev | NORMAL | 2021-09-18T16:02:12.182300+00:00 | 2021-09-19T01:55:46.050066+00:00 | 1,346 | false | Reformulate the problems: found the range `[x, x + n - 1]`, such that we have maximum number of values from `nums`.\nThis problem can be solved with use of binary indexed tree. The idea is to put all numbers in sparse binary indexed tree and then check for each range `[num, num + n - 1]`. Notice that we only need to check ranges which starts with some number from `nums`.\n\n#### Complexity\nIt is `O(n*log M)`, where `n = len(nums)` and `M = 10**9 + 10**5` is the maximum value of number + n`.\n\n#### Code\n```python\nclass BIT:\n def __init__(self, n):\n self.sums = defaultdict(int)\n self.n = n\n \n def update(self, i, delta):\n while i < self.n + 1:\n self.sums[i] += delta\n i += i & (-i)\n \n def query(self, i):\n res = 0\n while i > 0:\n res += self.sums[i]\n i -= i & (-i)\n return res\n\n def sum(self, i, j):\n return self.query(j) - self.query(i-1)\n\nclass Solution:\n def minOperations(self, nums):\n n, ans = len(nums), 0\n bit = BIT(10**9 + 10**5 + 10)\n for num in set(nums):\n bit.update(num, 1)\n\n for num in nums:\n ans = max(ans, bit.sum(num, num + n - 1))\n return n - ans\n```\n\n#### Solution 2\nIn fact we do not need bit, we can use binary search idea as well. Notice that if we sort all numbers, then all we need to find is number of values in range `[x, x + n - 1]`, which can be done using binary search.\n\n#### Complexity\nIt is `O(n log n)` for time and `O(n)` for space.\n\n#### Code\n```python\nclass Solution:\n def minOperations(self, nums):\n sArray = sorted(set(nums)) \n cand = [(i, n + len(nums) - 1) for i, n in enumerate(sArray)]\n \n ans = float("inf")\n for i, high in cand:\n idx = bisect.bisect_left(sArray, high)\n if idx >= len(sArray) or sArray[idx] != high: idx -= 1\n ans = min(ans, len(nums) - idx + i - 1)\n return ans\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 31 | 3 | ['Binary Search'] | 3 |
minimum-number-of-operations-to-make-array-continuous | Sliding Window | sliding-window-by-votrubac-4mt0 | First, we sort and de-dup the numbers. Be sure to remember the original array\'s size as n.\n\nThen, we use two pointers i and j to track numbers within the [nu | votrubac | NORMAL | 2021-09-18T23:18:58.254988+00:00 | 2021-09-18T23:31:39.589198+00:00 | 2,262 | false | First, we sort and de-dup the numbers. Be sure to remember the original array\'s size as `n`.\n\nThen, we use two pointers `i` and `j` to track numbers within the `[nums[i], nums[i] + n]` window. Numbers are already in their places, so we need to change the remaning `n - (j - i)` numbers. \n\n**C++**\n```cpp\nint minOperations(vector<int>& nums) {\n int res = INT_MAX, n = nums.size();\n sort(begin(nums), end(nums));\n nums.erase(unique(begin(nums), end(nums)), end(nums));\n for (int i = 0, j = 0; i < nums.size(); ++i)\n while (j < nums.size() && nums[j] < nums[i] + n)\n res = min(res, n - (++j - i));\n return res;\n}\n``` | 23 | 3 | [] | 3 |
minimum-number-of-operations-to-make-array-continuous | [Python] How Leetcode (and interviewers) will try to trick you with test cases | python-how-leetcode-and-interviewers-wil-m7fc | Me: "I was so sloppy during today\'s contest. I\'m going to write a discussion post to make myself feel better."\n\nMy girlfriend: "Whatever"\n\n--- \n\nIn this | grawlixes | NORMAL | 2021-09-18T16:00:44.963960+00:00 | 2021-09-18T16:00:44.964001+00:00 | 1,541 | false | Me: "I was so sloppy during today\'s contest. I\'m going to write a discussion post to make myself feel better."\n\nMy girlfriend: "Whatever"\n\n--- \n\nIn this problem, we have to form a consecutive set of numbers `[i, j]` with as many elements from the input array `nums` as possible. Let\'s call the set `[i, j]` with the most numbers from `nums` our "best set."\n\nHere\'s the idea: it isn\'t hard to imagine that the "best set" will include at least one number from `nums`. We don\'t know exactly how many yet, but it will most certainly include at least one. So, what if we could check the "best set" starting at every index of the sorted `nums` array? If we can do it fast enough, we can consider every possible "best set" and just return the one that includes the most numbers in `nums`.\n\nThe problem is that if we\'re checking each number in `nums`, we\'re already at `O(N)` time complexity. That means there\'s not much more room for work; if we try to look at subarrays, we\'ll be at `O(N**2)` which is definitely too slow given the constraints. However, think about it this way: if we sort `nums` and we move to start our "best set" from the value of index `k` to `k + 1`, we know that our new `j` value from the new interval `[nums[k+1], j]` will have to be greater than the last value of `j\'` from the previous interval `[nums[k], j\']`. So, we can use a **two-pointer solution** and keep track of the range we have to sum to. Once we\'re in that range, we can figure out the elements to change in `O(1)` time; we just have to change every number that is less than `k` (equal to the index of `k`, because the list is sorted) and the numbers greater than `j\'`. Success!!\n\n... wait a minute, I got it wrong?\n\n```\nInput: [4, 5, 8, 8, 9, 9]\nOutput: 1\nExpected: 2\n```\n\nCrap. I forgot about duplicates, because Leetcode didn\'t give any examples in the problem description that contained them! This is a simple, but good example of how your interviewers will sometimes trick you by hiding edge cases. **The interviewer will usually not be comprehensive when they give you test cases. It\'s your job to be vigilant and come up with the cases yourself!**\n\nAnyway, there is a simple solution to this duplicates problem. Just use dynamic programming: create an array `duplicates` where `duplicates[i]` = the number of duplicate elements on the inclusive interval `[i, j]`. Then, if you want to find the number of duplicates in subarray `nums[i\':j\']`, that number is just `duplicates[j\'] - duplicates[i\']`. Instead of just adding the numbers greater than the start and end of your consecutive series of numbers, you have to also add the number of duplicates in that range; after all, you can only use each number once.\n\nSolution:\n\n```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n from bisect import bisect_right\n \n nums.sort()\n # duplicates[i] is the count of duplicate numbers we\'ve seen\n # from indices 0 to i in the nums array\n duplicates = [0 for _ in nums]\n seen = set()\n cur = 0\n for i,num in enumerate(nums):\n cur += num in seen\n seen.add(num)\n duplicates[i] = cur\n duplicates.append(duplicates[-1])\n \n ret = float(\'inf\')\n i = 0\n j = bisect_right(nums, nums[i] + len(nums) - 1)\n while i < len(nums):\n start = nums[i]\n end = start + len(nums) - 1\n \n while j < len(nums) and nums[j] <= end:\n j += 1\n \n # we have to change every number greater than "end"...\n right = len(nums) - j\n # ... plus every number less than "start"...\n left = i\n # ... plus every number in between [start, end] that is a duplicate.\n dupes = duplicates[j] - duplicates[i]\n \n ret = min(ret, left + dupes + right)\n i += 1\n \n return ret\n``` | 22 | 1 | [] | 0 |
minimum-number-of-operations-to-make-array-continuous | 3C++ using sort &binary search/sliding window/queue||beats 100% | 3c-using-sort-binary-searchsliding-windo-igpc | Intuition\n Describe your first thoughts on how to solve this problem. \n1st method uses binary search.\n2nd method uses sliding windows which runs in 91ms and | anwendeng | NORMAL | 2023-10-10T01:20:08.445577+00:00 | 2023-10-10T05:58:01.148802+00:00 | 2,825 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1st method uses binary search.\n2nd method uses sliding windows which runs in 91ms and beats 100%.\n3rd method uses queue/deque which is in fact a variant for sliding window.\n\n[Please turn on English subtitle if necessary]\n[https://youtu.be/GrsD3FkB3OM?si=OUxhA8sTc66cua_l](https://youtu.be/GrsD3FkB3OM?si=OUxhA8sTc66cua_l)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the array `nums`\n2. Use unique & erase to remove the repetive elements in `nums`\n3. Use binary search upper_bound to compute the number for operations need.\n4. Or use sliding window\n5. Or use queue/deque to track the sliding window\n\nWith slight modification of 3rd solution, one can track the process for the sliding window\n```\nnums=[8,5,9,9,8,4]\nsort & remove the repetive elements\nnums=[4, 5, 8, 9]\nn=6 , m=4, k=2\nq=[4]\nq=[4, 5] \nq=[4, 5, 8] \nq=[4, 5, 8, 9]\nans=2\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n \\log n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\ndeque method: $$O(n)$$\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n=nums.size();\n int ans=n-1;\n sort(nums.begin(), nums.end());\n auto it=unique(nums.begin(), nums.end());\n nums.erase(it, nums.end());//erase the repetive elements\n int m=nums.size(), k=n-m;\n // cout<<"n="<<n<<" , m="<<m<<", k="<<k<<endl;\n #pragma unroll\n for(int i=0; i<m; i++){\n int l=nums[i], r=l+n-1;\n int j=upper_bound(nums.begin()+i, nums.end(), r)-nums.begin();\n ans=min(ans, n-j+i);\n }\n \n return ans;\n }\n};\n```\n# code using sliding windows runs in 91ms beats 100%\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n=nums.size();\n int ans=n-1;\n sort(nums.begin(), nums.end());\n auto it=unique(nums.begin(), nums.end());\n nums.erase(it, nums.end());//erase the repetive elements\n int m=nums.size(), k=n-m;\n // cout<<"n="<<n<<" , m="<<m<<", k="<<k<<endl;\n\n #pragma unroll\n for(int i=0, j=0; i<m; i++){\n while(j<m && nums[j]<nums[i]+n){ //Find first j out of range\n j++;\n }\n ans=min(ans, n-j+i);\n } \n return ans;\n }\n};\n\n```\n# Code using queue/deque which is also fast & beats 100%\n \n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n=nums.size();\n int ans=n-1;\n sort(nums.begin(), nums.end());\n auto it=unique(nums.begin(), nums.end());\n nums.erase(it, nums.end());//erase the repetive elements\n int m=nums.size(), k=n-m;\n // cout<<"n="<<n<<" , m="<<m<<", k="<<k<<endl;\n\n queue<int> q;// hold the sliding window\n #pragma unroll\n for (int i=0; i<m; i++) {\n while (!q.empty() && nums[i]-q.front()>= n)//q.front() is too small\n q.pop();// pop away from q\n \n q.push(nums[i]);\n ans = min(ans, n-(int)(q.size()));\n } \n return ans;\n }\n};\n\n```\n\n | 17 | 0 | ['Binary Search', 'Queue', 'Sliding Window', 'Sorting', 'C++'] | 1 |
minimum-number-of-operations-to-make-array-continuous | Sort and Sliding Window || C++ || O(NlogN) and O(N) | sort-and-sliding-window-c-onlogn-and-on-ojobp | INTUITION\nElements in the continuous array will be like:i, i+1, i+2, ..., i + arr.size()-1, for some integer i, because, max(arr) - min(arr) = i + arr.size() - | NAHDI51 | NORMAL | 2021-09-21T07:28:45.840545+00:00 | 2021-09-21T17:01:47.845582+00:00 | 1,479 | false | # INTUITION\nElements in the continuous array will be like:``` i, i+1, i+2, ..., i + arr.size()-1```, for some integer i, because, ```max(arr) - min(arr) = i + arr.size() - 1 - i = arr.size()-1,``` which is provided.\n\nThus, we will maintain a sliding window of ```a.size()``` (e.g ```a[i] - a[j] + 1<= a.size()```, the difference of ```a[i]-a[j]+1``` will be our slide, which will never exceed ```a.size()```), and count the number of **unique elements** present in the slide. (e.g ```i-j+1```), Our answer will be the **maximum** of such window, because we can **change the elements of the array** excluding them (As they are already good to go), which results in ```N - max```.\n\n# CODE\n```\nint minOperations(vector<int>& arr) {\n int n = arr.size();\n if(n == 1) return 0; //1 item is always continuous.\n sort(arr.begin(), arr.end());\n\t\n\tvector<int> a; //Array to store unique elements\n for(int i = 0; i < n-1; i++) {\n while(arr[i] == arr[i+1]) i++;\n a.push_back(arr[i]);\n }\n if(arr.back() != a.back()) a.push_back(arr.back());\n \n int mx = 0;\n for(int i = 0, j = 0; i < a.size(); i++) {\n while(j <= i && (a[i]-a[j]+1) > n) j++; //While our slide is invalid, keep reducing\n mx = max(mx, i-j+1); //Compare with the previous highest\n }\n return n - mx;\n}\n```\n# PERFORMANCE IF YOU ARE INTERESTED\n\n | 17 | 0 | ['C', 'Sliding Window', 'Sorting'] | 2 |
minimum-number-of-operations-to-make-array-continuous | Easy Sliding Window C++ Solution 180ms | easy-sliding-window-c-solution-180ms-by-2b023 | Important points are added as comments.\n\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int k = nums.size() - 1; // max size | hrishikesh_deshpande | NORMAL | 2021-10-05T16:29:22.855726+00:00 | 2022-10-17T21:22:31.413286+00:00 | 1,429 | false | Important points are added as comments.\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int k = nums.size() - 1; // max size of sliding window is the target gap between min and max elements\n sort(nums.begin(), nums.end()); // sorting in O(nlogn) time so that we can remove duplicates and slide over the array\n int newLen = unique(nums.begin(), nums.end()) - nums.begin(); // remove adjacent duplicates with STL unique\n int l = 0, r = 0, fin = 1; // initialize left and right pointers and the minimum elements in the window\n while (r < newLen) { // iterate over the new unique array\n if (l == r)\n r++; // if the window is closed, open it ;)\n else if (nums[r] - nums[l] > k)\n l++; // if window becomes bigger than allowed size, shrink it\n else {\n fin = max(fin, r - l + 1); // if window is in allowed size, maximize the number of elements in the window\n r++; // slide the right side \n }\n } // at this point, we have maximized the number of elements at any time inside the window\n return k - fin + 1; // return the missing elements in that window\n }\n};\n```\n\nIf you have any doubts or suggestions, please feel free to comment.\nIf you find this solution useful, you know where the upvote is :) | 15 | 0 | ['C', 'Sliding Window', 'C++'] | 0 |
minimum-number-of-operations-to-make-array-continuous | From Dumb to Pro with Just One Visit-My Promise to You with A Smart Approach to Minimize Operations | from-dumb-to-pro-with-just-one-visit-my-spdi5 | Intuition\n\nThe goal is to determine the minimum number of operations needed to make the numbers consecutive. To do this, we want to find the maximum unique el | curio_sity | NORMAL | 2023-10-10T04:03:27.935499+00:00 | 2023-10-10T04:03:27.935522+00:00 | 2,574 | false | # Intuition\n\nThe goal is to determine the minimum number of operations needed to make the numbers consecutive. To do this, we want to find the maximum unique element within a certain range, specifically from \'n\' to \'n + nums.size() - 1\', where \'n\' can be any element from the array. \n\nThe idea is that if we choose \'n\' as an element in the array, we have found the maximum value that doesn\'t need to be changed to make the numbers consecutive. Therefore, the result can be calculated as \'nums.size() - maximum unique element in the range (n to n + nums.size() - 1)\'. This will give us the minimum number of operations required to make the numbers consecutive, as we are subtracting the count of numbers that don\'t need to be changed from the total count of numbers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. **Sort the Array**: The first step is to sort the input `nums` array in ascending order. This is done using `sort(nums.begin(), nums.end())`.\n\n2. **Remove Duplicates**: After sorting, the code iterates through the sorted array to remove duplicate elements while maintaining a modified length in the variable `l`. This ensures that the array contains only unique elements in ascending order.\n\n3. **Choose a Reference Number \'n\'**: The algorithm selects a reference number \'n\' from the modified array. This \'n\' represents the starting point for our consecutive sequence. The code starts with \'n\' as the first element of the array.\n\n4. **Find the Maximum Consecutive Sequence**: The code iterates through the modified array, keeping track of the maximum consecutive sequence that includes \'n\'. It calculates the count of consecutive elements by comparing the difference between the current element and \'n\' and incrementing the count until the difference exceeds the maximum possible difference \'n\'. The maximum count is stored in the variable `maxi`.\n\n5. **Calculate the Minimum Operations**: The minimum number of operations needed to make the numbers consecutive is determined by subtracting the maximum count `maxi` from the total number of unique elements in the modified array, which is represented by `l`.\n\n6. **Return the Result**: Finally, the code returns the minimum number of operations as the result.\n\nThis approach ensures that we find the reference number \'n\' that, when used as the starting point, maximizes the consecutive sequence within the array. Subtracting this maximum count from the total unique elements gives us the minimum number of operations required to make the numbers consecutive.\n\n# Complexity\nHere are the time and space complexities for the given code:\n\n**Time Complexity:**\n\n1. Sorting the `nums` array takes O(n log n) time, where \'n\' is the number of elements in the array.\n2. Removing duplicates while iterating through the sorted array takes O(n) time, where \'n\' is the number of elements in the array.\n3. The consecutive sequence calculation also takes O(n) time in the worst case because for each element, we perform a while loop that goes through a portion of the array.\n4. The overall time complexity is dominated by the sorting step, so the total time complexity is O(n log n).\n\n**Space Complexity:**\n\n1. The code modifies the input `nums` array in place, so there is no additional space used for storing a separate copy of the array.\n2. The space used for variables like `maxi`, `count`, `n`, `l`, and loop indices is constant and not dependent on the size of the input array.\n3. Therefore, the space complexity of the code is O(1), which means it uses a constant amount of extra space.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums)\n {\n int maxi = 0; // Initialize a variable to store the maximum count of consecutive numbers\n int count = 0; // Initialize a variable to keep track of the current count of consecutive numbers\n int n = nums.size() - 1; // Calculate the maximum possible difference between numbers\n int l = 0; // Initialize a variable to keep track of the modified length of the \'nums\' vector\n\n sort(nums.begin(), nums.end()); // Sort the input vector \'nums\' in ascending order\n\n // Remove duplicates in \'nums\' and update \'l\' with the modified length\n for(int i = 0; i < nums.size(); i++) {\n if(i+1 < nums.size() && nums[i] == nums[i+1]) continue;\n nums[l++] = nums[i];\n }\n\n // Calculate the maximum count of consecutive numbers\n for(int i = 0, j = 0; i < l; i++) {\n while(j < l && (nums[j] - nums[i]) <= n) {\n count++;\n j++;\n }\n maxi = max(maxi, count);\n count--;\n }\n\n // Calculate and return the minimum number of operations needed to make the numbers consecutive\n return nums.size() - maxi;\n }\n};\n\n```\n```java []\nclass Solution {\n public int minOperations(int[] nums) {\n int maxi = 0; // Initialize a variable to store the maximum count of consecutive numbers\n int count = 0; // Initialize a variable to keep track of the current count of consecutive numbers\n int n = nums.length - 1; // Calculate the maximum possible difference between numbers\n int l = 0; // Initialize a variable to keep track of the modified length of the \'nums\' array\n\n Arrays.sort(nums); // Sort the input array \'nums\' in ascending order\n\n // Remove duplicates in \'nums\' and update \'l\' with the modified length\n for (int i = 0; i < nums.length; i++) {\n if (i + 1 < nums.length && nums[i] == nums[i + 1]) {\n continue;\n }\n nums[l++] = nums[i];\n }\n\n // Calculate the maximum count of consecutive numbers\n for (int i = 0, j = 0; i < l; i++) {\n while (j < l && (nums[j] - nums[i]) <= n) {\n count++;\n j++;\n }\n maxi = Math.max(maxi, count);\n count--;\n }\n\n // Calculate and return the minimum number of operations needed to make the numbers consecutive\n return nums.length - maxi;\n }\n}\n```\n```python3 []\nclass Solution:\n def minOperations(self, nums):\n maxi = 0 # Initialize a variable to store the maximum count of consecutive numbers\n count = 0 # Initialize a variable to keep track of the current count of consecutive numbers\n n = len(nums) - 1 # Calculate the maximum possible difference between numbers\n l = 0 # Initialize a variable to keep track of the modified length of the \'nums\' list\n\n nums.sort() # Sort the input list \'nums\' in ascending order\n\n # Remove duplicates in \'nums\' and update \'l\' with the modified length\n i = 0\n while i < len(nums):\n if i + 1 < len(nums) and nums[i] == nums[i + 1]:\n i += 1\n continue\n nums[l] = nums[i]\n l += 1\n i += 1\n\n # Calculate the maximum count of consecutive numbers\n i = 0\n j = 0\n while i < l:\n while j < l and (nums[j] - nums[i]) <= n:\n count += 1\n j += 1\n maxi = max(maxi, count)\n count -= 1\n i += 1\n\n # Calculate and return the minimum number of operations needed to make the numbers consecutive\n return len(nums) - maxi\n```\n*Thank you for taking the time to read my post in its entirety. I appreciate your attention and hope you found it informative and helpful.*\n\n**PLEASE UPVOTE THIS POST IF YOU FOUND IT HELPFUL** | 14 | 1 | ['Sliding Window', 'Sorting', 'C++', 'Java', 'Python3'] | 2 |
minimum-number-of-operations-to-make-array-continuous | 100% Beats 🤩 | Java - Sliding Window | | 100-beats-java-sliding-window-by-akhiles-jilb | \n\nHere\'s a step-by-step explanation of the code:\n\n1. The minOperations method takes an array of integers nums as input and returns an integer representing | Akhilesh21 | NORMAL | 2023-10-10T00:53:29.439094+00:00 | 2023-10-10T00:53:29.439112+00:00 | 1,153 | false | \n\nHere\'s a step-by-step explanation of the code:\n\n1. The `minOperations` method takes an array of integers `nums` as input and returns an integer representing the minimum number of operations required to make the array continuous.\n\n2. It starts by sorting the input array `nums` in ascending order using `Arrays.sort(nums)`.\n\n3. It initializes a variable `m` to 1. This variable `m` will be used to keep track of unique elements in the sorted array.\n\n4. The code then enters a loop to remove duplicate elements from the sorted array. It iterates through the sorted array and if the current element is different from the previous element, it updates the `nums` array in place, incrementing `m` and copying the unique element to the `nums` array. This loop effectively removes duplicate elements from the sorted array.\n\n5. After removing duplicates, the variable `m` represents the number of unique elements in the array.\n\n6. It initializes a variable `ans` to `n`, where `n` is the length of the original input array. `ans` will store the final answer, and it is initialized to a value larger than any possible answer.\n\n7. The code then enters another loop to find the minimum number of operations. This loop uses a sliding window approach. It maintains two pointers, `i` and `j`, representing the left and right boundaries of the window, respectively.\n\n8. Inside this loop, it checks if the difference between `nums[j]` and `nums[i]` is less than or equal to `n - 1`. If this condition is met, it means that the elements within the window can be made continuous. So, it updates the `ans` variable by taking the minimum of `ans` and `n - (j - i)`.\n\n9. The `j` pointer is incremented until the window is no longer continuous, and the loop continues.\n\n10. Finally, the method returns the value of `ans`, which represents the minimum number of operations required to make the array continuous.\n\nThis code efficiently removes duplicates, sorts the array, and uses a sliding window approach to find the minimum operations, making it an optimized solution for the problem.\n## Code\n``` Java []\nclass Solution {\n public int minOperations(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums); // Sort the input array in ascending order\n int m = 1;\n \n // Remove duplicate elements in the sorted array\n for (int i = 1; i < n; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[m++] = nums[i];\n }\n }\n \n int ans = n;\n \n // Use a sliding window to find the minimum number of operations\n for (int i = 0, j = 0; i < m; ++i) {\n while (j < m && nums[j] - nums[i] <= n - 1) {\n ++j;\n }\n ans = Math.min(ans, n - (j - i));\n }\n \n return ans;\n }\n}\n\n```\n\n# Complexity\n#### Time complexity: O(n*logn) ;\n1. Sorting the array using `Arrays.sort(nums)` takes O(n * log(n)) time, where \'n\' is the length of the input array.\n\n2. Removing duplicates from the sorted array takes O(n) time. In the worst case, you might have to iterate through the entire array once.\n\n3. The sliding window loop iterates through the unique elements in the array, and each iteration has a constant time complexity, as the inner loop\'s execution is limited by the length of the array. Therefore, the sliding window loop has a time complexity of O(m), where \'m\' is the number of unique elements in the array.\n\nOverall, the dominant time complexity factor is the sorting step (O(n * log(n))), so the time complexity of the entire code is **O(n * log(n))**.\n\n#### Space complexity: O(1) ;\n1. The code uses a constant amount of extra space for variables like `n`, `m`, `ans`, `i`, `j`, etc. So, the space complexity for these variables is O(1).\n\n2. The code modifies the `nums` array in place to remove duplicates, and it doesn\'t use any additional data structures that grow with the input size. Therefore, the space complexity for the `nums` array is O(1) as well.\n\nThe overall space complexity of the code is O(1) because it uses a constant amount of extra space that does not depend on the size of the input array.\n\n | 14 | 0 | ['Sliding Window', 'Java'] | 1 |
minimum-number-of-operations-to-make-array-continuous | simple c++ solution || Beginner Friendly || Sorting+Binary search | simple-c-solution-beginner-friendly-sort-mw3c | \n# Approach\n Describe your approach to solving the problem. \nour target is make continuous array \nmax element - min element = array size - 1\nif array size | utkarshR_Patel | NORMAL | 2023-10-10T08:42:47.892261+00:00 | 2023-10-10T08:42:47.892279+00:00 | 1,077 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nour target is make continuous array \nmax element - min element = array size - 1\nif array size 5 possible array [1,2,3,4,5] , [2,3,4,5,6] , [3,4,5,6,7] etc\n\n \npossible answer range \narray is already continuous answer=>0 \narray all number are random and diffarance in very high \nlike [100,200,300,400,500] \nyou can make like [100,101,102,103,104] or [200,201,202,203,204]=> \nanswer=4 (array size - 1)\nanswer always between [0,array size - 1]\n\nnow explain with example\nsuppose array is [10,9,12,4,11,8] \nso first sort array \nsorted array[4,8,9,10,11,12]\n\nnow take nums[i] min value and make array arrcoding min value and find minimum step for make this array \nnow you can try to make \n[4,5,6,7,8,9]=>min is 4 (steps=a)\n[8,9,10,11,12,13]=>min is 8 (steps=b)\n[9,10,11,12,13,14]=>min is 9 (steps=c)\n[10,11,12,13,14,15]=>min is 10 (steps=d)\n[11,12,13,14,15,16]=>min is 11 (steps=e)\n[12,13,14,15,16,17]=>min is 12 (steps=f)\nnow answer is min(a,b,c,d,e,f)\n\nchallenge is how to find a,b,c,d,e,f \nsuppose min value of array is 4 and array size is 6 then max value of array is 4+(array size-1) = 4+5=9\n\nfind upper bound 9 of array => it is index 3 [4,8,9,10,11,12]\nso index 0 to index 2 all elements are between 4 to 9 so we can change all elements those not present between 4 to 9 index 3 to index 5 => 3 elements \na=3\n\nnow same thing do for 8 \n8+5=13 upper bound of 8 is array end so [4,8,9,10,11,12] index 1 to 5 all elements are right change only one index 0 change 4 to 13 \nb=1 \n\nfind all c,d,e,f same algorithm and take minimum here answer is 1 \nmake [8,9,10,11,12,13] change 4 to 13\n\nThis code is valid if array contain all unique elements in duplicate elements is present than algorithm is fail !!!\n\nfor example [4,5,8,8,9,9] make [4,5,6,7,8,9] 4+5=9 upper bound of 9 is array end so all elements in array between 4 to 9 accoring to our algorithm answer is 0 but here not because of duplicate elements \n\nso solution is simple change duplicate element to INT_MAX\n[4,5,8,8,9,9] to [4,5,8,9,INT_MAX,INT_MAX] and apply algorithm for 4,5,8,9 not for INT_MAX \n\nhere i take 1e9+7 as INT_MAX \n\n\n# Complexity\n- Time complexity: O(n*logn) \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n map<int,bool>mp; // check duplicate elements using map\n for(int i=0;i<nums.size();i++)\n {\n // duplicate element present then make 1e9+7 \n if(mp[nums[i]]==true)\n nums[i]=1e9+7; \n else\n mp[nums[i]]=true;\n }\n //sort array \n sort(nums.begin(),nums.end());\n int max_right_len=0;\n for(int i=0;i<nums.size();i++)\n {\n int val=nums[i];\n if(val!=1e9+7)\n {\n int target=val+nums.size()-1;\n int index=upper_bound(nums.begin(),nums.end(),target)-nums.begin();\n index--;\n max_right_len=max(max_right_len,index-i+1);\n }\n }\n return nums.size()-max_right_len;\n }\n};\n``` | 11 | 0 | ['Binary Search', 'Sorting', 'C++'] | 1 |
minimum-number-of-operations-to-make-array-continuous | Detailed explanation | Sorting + Binary Search | detailed-explanation-sorting-binary-sear-4c23 | \nClearly, if input array is of length n, then our final continuous array must be of form:\n\n[start, start + 1, ... start + n - 1], where start is some startin | khaufnak | NORMAL | 2021-09-18T16:00:35.325383+00:00 | 2021-09-18T16:05:32.388641+00:00 | 776 | false | \nClearly, if input array is of length ```n```, then our final continuous array must be of form:\n\n[start, start + 1, ... start + n - 1], where ```start``` is some starting element. \n\nKey idea: We can ```start``` our final continuous array from one of the given elements of the input array to get the minimum operations. \n***Why?***\nWell, this is because by starting at an element ```i``` of input array, we give ourselves the opportunity to find more elements in the range [```arr[i] + 1```, ```arr[i] + n - 1```] that are already present in the input. This will help us reduce the number of operations that we need to perform in order to get rest of the elements in the range [```arr[i]```, ```arr[i] + n - 1```]\n\n***How do I code?***\nWe consider each element of the given array as a potential starting point of the final continuous array that we will form.\nGiven a potential starting element at ```i```\nWe can simply reuse all the unique elements of the given array that are between (```arr[i] + 1```, ```arr[i] + n - 1```)\nTo find these reusable elements, we keep input sorted and then binary search for the elements in this range.\n\n```\nclass Solution {\n public int minOperations(int[] nums) {\n // Maintain only the list of unique elements. \n List<Integer> unique = new ArrayList<>();\n HashSet<Integer> vis = new HashSet<>();\n for (int i = 0; i < nums.length; ++i) {\n if (!vis.contains(nums[i])) {\n vis.add(nums[i]);\n unique.add(nums[i]);\n }\n }\n\n // sort the unique elements, this will help us find reusable elements in O(logn) via binary search.\n Collections.sort(unique);\n \n int min = Integer.MAX_VALUE;\n for (int i = 0; i < unique.size(); ++i) {\n int start = unique.get(i);\n int last = unique.get(i) + nums.length - 1;\n int lo = i;\n int hi = unique.size() - 1;\n\n // find the elements that we can reuse if the starting point is start\n while (lo < hi) {\n int mi = (lo + hi + 1) / 2;\n\n if (unique.get(mi) <= last) {\n lo = mi;\n } else {\n hi = mi - 1;\n }\n }\n\n min = Math.min(min, nums.length - (lo - i + 1));\n }\n return min;\n }\n}\n```\n\nComplexity: O(nlogn) | 11 | 3 | [] | 2 |
minimum-number-of-operations-to-make-array-continuous | O(1) Space || O(nlogn) Time || Sort --> Binary Search | o1-space-onlogn-time-sort-binary-search-fqa7q | Complexity\n- Time complexity:\nO(nlogn) Add your time complexity here, e.g. O(n) \n\n- Space complexity:\nO(1) Add your space complexity here, e.g. O(n) \n\n# | abhijeet5000kumar | NORMAL | 2023-10-10T15:11:56.401503+00:00 | 2023-10-10T15:13:16.701979+00:00 | 697 | false | # Complexity\n- Time complexity:\n$$O(nlogn)$$<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n$$O(1)$$<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int ans=nums.size(),currans=0,x=nums.size();\n\n int t=nums[0],j=0;\n for(int i=1;i<x;i++){ //Set duplicates to zero\n if(nums[i]==t){\n nums[i]=0;\n j++;} //j=number of zero (duplicates)\n else{t=nums[i];}\n }\n\n if(j!=0){sort(nums.begin(),nums.end());}\n\n for(int i=j;i<x;i++){\n int endrange=nums[i]+x-1; //maximum possible range for num[i]\n int s=i,e=x-1,mid=(s+e)/2;\n while(s<=e){ //Find element which is just smaller(or =) than endrange\n if(nums[mid]==endrange || s==e){\n if(s==e && nums[mid]>endrange){\n mid=mid-1;}\n currans=(x-mid-1)+i;\n ans=min(ans,currans);\n break;}\n\n else if(nums[mid]>endrange){\n e=mid-1;}\n else{\n s=mid+1;}\n if(s>e){\n currans=(x-e-1)+i;\n ans=min(ans,currans);}\n mid=(s+e)/2;\n }\n }\n return ans;\n }\n};\n\n``` | 9 | 1 | ['Array', 'Binary Search', 'Sliding Window', 'Sorting', 'C++'] | 0 |
minimum-number-of-operations-to-make-array-continuous | [Python] Simple sort & queue, 2-liner | python-simple-sort-queue-2-liner-by-vu-d-yavy | Intuition\n\nThe continuous array that the problem asks for is simply an array with the form [x, x + 1, x + 2, x + 3, ..., x + n - 1], but scrambled. Let\'s cal | vu-dinh-hung | NORMAL | 2023-10-10T00:37:36.883632+00:00 | 2023-10-10T00:51:18.545987+00:00 | 627 | false | # Intuition\n\nThe continuous array that the problem asks for is simply an array with the form `[x, x + 1, x + 2, x + 3, ..., x + n - 1]`, but scrambled. Let\'s call that original sorted form **sorted continuous**.\n\nTo simplify the problem, we simply need to find the longest incomplete **sorted continuous** array from the given array.\n\nWe can keep a queue of the current longest incomplete **sorted continuous** array. Whenever adding a new element would make the queue an invalid incomplete **sorted continuous** array (i.e. the added element is larger than `queue[0] + N - 1`), we pop the first element of the queue.\n\nWhatever numbers that aren\'t included in the longest incomplete **sorted continuous** must be replaced. That\'s the number of operations we\'re looking for.\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n N = len(nums)\n queue = deque()\n max_length = 1\n\n for num in sorted(set(nums)):\n while queue and num - queue[0] >= N:\n queue.popleft()\n\n queue.append(num)\n max_length = max(max_length, len(queue))\n\n return N - max_length\n\n```\n\n## Time complexity\nSorting: O(NlogN)\nLoop: O(N)\n-> O(NlogN)\n\n## Note\n\nFor each `num` in `sorted(set(nums))`, we can also just binary search for the expected `num + N - 1` ending number. This will take O(logN) per loop iteration instead of O(1), but won\'t affect the final time complexity, which is bounded by the O(NlogN) sort anyway.\n\n## 2-liner using binary search, just for fun\n```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n sn = sorted(set(nums))\n return min(len(nums) - (bisect_right(sn, sn[i] + len(nums) - 1) - i) for i in range(len(sn)))\n\n``` | 9 | 0 | ['Queue', 'Python3'] | 2 |
minimum-number-of-operations-to-make-array-continuous | ✅ C++ naive solution that works 😎 | c-naive-solution-that-works-by-tyrex_19-d5zm | Intuition\n\nThe idea is to remove duplicates from the array \u2728, then use a brute force approach where you consider each element as the minimum of the resul | Tyrex_19 | NORMAL | 2023-10-10T04:51:10.999553+00:00 | 2023-10-10T05:59:29.787900+00:00 | 1,203 | false | # Intuition\n\nThe idea is to remove duplicates from the array \u2728, then use a brute force approach where you consider each element as the minimum of the resulting array \uD83D\uDE0E. The goal is to find how many elements you should add to make the condition of continuity respected \uD83D\uDD04. By evaluating each element in this manner, the minimum number of operations required to achieve a continuous array can be determined \u2699\uFE0F\uD83D\uDD0D.\n\n# Approach\n\n1. Initialize the answer **ans** with the maximum possible value, which is n, the size of the input array.\n\n1. Create a set called st to store the unique elements from the input array nums. This helps eliminate duplicates and maintain the elements in sorted order automatically.\n\n1. Create a vector called uniqueNums and populate it with the unique elements from the set. This vector will contain the unique elements in sorted order.\n\n1. Initialize a variable visited to 0. This variable will keep track of the number of elements visited.\n\n 1. Iterate over the uniqueNums vector using the index mi. This represents the current starting element for the subarray.\n\n 1. While visited is less than the size of uniqueNums and the element at visited index is less than uniqueNums[mi] + n, increment visited. This loop helps find the ending position for the subarray.\n\n 1. Calculate the number of elements between mi and visited, which represents the subarray size. Subtract this value from n to get the number of operations needed to make the subarray continuous. Update the ans with the minimum value between the current ans and n - subAns.\n\n\nFinally, return the minimum number of operations stored in ans.\n\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size();\n int ans = n;\n \n set<int> st(nums.begin(), nums.end());\n vector<int> uniqueNums;\n for (int num : st) {\n uniqueNums.push_back(num);\n }\n int visited = 0;\n for (int mi = 0; mi < uniqueNums.size(); mi++) {\n while (visited < uniqueNums.size() && uniqueNums[visited] < uniqueNums[mi] + n) {\n visited++;\n }\n \n int subAns = visited - mi;\n ans = min(ans, n - subAns);\n }\n \n return ans;\n }\n};\n```\n\nhttps://youtu.be/_zOzDfsfAvU | 8 | 2 | ['C++'] | 3 |
minimum-number-of-operations-to-make-array-continuous | Easy To Understand || Sliding Window || C++ || Java | easy-to-understand-sliding-window-c-java-7i3b | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nSorting and Removing Duplicates:\nFirst, the code sorts the input array n | me_avi | NORMAL | 2023-10-10T03:17:02.597387+00:00 | 2023-10-10T03:17:02.597419+00:00 | 1,165 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSorting and Removing Duplicates:\nFirst, the code sorts the input array nums in ascending order. This is done to make it easier to find the maximum and minimum elements.\nIt also removes any duplicate elements, ensuring that all elements are unique. This addresses the first condition.\n\nSliding Window Approach:\nThe core of the code is a sliding window approach, where the code iterates through potential "start" elements and extends a "window" to find a valid continuous subarray.\nFor each potential "start" element, it uses a while loop to find the maximum possible "end" element such that the difference between nums[end] and nums[start] is less than n (the length of the array).\n\nCalculating Operations:\nOnce the valid subarray is found, the code calculates the number of operations needed to make it continuous.\nThe number of operations is calculated as n - (end - start + 1). This formula considers the length of the array and the size of the valid subarray.\n\nTracking Minimum Operations:\nThe code keeps track of the minimum operations found so far using the ans variable.\nFor each potential "start" element, it updates ans with the minimum of the current ans and the calculated operations.\n\nFinal Result:\nAfter iterating through all potential "start" elements, the code returns the final value of ans, which represents the minimum number of operations needed to make the entire array continuous.\n\n# Complexity\n- Time complexity:\no(n*log(n))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n```c++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size();\n int ans=INT_MAX;\n sort(nums.begin(), nums.end());\n nums.erase(unique(begin(nums),end(nums)),end(nums));\n int end = 0;\n for(int start=0,end=0; start<nums.size(); ++start)\n {\n while (end < nums.size() && nums[end] < nums[start] + n) \n {\n ans=min(ans,n-(++end -start));\n }\n }\n\n return ans;\n }\n};\n```\n```python []\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums))\n ans = sys.maxsize\n for i, s in enumerate(nums):\n e = s + n - 1\n idx = bisect_right(nums, e)\n ans = min(ans, n - (idx - i))\n return ans\n\n```\n```java []\nclass Solution {\n public int minOperations(int[] nums) {\n Arrays.sort(nums);\n int uniqueLen = 1;\n for (int i = 1; i < nums.length; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[uniqueLen++] = nums[i];\n }\n }\n \n int ans = nums.length;\n for (int i = 0, j = 0; i < uniqueLen; ++i) {\n while (j < uniqueLen && nums[j] - nums[i] <= nums.length - 1) {\n ++j;\n }\n ans = Math.min(ans, nums.length - (j - i));\n }\n \n return ans;\n }\n}\n```\n | 7 | 0 | ['C++', 'Java', 'Python3'] | 0 |
minimum-number-of-operations-to-make-array-continuous | 100% Beats 🤩 | Java | C++ | Sliding Window | | 100-beats-java-c-sliding-window-by-akhil-b0ti | Java 100 % Beats\nC++ 87 % Beats\n\n# Java\nHere\'s a step-by-step explanation of the code:\n\n1. The minOperations method takes an array of integers nums as in | Akhilesh21 | NORMAL | 2023-10-10T01:16:26.221468+00:00 | 2023-10-10T01:17:10.858779+00:00 | 153 | false | Java 100 % Beats\nC++ 87 % Beats\n\n# Java\nHere\'s a step-by-step explanation of the code:\n\n1. The `minOperations` method takes an array of integers `nums` as input and returns an integer representing the minimum number of operations required to make the array continuous.\n\n2. It starts by sorting the input array `nums` in ascending order using `Arrays.sort(nums)`.\n\n3. It initializes a variable `m` to 1. This variable `m` will be used to keep track of unique elements in the sorted array.\n\n4. The code then enters a loop to remove duplicate elements from the sorted array. It iterates through the sorted array and if the current element is different from the previous element, it updates the `nums` array in place, incrementing `m` and copying the unique element to the `nums` array. This loop effectively removes duplicate elements from the sorted array.\n\n5. After removing duplicates, the variable `m` represents the number of unique elements in the array.\n\n6. It initializes a variable `ans` to `n`, where `n` is the length of the original input array. `ans` will store the final answer, and it is initialized to a value larger than any possible answer.\n\n7. The code then enters another loop to find the minimum number of operations. This loop uses a sliding window approach. It maintains two pointers, `i` and `j`, representing the left and right boundaries of the window, respectively.\n\n8. Inside this loop, it checks if the difference between `nums[j]` and `nums[i]` is less than or equal to `n - 1`. If this condition is met, it means that the elements within the window can be made continuous. So, it updates the `ans` variable by taking the minimum of `ans` and `n - (j - i)`.\n\n9. The `j` pointer is incremented until the window is no longer continuous, and the loop continues.\n\n10. Finally, the method returns the value of `ans`, which represents the minimum number of operations required to make the array continuous.\n\nThis code efficiently removes duplicates, sorts the array, and uses a sliding window approach to find the minimum operations, making it an optimized solution for the problem.\n## Code\n``` Java []\nclass Solution {\n public int minOperations(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums); // Sort the input array in ascending order\n int m = 1;\n \n // Remove duplicate elements in the sorted array\n for (int i = 1; i < n; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[m++] = nums[i];\n }\n }\n \n int ans = n;\n \n // Use a sliding window to find the minimum number of operations\n for (int i = 0, j = 0; i < m; ++i) {\n while (j < m && nums[j] - nums[i] <= n - 1) {\n ++j;\n }\n ans = Math.min(ans, n - (j - i));\n }\n \n return ans;\n }\n}\n\n```\n\n# Complexity\n#### Time complexity: O(n*logn) ;\n1. Sorting the array using `Arrays.sort(nums)` takes O(n * log(n)) time, where \'n\' is the length of the input array.\n\n2. Removing duplicates from the sorted array takes O(n) time. In the worst case, you might have to iterate through the entire array once.\n\n3. The sliding window loop iterates through the unique elements in the array, and each iteration has a constant time complexity, as the inner loop\'s execution is limited by the length of the array. Therefore, the sliding window loop has a time complexity of O(m), where \'m\' is the number of unique elements in the array.\n\nOverall, the dominant time complexity factor is the sorting step (O(n * log(n))), so the time complexity of the entire code is **O(n * log(n))**.\n\n#### Space complexity: O(1) ;\n1. The code uses a constant amount of extra space for variables like `n`, `m`, `ans`, `i`, `j`, etc. So, the space complexity for these variables is O(1).\n\n2. The code modifies the `nums` array in place to remove duplicates, and it doesn\'t use any additional data structures that grow with the input size. Therefore, the space complexity for the `nums` array is O(1) as well.\n\nThe overall space complexity of the code is O(1) because it uses a constant amount of extra space that does not depend on the size of the input array.\n\n---\n\n# C++\n\n\nHere\'s a step-by-step explanation of the code:\n\n1. The `minOperations` method takes a vector of integers `a` as input and returns an integer representing the minimum number of operations required to make the array continuous.\n\n2. It starts by getting the size of the input vector and assigns it to the variable `n`.\n\n3. The code then sorts the input vector `a` in ascending order using the `std::sort` function.\n\n4. After sorting, it removes duplicate elements from the vector using the `std::unique` function along with the `resize` method. This step ensures that the vector only contains unique elements.\n\n5. It initializes the variable `ans` to `n`, where `n` is the length of the original input vector. `ans` will store the final answer, and it is initialized to a value larger than any possible answer.\n\n6. The code enters a loop to find the minimum number of operations. It uses a sliding window approach, maintaining two pointers `l` and `r`, representing the left and right boundaries of the window, respectively.\n\n7. Inside this loop, it checks if the difference between `a[r]` and `a[l]` is less than or equal to `n - 1`. If this condition is met, it means that the elements within the window can be made continuous. So, it updates the `ans` variable by taking the minimum of `ans` and `n - (r - l)`.\n\n8. The `r` pointer is incremented until the window is no longer continuous, and the loop continues.\n\n9. Finally, the method returns the value of `ans`, which represents the minimum number of operations required to make the vector continuous.\n\nThis code efficiently removes duplicates, sorts the vector, and uses a sliding window approach to find the minimum operations, making it an optimized solution for the problem.\n\n## Code\n``` C++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& a) {\n int n = a.size();\n sort(a.begin(), a.end()); // Sort the input vector in ascending order\n a.resize(unique(a.begin(), a.end()) - a.begin()); // Remove duplicate elements\n\n int ans = n; // Initialize the answer to n\n\n // Use a sliding window approach to find the minimum number of operations\n for (int l = 0, r = 0; l < a.size(); ++l) {\n while (r < a.size() && a[r] <= a[l] + n - 1) ++r;\n ans = min<int>(ans, n - (r - l));\n }\n \n return ans; // Return the minimum number of operations\n }\n};\n```\n\n## Complexity\n#### Time complexity: O(n*logn) ;\n1. Sorting the vector using `std::sort(a.begin(), a.end())` takes O(n * log(n)) time, where \'n\' is the size of the input vector.\n\n2. Removing duplicates from the sorted vector using `std::unique` and `resize` takes O(n) time. In the worst case, you might have to iterate through the entire vector once.\n\n3. The sliding window loop iterates through the unique elements in the vector. Each iteration of this loop performs a constant amount of work as it checks conditions and updates variables. The number of iterations depends on the number of unique elements in the vector, which is at most \'n\'. So, the sliding window loop takes O(n) time.\n\nOverall, the dominant time complexity factor is the sorting step (O(n * log(n))), so the time complexity of the entire code is **O(n * log(n))**.\n\n#### Space complexity: O(1) ;\n1. The code uses a constant amount of extra space for variables like `n`, `ans`, `l`, `r`, and a few loop control variables. These variables do not depend on the size of the input vector. So, the space complexity for these variables is O(1).\n\n2. The code modifies the vector in place to remove duplicates, and it doesn\'t use any additional data structures that grow with the input size. Therefore, the space complexity for the vector manipulation is also O(1).\n\nThe overall space complexity of the code is O(1) because it uses a constant amount of extra space that does not depend on the size of the input vector. | 7 | 0 | ['Sliding Window', 'C++', 'Java'] | 0 |
minimum-number-of-operations-to-make-array-continuous | [Python3] sliding window | python3-sliding-window-by-ye15-zjvp | Please check out this commit for the solutions of biweekly 61. \n\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\ | ye15 | NORMAL | 2021-09-18T21:40:54.774119+00:00 | 2021-09-18T22:25:25.089140+00:00 | 608 | false | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/0dcbb71853720dc380becdd8968bf94bdf419b7d) for the solutions of biweekly 61. \n```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums))\n \n ans = ii = 0\n for i, x in enumerate(nums): \n if x - nums[ii] >= n: ii += 1\n ans = max(ans, i - ii + 1)\n return n - ans \n``` | 7 | 1 | ['Python3'] | 1 |
minimum-number-of-operations-to-make-array-continuous | Simple java logic | simple-java-logic-by-ramudarsingh46-todd | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ramudarsingh46 | NORMAL | 2023-10-10T15:00:39.868745+00:00 | 2023-10-10T15:00:39.868777+00:00 | 16 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minOperations(int[] nums) {\n Arrays.sort(nums);\n int uniqueLen = 1;\n for (int i = 1; i < nums.length; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[uniqueLen++] = nums[i];\n }\n }\n \n int ans = nums.length;\n for (int i = 0, j = 0; i < uniqueLen; ++i) {\n while (j < uniqueLen && nums[j] - nums[i] <= nums.length - 1) {\n ++j;\n }\n ans = Math.min(ans, nums.length - (j - i));\n }\n \n return ans;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
minimum-number-of-operations-to-make-array-continuous | C++ || Basic Beginners Approach || My Notes || Detailed Solution || Easy to Understand | c-basic-beginners-approach-my-notes-deta-iugd | Approach\n Describe your approach to solving the problem. \n\n\n\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nN*log(M)\n\n# Code\n\nclass | vaibhav_chachra | NORMAL | 2023-10-10T05:34:51.723937+00:00 | 2023-10-10T05:34:51.723968+00:00 | 545 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nN*log(M)\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n=nums.size();\n set<int> st;\n for(auto it:nums)st.insert(it);\n nums.resize(0);\n for(auto it:st)nums.push_back(it);\n int ans=n;\n for(int i=0;i<nums.size();i++){\n int first=nums[i];\n int last=first+n-1;\n vector<int>::iterator upper=upper_bound(nums.begin(),nums.end(),last);\n int len=upper-nums.begin();\n ans=min(ans,n-(len-i));\n }\n return ans;\n }\n};\n``` | 6 | 0 | ['Binary Search', 'Sorting', 'C++'] | 1 |
minimum-number-of-operations-to-make-array-continuous | Prefix Sum Solution. TC: O(NLog(N)) SC: O(N) | prefix-sum-solution-tc-onlogn-sc-on-by-1-gm6s | Since the array must be continuous, if the array starts with an element a, it will be continuous, and the last element will be a + size of the array - 1.\n\nWe | 1mknown | NORMAL | 2022-06-06T19:59:46.728495+00:00 | 2022-06-06T20:02:05.108790+00:00 | 619 | false | Since the array must be continuous, if the array starts with an element a, it will be continuous, and the last element will be a + size of the array - 1.\n\nWe can try to find an optimal starting position \'a\' for which we will need to change as few elements of the array as possible.\n\nTo do that, let us create an ordered map where each key of the map denotes an arbitrary starting position \'a\'. Now we iterate over all the elements of the array. For any element nums[i], it can be a part of all the arrays with starting positions in the range [max(1, nums[i] - k+1), nums[i]). So we increment the value of map at max(1, nums[i] - k+1) by 1 and decrement the value of map at (nums[i] + 1) by 1.\n\nNow do the prefix sum over all the keys of the map. It will give us the total number of elements that do not need modification for each key of the map.\n\nIterate over all the keys and find the one which has the highest value and then return the size of array - the highest value.\n\nexample: [1, 2, 3, 5, 6]\nmp[1]=1, mp[2]=-1\nmp[1]=2, mp[3]=-1\nmp[1]=3, mp[4]=-1\nmp[1]=4, mp[6]=-1\nmp[2]=0, mp[7]=-1\n\nNow the values can be given as:\n\nkeys = 1 2 3 4 5 6 7\nvalues = 4 0 -1 -1 -1 -1 -1\n\nsum = 4 4 3 2 1 0 -1\n\nSo the starting points 1 and 2 requires only one modifcation so the answer is 5-4=1.\n\nNote: We need to take care of duplicate elements. Figure out why\n\n**C++ code**\n\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n set<int>s;\n for(auto& val:nums){\n s.insert(val);\n }\n map<int, int>mp;\n for(auto& val:s){\n int l=max(1, val-(int)nums.size()+1);\n mp[l]++;\n mp[val+1]--;\n }\n int sum=0;\n for(auto& val:mp){\n sum+=val.second;\n val.second=sum;\n }\n int ans=INT_MAX;\n for(auto val:mp){\n ans=min(ans, (int)nums.size()-val.second);\n }\n return ans;\n }\n};\n```\n\n\n | 6 | 0 | ['C', 'Prefix Sum'] | 3 |
minimum-number-of-operations-to-make-array-continuous | Easy to understand || Concise C++ Solution || Sliding Window | easy-to-understand-concise-c-solution-sl-vftb | Intuition\nThe idea is to find the minimum number of operations to make the array continuous by removing elements while maintaining uniqueness.\n# Approach\n1. | Ankita_Chaturvedi | NORMAL | 2023-10-10T02:17:27.013881+00:00 | 2023-10-10T02:17:27.013902+00:00 | 692 | false | # Intuition\nThe idea is to find the minimum number of operations to make the array continuous by removing elements while maintaining uniqueness.\n# Approach\n1. Create a set to ensure uniqueness.\n2. Find unique elements from the input array.\n3. Iterate through unique elements to form a consecutive subarray.\n4. Calculate the number of operations to make it continuous.\n5. Find the minimum operations needed among all subarrays.\n6. Return the minimum operations required.\n\n# Complexity\n- Time complexity:\nO(n log n) due to sorting and set operations.\n\n- Space complexity:\nO(n) for the set s and vector v.\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size();\n set<int> s(nums.begin(), nums.end());\n vector<int> v;\n int mini = n;\n for (int num : s) {\n v.push_back(num);\n }\n int j = 0;\n for (int i = 0; i < v.size(); i++) {\n while (j < v.size() && v[j] < v[i] + n) {\n j++;\n }\n int count = j - i;\n mini= min(mini, n - count);\n }\n return mini;\n }\n};\n\n``` | 5 | 1 | ['Sliding Window', 'C++'] | 0 |
minimum-number-of-operations-to-make-array-continuous | Beats 100% on runtime [EXPLAINED] | beats-100-on-runtime-explained-by-r9n-l1zl | Intuition\nMake the array continuous by ensuring all numbers are unique and that they span a range equal to their count. This can be achieved by replacing eleme | r9n | NORMAL | 2024-10-22T05:18:53.723631+00:00 | 2024-10-22T05:18:53.723665+00:00 | 22 | false | # Intuition\nMake the array continuous by ensuring all numbers are unique and that they span a range equal to their count. This can be achieved by replacing elements in the array while minimizing the number of replacements needed.\n\n# Approach\nUse a sliding window technique to find the longest subsequence of unique numbers that fits within the required range, then calculate the minimum operations needed by subtracting the length of this subsequence from the total number of unique elements.\n\n# Complexity\n- Time complexity:\n O(n log n) due to sorting the unique numbers, where n is the number of elements in the original array.\n\n- Space complexity:\nO(n) for storing unique elements in a set and the sorted array.\n\n# Code\n```csharp []\npublic class Solution {\n public int MinOperations(int[] nums) {\n HashSet<int> uniqueNums = new HashSet<int>(nums); // Store unique elements\n int n = uniqueNums.Count;\n int[] sortedNums = new int[n];\n uniqueNums.CopyTo(sortedNums); // Copy unique elements to an array\n\n Array.Sort(sortedNums); // Sort the unique array\n\n int minOperations = nums.Length; // Initialize min operations to total length\n int r = 0;\n\n // Sliding window to determine the minimum operations\n for (int l = 0; l < sortedNums.Length; l++) {\n while (r < sortedNums.Length && sortedNums[r] <= sortedNums[l] + nums.Length - 1) {\n r++;\n }\n minOperations = Math.Min(minOperations, nums.Length - (r - l)); // Update min operations\n }\n\n return minOperations; // Return the result\n }\n}\n\n``` | 4 | 0 | ['C#'] | 0 |
minimum-number-of-operations-to-make-array-continuous | Sliding Window -Intuitive -C++ Solution. | sliding-window-intuitive-c-solution-by-m-3i5r | Intuition\nConvert the problem into a known problem which can be a little intuitive here.\nSort the array first.. Now we can reduce the problem to some extent b | mitthunkrishna | NORMAL | 2023-10-10T02:17:45.688586+00:00 | 2023-10-10T17:50:54.217897+00:00 | 339 | false | # Intuition\nConvert the problem into a known problem which can be a little intuitive here.\nSort the array first.. Now we can reduce the problem to some extent by just checking the window which has maximum number of elements where the maximum element and the minimum element in the array is <= (n-1).\n\n\nExample :-\n [41, 33, 29, 33, 35, 26, 47, 24, 18, 28]\n\n Now sort the array :- \n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n\n Keep a left pointer (left = 0)\n right = 1\n `Move the pointer right until nums[right]-nums[i] <= (n-1)`\n After that use the left pointer to reduce the window size by moving it to the right. \n We can also take care of the unique elements by using a variable.\n\n Here in the example n=10\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => window_size = 3, maxi = 3(so far), but we want to carry unique elements in the array.\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => (Note:This is an intermediatary result)`now we can see that 28-18>=10 so it\'s time to move the left pointer to right until we can see nums[right]-nums[left] >= n.`\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => window_size = 3, maxi = 3, also check for duplicates using left pointer to check the unique elements(Check the code for how to track the unique elements).\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => window_size = 4, maxi = 4.\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => window_size = 5, maxi = 5\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => window_size = 5, maxi = 5 (Here don\'t count the extra occurence of 33 in the window)\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => (Intermediatary step)Now we have to move the left pointer.\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => window_size = 5, maxi = 5\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => (Intermediatary step)Now we have to move the left pointer till 33.\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => window_size = 3, maxi = 5\n\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => (Intermediatary step)Now we have to move the left pointer till 41.\n\n [18, 24, 26, 28, 29, 33, 33, 35, 41, 47]\n | |\n left right => window_size = 2, maxi = 5\n\n\nWe can see that maxi =5, now the elements required to get changed is n-5 = 5.\n\n\n# Complexity\n- Time complexity:\nO(N * log(N))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\nO(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int left = 0;\n int ans = 1;\n int n = nums.size();\n int bigger = 1;\n for(int i=1;i<nums.size();i++) {\n if((nums[i]-nums[left]) <= (n-1) && nums[i]-nums[i-1] != 0) {\n bigger++;\n }\n int r = left;\n while(left <= i && nums[i]-nums[left] > (n-1)) {\n if(left != r && nums[left] != nums[left-1]) {\n bigger--;\n }\n left++;\n }\n ans = max(ans, bigger);\n }\n return n-ans;\n }\n};\n```\n\n## Pls upvote if you understand the solution. | 4 | 0 | ['C++'] | 0 |
minimum-number-of-operations-to-make-array-continuous | 🗓️ Daily LeetCoding Challenge October, Day 10 | daily-leetcoding-challenge-october-day-1-adyh | This problem is the Daily LeetCoding Challenge for October, Day 10. Feel free to share anything related to this problem here! You can ask questions, discuss wha | leetcode | OFFICIAL | 2023-10-10T00:00:06.335509+00:00 | 2023-10-10T00:00:06.335535+00:00 | 2,495 | false | This problem is the Daily LeetCoding Challenge for October, Day 10.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain these 2 approaches in the official solution</summary>
**Approach 1:** Binary Search
**Approach 2:** Sliding Window
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br> | 4 | 0 | [] | 16 |
minimum-number-of-operations-to-make-array-continuous | c++ silding Window | c-silding-window-by-solvedorerror-1zgg | Intution:-\n1.First i will sort the array, and make a new non repeating array in sorted form.\n2.From each value in "non-repeating-array" , I will try to find o | solvedORerror | NORMAL | 2022-10-26T18:16:22.639865+00:00 | 2022-10-26T18:16:22.639911+00:00 | 1,068 | false | **Intution:-**\n1.First i will sort the array, and make a new non repeating array in sorted form.\n2.From each value in "non-repeating-array" , I will try to find out maximum possible elements in continous array, if formed from that element.\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n vector<int> different;\n different.push_back(nums[0]);\n for(int i=1;i<n;i++){\n if(nums[i]!=nums[i-1]){\n different.push_back(nums[i]);\n }\n }\n int i=0;\n int m=different.size();\n int ans=0;\n for(int j=0;j<m;j++){\n if(different[j]<=different[i]+n-1){\n ans=max(ans,j-i+1);\n }else{\n i++;\n }\n }\n return n-ans;\n }\n};****\n``` | 4 | 0 | ['Sorting'] | 0 |
minimum-number-of-operations-to-make-array-continuous | C++ | Simple Binary Search | c-simple-binary-search-by-av1shek-byy1 | \nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n nums.res | av1shek | NORMAL | 2022-08-04T03:27:03.922132+00:00 | 2022-08-04T03:27:03.922172+00:00 | 566 | false | ```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n nums.resize(unique(nums.begin(), nums.end()) - nums.begin());\n \n int ans = INT_MAX;\n for(int i=0; i<nums.size(); i++)\n {\n int cntLess = i;\n int cntGreater = nums.end() - upper_bound(nums.begin(), nums.end(), nums[i] + n - 1);\n int inRange = nums.size() - (cntLess + cntGreater);\n ans = min(ans, n - inRange);\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['Binary Search', 'C', 'Binary Tree'] | 0 |
minimum-number-of-operations-to-make-array-continuous | C++ Solution, unique and queue. | c-solution-unique-and-queue-by-chejianch-05yy | \n### Idea\n- make a new array with all unique element and sort.\n- keep pushing an element into queue, and pop out the front element which is queue.back() - qu | chejianchao | NORMAL | 2021-09-18T16:00:33.644704+00:00 | 2021-09-18T16:04:22.704854+00:00 | 385 | false | \n### Idea\n- make a new array with all unique element and sort.\n- keep pushing an element into queue, and pop out the front element which is `queue.back() - queue.front() > n -1`, these elements in the queue are guaranteed that we don\'t need to change.\n- answer is n - queue.size();\n\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& _nums) {\n if(_nums.size() == 1) return 0;\n int n = _nums.size();\n map<int, int> cnt;\n for(auto x : _nums) ++cnt[x];\n vector<int> nums;\n for(auto it : cnt) nums.push_back(it.first); // sorted\n int ans = 0;\n queue<int> q;\n for(auto x : nums) {\n q.push(x);\n while(q.back() - q.front() > n - 1) q.pop();\n ans = max(ans, (int)q.size());\n }\n return n - ans;\n }\n};\n```\n | 4 | 1 | [] | 1 |
minimum-number-of-operations-to-make-array-continuous | Easy Solution | Binary Search Solution with Explanation | easy-solution-binary-search-solution-wit-8yrm | Intuition\n Describe your first thoughts on how to solve this problem. \n- There should have a range of numbers after replacing the numbers if needed. \n- Findi | KhaledAhmmedAnik | NORMAL | 2023-10-10T18:35:04.377242+00:00 | 2023-10-11T08:13:34.081305+00:00 | 37 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- There should have a **range** of numbers after replacing the numbers if needed. \n- Finding the end value will be easy if we can find the start value\n- The **end value** will be **(starting value + array length - 1)** to match with the condition of unique numbers.\n- For searching the minimum operation, we can think of taking at least 1 number from the given nums that will remain unchanged.\n- So, I am thinking of considering **each elements** of nums as the 1**st value** of **final nums** after replacing necessary number of elements, than tring to calculate if the **selected number is the 1st value**, then h**ow many number should have to be replace** to match the given conditions within (logN) time.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- **Sort nums** for make it ready for **binary search**\n\n- In an array pre-calculate the number of dublicats till index value, as we need to keep all unique numbers\n\n- Then, iterate through the nums, every iteration we consider the current value as the 1st value of final nums\n\n- For each 1st value, calculate how many replacement needed for finding the nums that match with the requirement. Final result will be the minimum of calculated value for each 1st value.\n- In the calculation part:\n 1. Add number of element before current element (because these need to replace as current value is considered as 1st value)\n 2. Find the last value index using binary search.\n 1. Last value calulation = (1st value + n) - 1; (from the condition of max min value diffrence)\n 2. Then can binary search with the last_value upper bound.\n 3. For the binary search used upper_bound c++ STL.\n 3. So, we have the index range of selected values for the final nums, that is current index to last_value index. But there might be case where there will be duplicate value in-side the range, so we need to repalce the extra duplicate value as well.\n 1. To get how many index we need to chagne, we can use the extra **duplication_calculate** array, that will be needChage[last_value_index]-needChange[current_value_index]\n 4. Then, add the number of elements after last_value index.\n\n \n\n****Bold****\n\n# Complexity\n- Time complexity: **O(nlogn)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: **O(n)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size(), maxValue, j, ans = INT_MAX, replaceNeeded;\n sort(nums.begin(),nums.end());\n vector<int> needChange(n,0);\n\n for(int i=1;i<n;i++){\n needChange[i] = needChange[i-1] + (int)(nums[i]==nums[i-1]);\n }\n\n for(int i=0;i<n;i++){\n maxValue = nums[i]+(n-1);\n j = (upper_bound(nums.begin()+i, nums.end(), maxValue) - nums.begin()) - 1;\n // replaceNeeded = before + (duplicate in between) + after\n replaceNeeded = i + (needChange[j] - needChange[i]) + ((n-1)-j);\n\n ans = min(ans, replaceNeeded);\n }\n\n return ans;\n }\n};\n``` | 3 | 0 | ['C++'] | 2 |
minimum-number-of-operations-to-make-array-continuous | 🔥💥Simple C++ Solution using Sliding Window 💥🔥 | simple-c-solution-using-sliding-window-b-n1jx | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem revolves around finding the minimum number of operations required to reduce | eknath_mali_002 | NORMAL | 2023-10-10T05:14:31.317616+00:00 | 2023-10-10T05:14:31.317665+00:00 | 199 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem revolves around finding the minimum number of operations required to reduce an array to a unique element by repeatedly choosing an element and reducing its value. The approach involves sorting the array, removing duplicates, and finding the longest subarray where the difference between elements is at most the original length of the array minus one.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. `Sort` the input array in ascending order.\n2. Remove `duplicates` by using a `set` data structure.\n3. Find the `longest subarray` where the difference between elements is at most the original length of the array minus one.\n4. Calculate the minimum number of operations by subtracting the length of this `longest subarray` from the original array length.\n# Complexity\n- Time complexity:$$O(n logn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int prev_len = nums.size();\n sort(nums.begin() , nums.end());\n set<int>s(nums.begin() , nums.end());\n nums.clear();\n nums.assign(s.begin() , s.end());\n int len = nums.size();\n int max_window =1;\n int i = 0, j = 0;\n\n while(j<len){\n if(nums[j] - nums[i] <= prev_len-1){\n max_window = max(max_window , j-i+1);\n j++;\n }\n else i++;\n }\n\n return prev_len- max_window;\n }\n};\n``` | 3 | 0 | ['Binary Search', 'Sliding Window', 'Ordered Set', 'C++'] | 0 |
minimum-number-of-operations-to-make-array-continuous | [C++] Sliding Window on the Sorted and Unique Array | c-sliding-window-on-the-sorted-and-uniqu-0f6r | Intuition\n Describe your first thoughts on how to solve this problem. \nFind the maximum window that meets the problem\'s conditions.\n\n# Approach\n Describe | pepe-the-frog | NORMAL | 2023-10-10T04:40:11.367257+00:00 | 2023-10-10T04:40:11.367284+00:00 | 1,510 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind the maximum window that meets the problem\'s conditions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* get the sorted and unique integers\n* slide the window within a valid range\n\n# Complexity\n- Time complexity: $$O(n * log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // time/space: O(nlogn)/O(n)\n int minOperations(vector<int>& nums) {\n // get the sorted and unique integers\n int n = nums.size();\n sort(nums.begin(), nums.end());\n int k = unique(nums.begin(), nums.end()) - nums.begin();\n \n // slide the window within a valid range\n int result = INT_MAX;\n for (int l = 0, r = 0; r < k; r++) {\n while ((l < r) && ((nums[l] + n - 1) < nums[r])) l++;\n result = min(result, n - (r - l + 1));\n }\n return result;\n }\n};\n``` | 3 | 0 | ['Sliding Window', 'Sorting', 'C++'] | 0 |
minimum-number-of-operations-to-make-array-continuous | C++ || Binary search || Explained | c-binary-search-explained-by-amol_2004-b0cl | \n# Approach\n Describe your approach to solving the problem. \n- sort the array and remove all the dublicate element\n- For every index do a binary search to g | amol_2004 | NORMAL | 2023-10-10T04:32:00.038877+00:00 | 2023-10-10T04:32:00.038905+00:00 | 235 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n- sort the array and remove all the dublicate element\n- For every index do a binary search to get the possible right end of the window and calculate the possible answer.\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n set<int> s;\n for(auto it : nums)\n s.insert(it);\n \n vector<int> v;\n for(auto it : s)\n v.push_back(it);\n int n = nums.size();\n\n int ans = INT_MAX;\n for(int i = 0; i < v.size(); i++){\n int left = i + 1, right = v.size() - 1;\n int ele = v[i] + n - 1;\n while(left <= right){\n int mid = left + (right - left)/2;\n if(v[mid] == ele){\n ans = min(ans, n - (mid - i + 1));\n break;\n }\n else if(v[mid] > ele)\n right = mid - 1;\n else\n left = mid + 1;\n }\n ans = min(ans, n - (left - i + 1) + 1);\n }\n\n return ans;\n }\n};\n```\n\n | 3 | 0 | ['Array', 'Binary Search', 'C++'] | 1 |
minimum-number-of-operations-to-make-array-continuous | Easyiest Solution | easyiest-solution-by-vaibhav0077-aicv | \nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n \n n = len(nums)\n arr = sorted(set(nums))\n\n j = 0\n | vaibhav0077 | NORMAL | 2023-10-10T04:09:08.292183+00:00 | 2023-10-10T04:09:08.292202+00:00 | 53 | false | ```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n \n n = len(nums)\n arr = sorted(set(nums))\n\n j = 0\n for item in arr:\n j += item - arr[j] > n-1\n\n return j + n - len(arr)\n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
minimum-number-of-operations-to-make-array-continuous | 💡Swift - Optimal Solution - Sliding Window | swift-optimal-solution-sliding-window-by-hbpv | Solution\nswift\nclass Solution {\n func minOperations(_ nums: [Int]) -> Int {\n // There is no point in using duplicated numbers since we\'re require | bernikovich | NORMAL | 2023-10-10T03:06:31.964937+00:00 | 2023-10-11T01:08:11.137001+00:00 | 138 | false | # Solution\n```swift\nclass Solution {\n func minOperations(_ nums: [Int]) -> Int {\n // There is no point in using duplicated numbers since we\'re required to\n // perform an operation on them anyway.\n let uniqueNums = Array(Set(nums)).sorted()\n let n = uniqueNums.count\n\n var result = 0\n var right = 0\n\n for left in 0..<n {\n // The difference between the remaining leftmost and rightmost elements\n // should not exceed the initial number of elements.\n while right < n && uniqueNums[right] - uniqueNums[left] < nums.count {\n right += 1\n }\n\n // `right - left` is the number of elements remaining in their original place.\n result = max(result, right - left)\n }\n\n return nums.count - result\n }\n}\n```\n\n# Complexity\n- Time: $$O(nlogn)$$\n- Space: $$O(n)$$ | 3 | 0 | ['Swift', 'Sliding Window'] | 0 |
minimum-number-of-operations-to-make-array-continuous | python3 Solution | python3-solution-by-motaharozzaman1996-jsa2 | \n\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n=len(nums)\n nums=sorted(set(nums))\n ans=sys.maxsize\n | Motaharozzaman1996 | NORMAL | 2023-10-10T02:58:33.184279+00:00 | 2023-10-10T02:58:33.184354+00:00 | 127 | false | \n```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n=len(nums)\n nums=sorted(set(nums))\n ans=sys.maxsize\n for i,s in enumerate(nums):\n e=s+n-1\n idx=bisect_right(nums,e)\n ans=min(ans,n-idx+i)\n return ans \n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
minimum-number-of-operations-to-make-array-continuous | Rust | 25ms | 6 lines | rust-25ms-6-lines-by-rbird111-zhz0 | Code\nrust\nimpl Solution {\n pub fn min_operations(mut nums: Vec<i32>) -> i32 {\n let n = nums.len() as i32;\n nums.sort_unstable();\n | RBird111 | NORMAL | 2023-10-10T01:41:52.901474+00:00 | 2023-10-10T01:41:52.901491+00:00 | 80 | false | # Code\n```rust\nimpl Solution {\n pub fn min_operations(mut nums: Vec<i32>) -> i32 {\n let n = nums.len() as i32;\n nums.sort_unstable();\n nums.dedup();\n nums.iter().enumerate().fold(n, |ops, (i, l)| {\n ops.min(n - (nums.partition_point(|&m| m < l + n) - i) as i32)\n })\n }\n}\n``` | 3 | 0 | ['Rust'] | 1 |
minimum-number-of-operations-to-make-array-continuous | Minimum Number of Operations to Make Array Continuous | minimum-number-of-operations-to-make-arr-niih | Code\n\nvar minOperations = function(nums) {\n const n = nums.length;\n const set = new Set(nums);\n const distinctNums = Array.from(set).sort((a, b) = | dhruvabhat | NORMAL | 2023-10-10T01:38:41.058724+00:00 | 2023-10-10T01:38:41.058743+00:00 | 317 | false | # Code\n```\nvar minOperations = function(nums) {\n const n = nums.length;\n const set = new Set(nums);\n const distinctNums = Array.from(set).sort((a, b) => a - b);\n const targetLen = distinctNums.length;\n\n let left = 0;\n let right = 0;\n let maxLen = 0;\n\n while (right < targetLen) {\n while (distinctNums[right] - distinctNums[left] > n - 1) {\n left++;\n }\n maxLen = Math.max(maxLen, right - left + 1);\n right++;\n }\n\n return n - maxLen;\n};\n\nconst nums = [8, 5, 9, 9, 8, 4];\nconsole.log(minOperations(nums)); // Output: 2\n``` | 3 | 0 | ['JavaScript'] | 0 |
minimum-number-of-operations-to-make-array-continuous | Python 3 binary search O(nlogn) simple solution | python-3-binary-search-onlogn-simple-sol-jvz2 | \nimport bisect\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n=len(nums)\n nums=list(set(nums))\n nums.sort()\n | saisanjith15 | NORMAL | 2022-05-01T09:58:31.365875+00:00 | 2022-05-01T09:58:31.365905+00:00 | 217 | false | ```\nimport bisect\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n=len(nums)\n nums=list(set(nums))\n nums.sort()\n minn=float(\'inf\')\n for i,val in enumerate(nums):\n index=bisect_right(nums,val+n-1)\n minn=min(minn,n-(index-i))\n return minn\n \n``` | 3 | 0 | ['Binary Search'] | 0 |
minimum-number-of-operations-to-make-array-continuous | C++ | SET | IMPLEMENTATION | c-set-implementation-by-chikzz-1pzh | \nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n \n //length of the initial array\n int len=nums.size();\n | chikzz | NORMAL | 2021-12-19T15:15:38.652885+00:00 | 2021-12-19T15:15:38.652928+00:00 | 475 | false | ```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n \n //length of the initial array\n int len=nums.size();\n \n //remove duplicate elements and sort them\n set<int>S;\n for(auto &x:nums)\n S.insert(x);\n \n vector<int>temp;\n for(auto &x:S)\n temp.push_back(x);\n \n \n int maxx=INT_MIN,e=0;\n //In the first loop we traverse the entire array(modified) and take that element\n //as the minimum element of the required array and count the no of elements \n //that are in the range of [element,element+len) \n //and so for each element we count the count of elements required in the array \n //which is present in modified array and take the maximum of such counts.\n for(int i=0;i<temp.size();i++)\n {\n while(e<temp.size()&&temp[e]<temp[i]+len)\n e++;\n \n maxx=max(maxx,e-i);\n }\n \n //the answer is the (length of the given array)-(maximum no of elements found in nums of any\n //such array that is being created in the above process.)\n return len-maxx;\n }\n};\n``` | 3 | 0 | ['Sorting', 'Ordered Set'] | 1 |
minimum-number-of-operations-to-make-array-continuous | C++, Easy to understand, well commented, Binary Search, Sorting | c-easy-to-understand-well-commented-bina-lkr8 | \n// Problem Link : https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/\nclass Solution {\npublic:\n // Binary Search\n / | prit_manvar | NORMAL | 2021-12-09T08:17:21.134963+00:00 | 2021-12-09T08:17:21.134996+00:00 | 377 | false | ```\n// Problem Link : https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/\nclass Solution {\npublic:\n // Binary Search\n // it will give index of target and if target is not present then it will give largest element which is smaller than target\n int bsearch(vector<int>& nums, int target){\n int l = 0, h = nums.size()-1;\n \n while(l <= h){\n int m = l + (h-l)/2;\n \n if(target == nums[m])\n return m;\n else if(target < nums[m])\n h = m-1;\n else\n l = m+1;\n }\n return h;\n }\n int minOperations(vector<int>& nums) {\n // To remove duplicates\n unordered_set<int> st;\n int duplicates = 0;\n for(int i = 0; i < nums.size(); i++){\n if(st.count(nums[i]) == 0){\n st.insert(nums[i]);\n }else{\n nums[i] = -1;\n duplicates++;\n }\n }\n int ans = nums.size();\n \n // sort an array\n sort(nums.begin(), nums.end());\n \n for(int i = duplicates; i < nums.size(); i++){\n int valid = nums[i]+nums.size()-1; // this will be largest valid number if we start from nums[i]\n \n int indx = bsearch(nums,valid); // index of largest valid number\n int valid_numbers = indx-i+1; // numbers which are valid\n ans = min(ans,(int)nums.size()-valid_numbers); // substract valid numbers from total numbers to get valid numbers.\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Binary Search', 'Sorting'] | 0 |
minimum-number-of-operations-to-make-array-continuous | Using Ordered Set | C++ | O(nlogn) | using-ordered-set-c-onlogn-by-narayanban-3frk | The time complexity is high but easy to understand.\nEvery time we just go to every element and find how many elements we need to change to make the array conti | narayanbansal35 | NORMAL | 2021-10-08T18:45:53.143903+00:00 | 2021-10-08T18:46:45.812154+00:00 | 318 | false | The time complexity is high but easy to understand.\nEvery time we just go to every element and find how many elements we need to change to make the array contiguous which can easily be achived using the ordered_set \n```\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\n#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>\n \nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size();\n ordered_set st;\n \n for (int i = 0;i < n;i++){\n st.insert(nums[i]);\n }\n //This is the minimum number of change we have to made\n int mst = n - st.size();\n int ans = INT_MAX;\n for (auto val : st){\n\t\t// Finding how many element we have to change which are less then val and which are greater than the (val+n-1) \n int val2 = n - st.order_of_key(val+n) + st.order_of_key(val);\n int mx = max(mst, val2);\n ans = min(ans, mx);\n }\n return ans;\n }\n};\n```\nUpvote if you like | 3 | 0 | ['C', 'Ordered Set'] | 0 |
minimum-number-of-operations-to-make-array-continuous | SLIDING WINDOW | sliding-window-by-mk_kr_24-qs0g | \nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n set<int> s;\n for(int i: nums)\n s.insert(i);\n int l1 | mk_kr_24 | NORMAL | 2021-09-25T11:22:56.283744+00:00 | 2021-09-25T11:22:56.283774+00:00 | 176 | false | ```\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n set<int> s;\n for(int i: nums)\n s.insert(i);\n int l1= nums.size();\n int ans= l1;\n int l2= s.size();\n set<int>:: iterator itr1;\n itr1= s.begin();\n int i= 0, j= 0;\n for(auto itr= s.begin(); itr!= s.end(); ++itr, ++i)\n {\n while(itr1!= s.end()&&*itr1<=*itr+l1-1)\n {\n ++itr1;\n ++j;\n }\n ans= min(ans, l1-j+i);\n }\n return ans;\n }\n};\n``` | 3 | 0 | [] | 0 |
minimum-number-of-operations-to-make-array-continuous | Java Set+Sorting+Binary Search | java-setsortingbinary-search-by-yashoda_-c6fx | \nclass Solution {\n public int minOperations(int[] nums) {\n //get unique elemets\n Set<Integer> set=new HashSet();\n for(int i:nums)\n | yashoda_agrawal | NORMAL | 2021-09-19T06:02:06.873778+00:00 | 2021-09-19T06:02:06.873824+00:00 | 175 | false | ```\nclass Solution {\n public int minOperations(int[] nums) {\n //get unique elemets\n Set<Integer> set=new HashSet();\n for(int i:nums)\n {\n set.add(i);\n }\n int[] res=new int[set.size()];\n int in=0;\n for(int i:set)\n {\n res[in++]=i;\n }\n //sort the unique elements\n Arrays.sort(res);\n int ans=Integer.MAX_VALUE;\n for(int i=0;i<res.length;i++)\n {\n //find the target based on the original array\n int e=res[i]+nums.length-1;\n //binary search for target\n int index=bs(res, i+1, e);\n ans=Math.min(ans, nums.length-(index-i+1));\n \n }\n return ans;\n }\n \n public int bs(int[] nums, int start, int target)\n {\n int high=nums.length-1;\n while(start<=high)\n {\n int mid=start+(high-start)/2;\n if(nums[mid]==target)\n return mid;\n if(nums[mid]<target)\n {\n start=mid+1;\n } else {\n high=mid-1;\n }\n }\n return start-1;\n }\n}\n``` | 3 | 0 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.