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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
the-k-strongest-values-in-an-array | [Java] Without PriorityQueue, it can be faster. 100%, 100%! | java-without-priorityqueue-it-can-be-fas-8na6 | \nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr); \n int[] result = new int [k];\n i | lincanshu | NORMAL | 2020-06-07T07:12:08.732116+00:00 | 2020-06-08T02:30:31.770696+00:00 | 128 | false | ```\nclass Solution {\n public int[] getStrongest(int[] arr, int k) {\n Arrays.sort(arr); \n int[] result = new int [k];\n int lo = 0, hi = arr.length - 1;\n int m = arr[hi / 2];\n for (int i = 0; i < k; ++ i) {\n int diff = Math.abs(arr[lo] - m) - Math.abs(arr[hi] - m);\n if (diff <= 0) {\n result[i] = arr[hi -- ];\n } else {\n result[i] = arr[lo ++];\n }\n }\n return result;\n }\n}\n``` | 1 | 1 | ['Java'] | 1 |
the-k-strongest-values-in-an-array | [C++] Using pairs and custom comparator | c-using-pairs-and-custom-comparator-by-s-44st | Pls upvote if you find this helpful :)\nThe basic idea is to first get the array sorted and find the median .After getting median we store the absolute differe | shubhambhatt__ | NORMAL | 2020-06-07T06:48:59.324480+00:00 | 2020-06-07T06:48:59.324529+00:00 | 128 | false | ***Pls upvote if you find this helpful :)***\nThe basic idea is to first get the array sorted and find the median .After getting median we store the absolute difference of the array values and median and the value itself in an array of pairs.And then we define our custom comparator for the purpose.\nAt last we find the first k values from the sorted array of pairs .Remember we have stored pairs in the second array(**answer**).So while returning the desired array(**answer1**)store the second value of pair from answer.\n```\nclass Solution {\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(),arr.end());\n vector<int>answer1;\n int m=arr.size();\n int median=arr[(m-1)/2];\n vector<pair<int,int>> answer;\n for(auto i:arr){\n answer.push_back(make_pair(abs(i-median),i));\n }\n sort(answer.begin(),answer.end(),[]( pair<int,int>a,pair<int,int> b){\n return (a.first>b.first)||(a.first==b.first&&a.second>b.second);\n });\n for(int i=0;i<k;i++) answer1.push_back(answer[i].second);\n return answer1;\n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
the-k-strongest-values-in-an-array | C++ Simplest solution | Two pointer | Sorting | c-simplest-solution-two-pointer-sorting-8v58n | \nvector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(), arr.end());\n int len = arr.size();\n int median = arr[(len-1)/2] | Atyant | NORMAL | 2020-06-07T06:31:05.508228+00:00 | 2020-06-07T06:49:19.887056+00:00 | 83 | false | ```\nvector<int> getStrongest(vector<int>& arr, int k) {\n sort(arr.begin(), arr.end());\n int len = arr.size();\n int median = arr[(len-1)/2];\n vector<int> ans;\n int li = 0, ri = len-1;\n while(ans.size()<k && li<=ri){\n if(abs(arr[ri]-median)>=abs(arr[li]-median)) {\n ans.push_back(arr[ri]);\n ri--;\n }\n else{\n ans.push_back(arr[li]);\n li++;\n }\n }\n return ans;\n }\n```\n\nLogic: Strongest element will be either side of shortest array (beacuse absolute difference will be maximum there)\n\nComment if you want Video Explaination for solution.\nI hope it helps! | 1 | 0 | ['Two Pointers', 'C', 'Sorting', 'C++'] | 0 |
the-k-strongest-values-in-an-array | [Python] 3 Solutions: Sort, Heap, Two-Pointer | python-3-solutions-sort-heap-two-pointer-lzi3 | Double Sort\npython\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n m = arr[((len(arr) - 1) // 2 | ztonege | NORMAL | 2020-06-07T05:33:15.156107+00:00 | 2020-06-07T05:33:15.156141+00:00 | 37 | false | **Double Sort**\n```python\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n m = arr[((len(arr) - 1) // 2)]\n return sorted(arr, key = lambda x: (abs(x - m), x), reverse = True)[:k]\n```\n\n**Heap**\n```python\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n m, h, result = arr[((len(arr) - 1) // 2)], [(-abs(a-m), -a) for a in arr], []\n heapq.heapify(h)\n for i in range(k):\n result.append(-heapq.heappop(h)[1])\n return result\n```\n\n**Two-Pointer**\n```python\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n m, result = arr[((len(arr) - 1) // 2)], []\n left, right = 0, len(arr)-1\n while len(result) < k:\n if abs(arr[left] - m) > abs(arr[right] - m):\n result.append(arr[left])\n left += 1\n else:\n result.append(arr[right])\n right -= 1\n return result\n``` | 1 | 0 | [] | 0 |
the-k-strongest-values-in-an-array | huh? TLE when I originally submitted nlogk solution in contest, which now passes and beats 100% | huh-tle-when-i-originally-submitted-nlog-9ejl | I posted below O(nlogk) solution during contest and it gave me "Time Limit Exceeded". Now after looking at all the solutions here which are also nlogk, I resubm | cham_ | NORMAL | 2020-06-07T05:29:48.440918+00:00 | 2020-06-07T07:07:42.274233+00:00 | 50 | false | I posted below O(nlogk) solution during contest and it gave me "Time Limit Exceeded". Now after looking at all the solutions here which are also nlogk, I resubmitted the same code again and now it passes beating 100% submissions for memory and 50% submissions for time complexity. \n\nWhat does this even mean??\n\n\n```\nclass Solution {\n int median;\n struct compare {\n bool operator()(const pair<int, int> &x, const pair<int, int> &y) {\n if(x.second == y.second)\n return x.first > y.first;\n return x.second > y.second;\n } \n };\npublic:\n vector<int> getStrongest(vector<int>& arr, int k) {\n priority_queue<int, vector<int>> minMedian;\n int size = arr.size();\n int n = (size - 1)/2 + 1;\n for(int i = 0 ; i < arr.size(); ++i) {\n minMedian.push(arr[i]);\n if(minMedian.size() > n) {\n minMedian.pop();\n }\n }\n median = minMedian.top();\n priority_queue<pair<int, int>, vector<pair<int, int>>, compare> minHeap;\n for(int i = 0 ; i < arr.size(); ++i) {\n int temp = arr[i];\n arr[i] = abs(arr[i] - median);\n minHeap.push({temp, arr[i]});\n if(minHeap.size() > k) {\n minHeap.pop();\n }\n }\n int i = k - 1;\n vector<int> output(k);\n while(i >= 0 && !minHeap.empty()) {\n output[i] = minHeap.top().first;\n minHeap.pop();\n i--;\n }\n \n return output;\n }\n};\n``` | 1 | 0 | [] | 1 |
recover-the-original-array | [Python] Short solution, explained | python-short-solution-explained-by-dbabi-anke | Notice, that what we have in the end is sum array X and array X + 2k. It seems very familiar and you can use the greedy idea of 954. Array of Doubled Pairs, but | dbabichev | NORMAL | 2021-12-26T04:00:47.975306+00:00 | 2021-12-26T04:00:47.975339+00:00 | 4,281 | false | Notice, that what we have in the end is sum array `X` and array `X + 2k`. It seems very familiar and you can use the greedy idea of 954. Array of Doubled Pairs, but now pairs are not doubled but with constant difference. How to find difference? It can be one of `n-1` numbers: `a1 - a0, a2 - a0, ...`. Also we need to make sure that difference is positive and can be divided by `2`.\n\n#### Complexity\nTime complexity is `O(n^2)`, space is `O(n)`.\n\n#### Code\n```python\nclass Solution:\n def recoverArray(self, nums):\n def check(nums, k):\n cnt, ans = Counter(nums), []\n for num in nums:\n if cnt[num] == 0: continue\n if cnt[num + k] == 0: return False, []\n cnt[num] -= 1\n cnt[num + k] -= 1\n ans += [num + k//2]\n return True, ans\n \n nums = sorted(nums)\n n = len(nums)\n for i in range(1, n):\n k = nums[i] - nums[0]\n if k != 0 and k % 2 == 0:\n a, b = check(nums, k)\n if a: return b\n```\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!** | 100 | 4 | ['Greedy'] | 13 |
recover-the-original-array | [100%] [50ms] WITHOUT map | 100-50ms-without-map-by-lyronly-2klu | First sort the nums array, nums[0] belong to low array. \nTry every possible diff in array, and diff must be even. k = diff / 2;\nEach element in low array (v) | lyronly | NORMAL | 2021-12-26T05:21:26.089182+00:00 | 2021-12-26T07:43:20.374917+00:00 | 1,991 | false | First sort the nums array, nums[0] belong to low array. \nTry every possible diff in array, and diff must be even. k = diff / 2;\nEach element in low array (v) should have its equivalent in high arrray (v + k + k). \nMaintain a pointer for the last element in low array that haven\'t found its equalient in high array yet, \n1 If pointer is valid and next element\'s value is pointer\'s value + k + k, then next element is the in high array. pointer++;\n2 Otherwise next element is in low array.\n\n```\nclass Solution {\npublic:\n int n;\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n2 = nums.size();\n n = n2/2;\n int a = nums[0];\n vector<int> v1, v2, ans;\n v1.reserve(n);v2.reserve(n);\n for (int i = 1; i < n2; i++)\n {\n int k = nums[i] - a;\n if (k % 2 == 1 || k == 0 || nums[i] == nums[i - 1]) continue; \n v1.clear();v2.clear();\n v1.push_back(a);\n int x = 0;\n for (int j = 1; j < n2; j++)\n {\n if (x < v1.size() && (nums[j] == v1[x] + k)) {\n v2.push_back(nums[j]);\n x++;\n } else v1.push_back(nums[j]);\n \n if (v1.size() > n || v2.size() > n) break;\n }\n if (v1.size() != n || v2.size() != n) continue;\n for (int i = 0; i < n; i++) ans.push_back((v1[i] + v2[i]) / 2);\n return ans;\n }\n return ans; \n }\n};\n``` | 33 | 2 | ['Greedy', 'C'] | 10 |
recover-the-original-array | Try possible k | try-possible-k-by-votrubac-hz2u | The smallest element in nums must be in the lower array. If we sort the array, our k can be (nums[i] - nums[0]) / 2.\n\nFor each such k, we try to match all pai | votrubac | NORMAL | 2021-12-26T04:01:45.915125+00:00 | 2021-12-26T04:18:32.954991+00:00 | 3,864 | false | The smallest element in `nums` must be in the lower array. If we sort the array, our `k` can be `(nums[i] - nums[0]) / 2`.\n\nFor each such `k`, we try to match all pairs, going from smallest to larger and removing pairs. If we match all pairs, we return the original array.\n\n**C++**\n```cpp\nvector<int> recoverArray(vector<int>& nums) {\n multiset<int> s(begin(nums), end(nums));\n int start = *begin(s);\n for (auto it = next(begin(s)); it != end(s); ++it) {\n int k = (*it - start) / 2;\n if (k > 0 && start + 2 * k == *it) {\n vector<int> res;\n auto ss = s;\n while(!ss.empty()) {\n auto it_h = ss.find(*begin(ss) + 2 * k);\n if (it_h == end(ss))\n break;\n res.push_back(*begin(ss) + k);\n ss.erase(begin(ss));\n ss.erase(it_h);\n }\n if (ss.empty())\n return res;\n }\n }\n return {};\n}\n``` | 30 | 4 | [] | 16 |
recover-the-original-array | Java Clean | java-clean-by-rexue70-orse | from N = 1000, we know we can try something similar to O(n2)\nwe find out K is actually a limited number, it would be the difference between first element with | rexue70 | NORMAL | 2021-12-26T04:37:15.129006+00:00 | 2021-12-28T06:16:52.776431+00:00 | 1,559 | false | from N = 1000, we know we can try something similar to O(n2)\nwe find out K is actually a limited number, it would be the difference between first element with all the rest number, one by one, when we have this list of k, we can try them one by one.\n\nwhen we have a possible k to guess, we will see if both low (nums[i]) and high (nums[i] + 2 * k) exist, and we increase counter by 1 (here in code has use tmp array), if counter is N / 2 in the end, we will conclue that we find one possible answer.\n\n```\nclass Solution {\n public int[] recoverArray(int[] nums) {\n int N = nums.length;\n Arrays.sort(nums);\n List<Integer> diffList = new ArrayList<>();\n for (int i = 1; i < N; i++) {\n int diff = Math.abs(nums[i] - nums[0]);\n if (diff % 2 == 0 && diff > 0) diffList.add(diff / 2);\n }\n Map<Integer, Integer> map1 = new HashMap<>();\n for (int i = 0; i < N; i++)\n map1.put(nums[i], map1.getOrDefault(nums[i], 0) + 1);\n for (int diff : diffList) {\n Map<Integer, Integer> map = new HashMap<>(map1);\n List<Integer> tmp = new ArrayList<>();\n for (int i = 0; i < N; i++) {\n\t\t\t if (tmp.size() == N / 2) break;\n int low = nums[i];\n int high = low + 2 * diff;\n if (map.containsKey(low) && map.containsKey(high)) {\n tmp.add(low + diff);\n map.put(low, map.get(low) - 1); \n map.put(high, map.get(high) - 1);\n if (map.get(low) == 0) map.remove(low);\n if (map.get(high) == 0) map.remove(high);\n }\n }\n if (tmp.size() == N / 2) return tmp.stream().mapToInt(i -> i).toArray();\n }\n return null;\n }\n}\n``` | 21 | 1 | ['Java'] | 4 |
recover-the-original-array | Easy to Understand Explanation with C++ Code || Multiset TLE Why? | easy-to-understand-explanation-with-c-co-leq8 | Question Summary - There is an array arr. You created two different arrays, say Low and High. Low contains all the elements of arr but all the elements are decr | rupakk | NORMAL | 2021-12-26T05:29:33.740088+00:00 | 2022-01-02T06:04:23.807966+00:00 | 2,015 | false | Question Summary - There is an array arr. You created two different arrays, say Low and High. Low contains all the elements of arr but all the elements are decremented by a positive no k. Same as Low, High contains all the elements of arr but they are incremented by k. You are given an array which contains all the elements of Low and High array(with duplicates). You need to construct the original array.\n\nApproach:\n\nAs the size of given array was at max 10^3, we can construct a O(n^2) algo and it will do the job. \nNow first we sort the given array. \n\nIf we can get the value of k by any means then the original array can be reconstructed.\nHow?\nWe take all the element of given array in a multiset. Now the smallest element of multiset will always be in the form of X-k, where X is a element of our original array. \nNow since we have X, we can search X+k in our multiset and if it is present, we can remove these both elements and add X to the ans vector. Futher we continue the same algo until the size of multiset is greater than 0.\n\nNow how can we get k?\nSay the smallest element of the original array be Y. If we have sorted our array then the element at 0 index will be Y-k.\nNow if we can find Y+k in the given array, then by adding these values we can get 2*Y and thus we can also get value of k.\nSince Y+k can be any value of the array, we will iterate entire array and consider every index from 1 to n-1 as Y+k.\n\nNote: Some multiset solutions are giving TLE because some test cases were added recently. It all boils down to reducing number of operations. I reduced operations by passing multiset by reference and hence it is giving Accepted verdict.\n\nC++ Code:\n```\ntypedef long long ll;\ntypedef long double ld;\n#define mod 1000000007\n#define F first\n#define S second\n#define all(x) begin(x),end(x)\n\nclass Solution {\npublic:\n\tvector<int> canMakeIt(multiset<int>& st, int k) {\n\t\tif (k <= 0)\n\t\t\treturn { -1};\n\t\tmultiset<int> erased;\n\t\tvector<int> ans;\n\t\twhile (st.size() > 0) {\n\t\t\tauto it = st.begin();\n\t\t\tint val = *it;\n\t\t\tint org = val + k;\n\t\t\tst.erase(st.find(val));\n erased.insert(val);\n\t\t\tif (st.find(org + k) != st.end()) {\n\t\t\t\tans.push_back(org);\n\t\t\t\tst.erase(st.find(org + k));\n\t\t\t\terased.insert(org + k);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor(int x:erased)\n\t\t\t\t\tst.insert(x);\n\t\t\t\treturn { -1};\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\n\tvector<int> recoverArray(vector<int>& nums) {\n\t\tsort(all(nums));\n\t\tmultiset<int> st(all(nums));\n\t\tint smallest = nums[0];\n\t\tfor (int j = 1; j < nums.size(); ++j) {\n\t\t\tint addi = smallest + nums[j];\n\t\t\tif (addi % 2 == 0) {\n\t\t\t\tint org = addi / 2;\n\t\t\t\tint k = nums[j] - org;\n\t\t\t\tvector<int> ans = canMakeIt(st, k);\n\t\t\t\tif (ans[0] != -1)\n\t\t\t\t\treturn ans;\n\t\t\t}\n\t\t}\n\t\treturn { -1};\n\t}\n};\n```\nTIme complexity will be O(n^2logn) as I am using multiset.\nIf you have any doubts, you can ask in the comment section.\nIf you found this post helpful consider upvoting so that others can also undestand this question. | 20 | 2 | ['C'] | 5 |
recover-the-original-array | ✅ [Python] Simple O(N^2) Solution || Detailed Explanation || Beginner Friendly | python-simple-on2-solution-detailed-expl-98zd | PLEASE UPVOTE if you like \uD83D\uDE01 If you have any question, feel free to ask. \n\nThe time complexity is O(N^2)\n\n\nclass Solution(object):\n def recov | linfq | NORMAL | 2021-12-26T16:27:59.369331+00:00 | 2021-12-27T03:59:22.600744+00:00 | 790 | false | **PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n\n`The time complexity is O(N^2)`\n\n```\nclass Solution(object):\n def recoverArray(self, nums):\n nums.sort()\n mid = len(nums) // 2\n # All possible k are (nums[j] - nums[0]) // 2, otherwise there is no num that satisfies nums[0] + k = num - k.\n # For nums is sorted, so that any 2 elements (x, y) in nums[1:j] cannot satisfy x + k = y - k.\n # In other words, for any x in nums[1:j], it needs to find y from nums[j + 1:] to satisfy x + k = y - k, but\n # unfortunately if j > mid, then len(nums[j + 1:]) < mid <= len(nums[1:j]), nums[j + 1:] are not enough.\n # The conclusion is j <= mid.\n\t\t# If you think it\u2019s not easy to understand why mid is enough, len(nums) can also work well\n\t\t# for j in range(1, len(nums)): \n for j in range(1, mid + 1): # O(N)\n if nums[j] - nums[0] > 0 and (nums[j] - nums[0]) % 2 == 0: # Note the problem described k is positive.\n k, counter, ans = (nums[j] - nums[0]) // 2, collections.Counter(nums), []\n # For each number in lower, we try to find the corresponding number from higher list.\n # Because nums is sorted, current n is always the current lowest num which can only come from lower\n # list, so we search the corresponding number of n which equals to n + 2 * k in the left\n # if it can not be found, change another k and continue to try.\n for n in nums: # check if n + 2 * k available as corresponding number in higher list of n\n if counter[n] == 0: # removed by previous num as its corresponding number in higher list\n continue\n if counter[n + 2 * k] == 0: # not found corresponding number in higher list\n break\n ans.append(n + k)\n counter[n] -= 1 # remove n\n counter[n + 2 * k] -= 1 # remove the corresponding number in higher list\n if len(ans) == mid:\n return ans\n``` | 17 | 1 | ['Python'] | 4 |
recover-the-original-array | C++ Very Easy Solution | c-very-easy-solution-by-rishabh_devbansh-h2tw | Approach\n\nThe idea is very simple, we know the minimum element in the permutation belongs to lower and maximum element belongs to higher. So , we\'ll push min | rishabh_devbanshi | NORMAL | 2021-12-26T10:21:12.871675+00:00 | 2021-12-26T12:56:48.684679+00:00 | 1,375 | false | ## Approach\n\nThe idea is very simple, we know the minimum element in the permutation belongs to lower and maximum element belongs to higher. So , we\'ll push minimum element in our ans array, then for each remaining element we\'ll try it to make first element of b and find k as\n\n\t\t\t\t\t\t\t\thigher[i] - lower[i] = arr[i] + k - (arr[i] - k) = 2*k\n\nusing this we can find possible values of k and check if we can form the array using this value of k.\n\n\n## Code\n\n```\nvector<int> recoverArray(vector<int>& nums) {\n \n\t\t//sorting the nums array\n sort(nums.begin(),nums.end());\n \n\t\t//we\'ll try every nums[i] as first element of higher array excpet nums[0]\n\t\t//as it is first element of lower\n for(int i=1;i<size(nums);i++)\n {\n vector<int> a;\n\t\t\t//pushing minimum element in lowest\n a.push_back(nums[0]);\n\t\t\t\n\t\t\t//calculating k after assuming nums[i] as first element of higher\n int k = nums[i] - a.back();\n \n\t\t\t//in case k is odd or k = 0, skip !\n if(k&1 || k == 0) continue;\n \n multiset<int> st(nums.begin(),nums.end());\n\t\t\t\n\t\t\t//delete used elements ,ie, nums[0] and nums[i]\n st.erase(st.find(a.back())) , st.erase(st.find(nums[i]));\n\t\t\t\n while(!st.empty())\n {\n // now current minimum value will be part of lower array, so pushing it to a\n\t\t\t\t// and deleting from multiset\n a.push_back(*st.begin());\n st.erase(st.begin());\n\t\t\t\t\n\t\t\t\t//now corresponding element in higher should be\n\t\t\t\t// last pushed element in lower + current k\n auto it = st.find(a.back() + k);\n\t\t\t\t\n\t\t\t\t//if we cann\'t find corresponding element in higher, we\'ll break the loop\n if(it == st.end()) break;\n\t\t\t\t\n\t\t\t\t//else delete it from multiset\n st.erase(it);\n }\n \n\t\t\t//now if our multiset is empty, ie , we have used all the elements then\n\t\t\t// it is clear that current value of k is the right choice\n\t\t\t// increment every value of lower by k/2 as higher[i] - lower[i] = 2*k\n\t\t\t// and we need to add k to lower[i] to make current array\n if(st.empty())\n {\n for(auto &val : a) val += k/2;\n // cout<<"\\n";\n return a;\n }\n \n }\n \n assert(false);\n \n }\n```\n\n**Time Complexity :** O(nlogn + n^2) | 16 | 1 | ['C'] | 3 |
recover-the-original-array | ✅Detailed Explanation || Binary Search || C++ , java | detailed-explanation-binary-search-c-jav-ylcc | Read the whole post and solution code to get clear understanding.\n\nQuestion explanation :\nAlice has array nums with n elements which is not given us. He choo | VishalSahu18 | NORMAL | 2021-12-26T18:53:40.716470+00:00 | 2023-03-05T09:11:13.362337+00:00 | 951 | false | *Read the whole post and solution code to get clear understanding.*\n\n**Question explanation :**\nAlice has array nums with n elements which is not given us. He chooses a **positive** integer **k** and created two new array of **same size** from the array he has\n1.) **lower array**\n2.) **higher array**\n\nfor each **i** to n:\n\nlower[i] = **nums[i] - k**; \nhigher[i] = **nums[i] + k**;\n\n* we neither given nums nor lower and higher array but \n* we are given an array of size 2n which is **combination** of elements of array **lower** and **higher**\n* here elements are arranged **randomly** we not know which element belongs which array (lower or higher)\n* we have to create an array Alice has.\n\n**Solution Explaination:**\n\n* For any valid k value we take lower[i] element and search for their higher[i] in nums\n* such that lower[i] = higher[i] + 2*k explain below\n\nI would like to explain you with example \n\n ```nums = [11, 6, 3, 4, 8, 7, 8, 7, 9, 8, 9, 10, 10, 2, 1, 9] n = 16```\n\n* since k is subtracting and adding from each nums[i] to create lower and higher array respectively.\n* k is same for all so the smallest value belongs to the lower array.\n\nfirstly we sort the given array so it becomes\n\t\t\t```[1, 2, 3, 4, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11]```\n\n***Little Maths Equations***\n```\t\t\t \t\t\t\nlower[i] = nums[i] - k\t\t (given in ques) \nnums[i] = lower[i] + k ....1) \t \n \nhigher[i] = nums[i] + k (given in ques)\nnums[i] = higher[i] - k ....2) \n\nusing 1 and 2\n lower[i] + k = higher[i] - k\n lower[i] + 2k = higher[i] \n \n``` \n ***higher[i] = lower[i] + 2k*** // so we can say that for every higher **there is a match** in lower or vice versa.\n \n we use above equation to find the match with every lower\n\n```\nalso for getting k value\nk = (higher[i] - lower[i])/2 (using above equation)\n```\n\n**Instead** of trying for every possible value we only need to try with **smallest** element to find a **valid k** value. (since **at** **least** one ans possible)\n\nSo lets **dry** run the above example \n ```nums[] = [1, 2, 3, 4, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11]```\n\n **smallest** = nums[0] = 1\n ``` \n k = (nums[i] - smallest)/2\n```\n for **checking** valid k \n ``` we check if k>0 && smallest + 2*k == nums[i] ```\n\nfrom **each** index i = 1 to n in nums:\n```\ni= 1:\n\n\t\t\t nums[i] = 2\n\t\t\t k = (2 - 1)/2;\n\t\t\t k = 0 (not valid); \n\n\ni = 2:\n\n\t\t\t nums[i] = 3\n\t\t\t k = (3-1)/2;\n\t\t\t k = 1 (valid)\n```\t\t \n **Now we try to find match of every lower with higher**\n\nfor **each** i = 0 to n in nums \n\n\t\ttarget = nums[i] + 2*k; // we search target value in nums (since for every lower there is a match in higher if we find valid k)\n\t\tans = [] \n\n\ti= 0:\n\t\tnums[i] =1\n\n\t\t\ttarget = 1 + 2*1 = 3 (present in nums[2] mark as visited)\n\t\t\tpush (nums[i] + k) in ans array\n\n\t\t\tnums[i] + k = 2\n\t\t\tans = [2]\n\n\ti= 1: \n\t\tnums[i] =2\n\n\t\t\ttarget = 2 + 2*1 = 4 (present in nums[3] mark as visited)\n\t\t\tpush (nums[i] + k) in ans array\n\n\t\t\tnums[i] + k =3\n\t\t\tans = [2,3]\n\n\ti= 2:\n\t\t nums[i] = 3 (already visited (matched with index 0) so skip it\n\n\ti= 3:\n\t\t\tnums[i] = 4 (already visited (matched with index 1) so skip it\n\n\ti= 4:\n\t\t\tnums[i] = 6\n\n\t\t\ttarget = 6 + 2*1 = 8 (present in nums[7] mark as visited)\n\t\t\tNote : here we find multiple 8 but we start from the leftmost.\n\n\t\t\tpush (nums[i] + k ) in ans array\n\n\t\t\tnums[i] + k = 7;\n\t\t\tans = [2,3,7]\n\n\ti= 5:\n\t\tnums[i] = 7\n\n\t\t\ttarget = 7 + 2*1 = 9 (present in nums[10] mark as visited)\n\t\t\tagain we find multiple value equals to target but start from the leftmost\n\n\t\t\tpush (nums[i] + k) in ans array\n\n\t\t\tnums[i] + k = 8\n\t\t\tans = [2,3,7,8]\n\n\ti= 6:\n\t\tnums[i] = 7\n\n\t\t\ttarget = 7 + 2*1 = 9 (present in nums[11] mark as visited)\n\t\t\tpush (nums[i] + k) in ans array\n\n\t\t\tnums[i] + k = 8\n\t\t\tans = [2,3,7,8,8]\n\n\ti=7:\n\t\t\tnums[i] = 8 (already visited (matched with index 4) so skip it\n\n\n\ti=8:\n\t\tnums[i] = 8\n\n\t\t\ttarget = 8 + 2*1 = 10 (present in nums[13] mark as visited)\n\t\t\tpush (nums[i] + k) in ans array\n\n\t\t\tnums[i] + k = 9\n\t\t\tans = [2,3,7,8,8,9]\n\n\ti=9:\n\t\tnums[i] = 8\n\n\t\t\ttarget = 8 + 2*1 = 10 (present in nums[14] mark as visited)\n\t\t\tpush (nums[i] + k which 9) in ans array\n\n\t\t\tnums[i] + k = 9\n\t\t\tans = [2,3,7,8,8,9,9]\n\n\ti=10:\n\t\t\tnums[i] = 9 (already visited (matched with index 5) so skip it\n\n\ti=11:\n\t\t\tnums[i] = 9 (already visited (matched with index 6) so skip it\n\n\ti=12:\n\t\tnums[i] = 9\n\n\t\t\ttarget = 9 + 2*1 = 11 (present in nums[15] mark as visited)\n\t\t\tpush (nums[i] + k) in ans array\n\n\t\t\tnums[i] + k = 10\n\t\t\tans = [2,3,7,8,8,9,9,10]\n\n\n\ti = 13,14 15 \n\t\t\t\t\talready visited so skip it\n\n\t\tans = [2,3,7,8,8,9,9,10] // bingo our ans array size equals to n/2 hence we found a valid array.\n\t\t\n\n***Solution Code :-***\n\n```\nclass Solution\n{\npublic:\n int search(vector<int> &nums, vector<bool> visit, int low, int high, int target)\n {\n int index = -1;\n\n while (low <= high)\n {\n\n int mid = (low + high) / 2;\n\n if (nums[mid] == target)\n {\n if (visit[mid])\n {\n low = mid + 1;\n }\n else\n {\n index = mid; \n high = mid - 1; \n }\n\n continue;\n }\n\n if (nums[mid] > target)\n high = mid - 1;\n else\n low = mid + 1;\n }\n\n return index;\n }\n\n vector<int> recoverArray(vector<int> &nums)\n {\n\n int n = nums.size();\n sort(nums.begin(), nums.end());\n\n int smallest = nums[0];\n\n for (int i = 1; i < n; i++)\n {\n\n int k = (nums[i] - smallest) / 2; \n if (k <= 0 || smallest + 2 * k != nums[i]) \n continue;\n\n vector<bool> visit(n);\n vector<int> ans;\n\n for (int j = 0; j < n; j++)\n {\n\n if (visit[j]) \n continue;\n\n int target = nums[j] + 2 * k;\n\n int index = search(nums, visit, j + 1, n - 1, target);\n\n if (index == -1) \n break;\n\n visit[index] = true; \n ans.push_back(nums[j] + k); \n }\n\n if (ans.size() == n / 2)\n return ans;\n }\n\n return {};\n }\n};\n\n```\n\n```\n\nclass Solution {\n \n int search(int nums[],boolean visit[] ,int low,int high,int target){\n int index = -1;\n \n while(low <= high){\n int mid = (low + high)/2;\n if(nums[mid]==target){\n if(visit[mid]){\n low = mid +1;\n }\n else{\n index = mid; \n high = mid-1; \n }\n continue;\n }\n\n if(nums[mid] > target)\n high = mid-1;\n else\n low = mid +1;\n }\n return index;\n}\n \n public int[] recoverArray(int[]nums) {\n \n int n = nums.length;\n Arrays.sort(nums);\n \n int smallest = nums[0];\n \n for(int i =1;i<n;i++){\n \n int k = (nums[i] - smallest)/2; \n \n if(k<=0 || smallest + 2*k != nums[i]) \n continue;\n \n boolean visit[] = new boolean[n];\n int ans[] = new int[n/2]; \n int cnt = 0;\n for(int j=0;j<n;j++){\n \n if(visit[j]) \n continue;\n \n int target = nums[j] + 2*k; \n int index = search(nums,visit,j+1,n-1, target); \n if(index==-1)\n break;\n \n visit[index] = true; \n ans[cnt++] = nums[j] + k; \n \n }\n if(cnt==n/2) \n return ans;\n }\n \n return new int[0];\n }\n}\n\n```\n\n\n***Time Complexity : - O(n^2 logn)\n Space Complexity :- O(n) (for maintaining visited array)***\n\n ***If you Like this post please do upvote so other people can also take benefit of this.\n any doubt welcome in comment section.***\n | 13 | 0 | ['Binary Tree'] | 2 |
recover-the-original-array | [Python3] brute-force | python3-brute-force-by-ye15-o2kx | Please check out this commit for solutions of weely 273. \n\n\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n | ye15 | NORMAL | 2021-12-26T04:01:49.429901+00:00 | 2021-12-26T15:17:34.063389+00:00 | 867 | false | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/338b3e50d12cc0067b8b85e8e27c1b0c10fd91c6) for solutions of weely 273. \n\n```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n cnt = Counter(nums)\n for i in range(1, len(nums)): \n diff = nums[i] - nums[0]\n if diff and diff&1 == 0: \n ans = []\n freq = cnt.copy()\n for k, v in freq.items(): \n if v: \n if freq[k+diff] < v: break \n ans.extend([k+diff//2]*v)\n freq[k+diff] -= v\n else: return ans \n``` | 12 | 0 | ['Python3'] | 4 |
recover-the-original-array | [Java] Explained: check valid K with two pointers, 6ms beats 100% | java-explained-check-valid-k-with-two-po-429f | Let\'s assume that the original array was [x, y, z] (x <= y <= z), and after subtracting and adding k we\'ve got an array of pairs [x-k, x+k, y-k, y+k, z-k, z+k | bl2003 | NORMAL | 2021-12-26T06:25:37.330563+00:00 | 2021-12-26T23:46:04.813075+00:00 | 539 | false | Let\'s assume that the original array was `[x, y, z] (x <= y <= z)`, and after subtracting and adding `k` we\'ve got an array of pairs `[x-k, x+k, y-k, y+k, z-k, z+k]`. We can make the following observations:\n1. The smallest number `x` in the original array will produce the smallest number `x - k` in the generated array.\n2. All generated pairs will have the same fixed difference: `(x+k) - (x-k) = x + k - x + k = 2 * k`. \n3. This difference `2 * k` must be even and positive (because `k` is positive).\n4. Sequential numbers in the original array `x < y` generate 2 pairs in one of the following sorted orders: `[x-k, x+k, y-k, y+k]` or `[x-k, y-k, x+k, y+k]`, because `x-k < y-k` and `x+k < y+k`\n5. Thus, we can sort the array and use a sliding window of fixed difference = `2 * k` with `i` = index of the lower element and `j` = index of the higher element of the pair, both of them are strictly increasing.\n5. Introduce `visited` array to ensure that each number is processed only once.\n ```java\nclass Solution {\n public int[] recoverArray(int[] nums) {\n Arrays.sort(nums);\n int[] res = new int[nums.length / 2];\n int prev = 0; // used to process each diff of 2*k only once\n // try finding a pair element x+2*k for the smallest one x\n for (int i = 1; i < nums.length; i++) {\n int diff = nums[i] - nums[0]; // 2*k, must be positive and even\n if (diff != prev && diff > 0 && diff % 2 == 0 && check(nums, i, diff / 2, res)) break;\n prev = diff;\n }\n return res;\n }\n \n\t // j points to the higher element of the pair\n private boolean check(int[] nums, int j, int k, int[] res) {\n int idx = 0;\n boolean[] visited = new boolean[nums.length];\n // i points to the lower element of the pair\n for (int i = 0; i < nums.length; i++) {\n if (visited[i]) continue;\n visited[i] = true;\n int target = nums[i] + 2 * k;\n // find the target = the higher element of the pair\n while (j < nums.length && (nums[j] < target || (nums[j] == target && visited[j]))) j++;\n if (j == nums.length || nums[j] != target) return false;\n visited[j] = true;\n // both elements of the pair are confirmed, update the result\n res[idx++] = nums[i] + k;\n }\n return true;\n }\n}\n```\nSimilar problems:\n[954. Array of Doubled Pairs](https://leetcode.com/problems/array-of-doubled-pairs/)\n[2007. Find Original Array From Doubled Array](https://leetcode.com/problems/find-original-array-from-doubled-array/)\n\n**PLEASE UPVOTE if you liked this post. THANKS!** | 9 | 0 | ['Java'] | 1 |
recover-the-original-array | Beats 100% on runtime [EXPLAINED] | beats-100-on-runtime-explained-by-r9n-3st2 | Intuition\nUnderstanding how the original array can be derived from the modified arrays, where each element has been adjusted by a positive integer k. Since we | r9n | NORMAL | 2024-11-04T05:55:53.355349+00:00 | 2024-11-04T05:55:53.355383+00:00 | 83 | false | # Intuition\nUnderstanding how the original array can be derived from the modified arrays, where each element has been adjusted by a positive integer k. Since we know how the modified values relate to the original ones, we can reverse-engineer the original values.\n\n# Approach\nSort the given array, iterate through possible values of k by checking the difference between elements, and use a frequency map to match elements back to the original array while ensuring all pairs are valid.\n\n# Complexity\n- Time complexity:\nThe overall time complexity is O(n log \u2061n) due to sorting the array, where \uD835\uDC5B is the length of the input array. Each subsequent operation with the frequency map takes linear time.\n\n- Space complexity:\nThe space complexity is O(n) for storing the frequency map and the recovered array, as we may need to hold up to n/2 elements.\n\n# Code\n```csharp []\npublic class Solution {\n public int[] RecoverArray(int[] nums) {\n Array.Sort(nums);\n int n = nums.Length;\n\n for (int i = 1; i < n; i++) {\n // Calculate potential k\n int k = (nums[i] - nums[0]) % 2 == 1 ? -1 : (nums[i] - nums[0]) / 2;\n if (k <= 0) continue;\n\n var freqMap = new Dictionary<int, int>();\n var recoveredArray = new List<int>();\n\n foreach (var num in nums) {\n if (freqMap.TryGetValue(num, out int count) && count > 0) {\n recoveredArray.Add(num - k);\n freqMap[num]--;\n if (freqMap[num] == 0) {\n freqMap.Remove(num);\n }\n } else {\n freqMap[num + 2 * k] = freqMap.GetValueOrDefault(num + 2 * k, 0) + 1;\n }\n }\n\n if (recoveredArray.Count == n / 2 && freqMap.Count == 0) {\n return recoveredArray.ToArray();\n }\n }\n\n return Array.Empty<int>(); // Return an empty array if no valid solution is found\n }\n}\n\n``` | 7 | 0 | ['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'Enumeration', 'C#'] | 0 |
recover-the-original-array | O(N^2) Time solution without hashMap | on2-time-solution-without-hashmap-by-nik-5f8y | The idea is similar to most of the Solutions on Discuss page, Only difference is function used to find the original array given a value of k.\nInstead of using | nikhilmishra1211 | NORMAL | 2021-12-29T15:26:04.003437+00:00 | 2021-12-29T15:26:04.003480+00:00 | 506 | false | The idea is similar to most of the Solutions on Discuss page, Only difference is function used to find the original array given a value of k.\nInstead of using a Hashmap or multiset. This solution uses to 2-pointer approch which is guaranteed O(N) time, getting rid of hash colliosions in case of HashMap.\n\n```\n\nclass Solution {\npublic:\n \n vector<int> recoverArray(vector<int>& a) {\n sort(a.begin(), a.end());\n int n = a.size();\n for(int i = 1; i < n; i++) {\n \n int dif = a[i] - a[0];\n if(!dif || dif&1)\n continue;\n int k = dif/2;\n \n vector<int> resultArray = getResultArray(a, n, k);\n if(resultArray.size() == n/2)\n return resultArray;\n }\n \n return {};\n }\n \n vector<int> getResultArray(vector<int> &a, int n, int k) {\n \n int left = 0, right = 1;\n vector<bool> done(n);\n \n vector<int> resultArray;\n \n while(right < n) {\n if(done[left]) {\n left++;\n continue;\n }\n if(done[right]) {\n right++;\n continue;\n }\n int dif = a[right] - a[left];\n if(dif < 2*k) {\n right++;\n }\n else if(dif > 2*k) {\n left++;\n }\n else {\n done[left] = 1; done[right] = 1;\n resultArray.push_back(a[left]+k);\n left++;\n right++;\n }\n }\n \n return resultArray;\n }\n \n \n};\n\n``` | 6 | 0 | ['Two Pointers', 'C'] | 1 |
recover-the-original-array | C++ || Simple Maths || With Explanation | c-simple-maths-with-explanation-by-matic-zqvy | ```\n/ so array elements are of form\nA-K B-K C-K A+K B+K C+K but we dont know actual sequence\nsubstrate A-K from the whole so\n0 B- | Matic001 | NORMAL | 2021-12-28T10:00:33.651184+00:00 | 2021-12-28T10:00:51.827044+00:00 | 603 | false | ```\n/* so array elements are of form\nA-K B-K C-K A+K B+K C+K but we dont know actual sequence\nsubstrate A-K from the whole so\n0 B-A C-A 2K B-A+2K C-A+2K\nso we calculate 2k that is the Doublediff and store in doublediff vector \n\nso we put all possibel value of double diff in doublediff vector\nwe iterate through every diff in double diff and try to form our ans\nfor diff :doubeldiff\n iteration 1: \n\t getsolution // Explantion of getsolution function\n\t\t\t\t\t{\n\t we store freq of every element in map\n\t we assume A-K as the first element in nums\n\t\t\t\t\t and we calculate wheteher a+k is present or not bu A-K+ diff where diff= 2k\n\t\t\t\t\t if\n\t\t\t\t\t {we find A+K we decrement its freq by 1\n\t\t\t\t\t and we calculate the A as A=A-K + diff/2;\n\t\t\t\t\t }\n\t\t\t\t\t else we return \n\t\t\t\t\t }\n\t\t\t\t\t if (ans.size()== nums.size()/2) return ans\n\t\t\t\t\t \n\titeration 2....\n\titeration 3..\n\t return empty array */\n\t\t\t\t\t \n\nclass Solution {\npublic:\n vector<int> getdoublediff(vector<int> nums)\n {\n int n= nums.size(),dif;\n vector<int> diff;\n \n for (int i=0;i<n;i++)\n {\n dif= nums[i]-nums[0];\n if (dif >0 && (dif %2==0)) diff.push_back(dif);\n }\n return diff;\n }\n vector<int> getsolution(vector<int> nums,int diff)\n {\n int n=nums.size();\n unordered_map<int,int> mp;\n vector<int> res;\n for (auto x: nums) mp[x]++;\n for (int i=0;i<n;i++)\n {\n if (mp.find(nums[i])!=mp.end())\n {\n mp[nums[i]]--;\n if (mp[nums[i]]==0) mp.erase(nums[i]);\n \n int val= nums[i]+diff;\n if (mp.find(val)==mp.end()) return res;\n else\n {\n mp[val]--;\n if (mp[val]==0) mp.erase(val);\n \n res.push_back(nums[i]+(diff)/2);\n }\n }\n }\n return res;\n }\n vector<int> recoverArray(vector<int>& nums) {\n \n int n= nums.size();\n sort(nums.begin(),nums.end());\n \n vector<int> doublediff= getdoublediff(nums);\n \n for (auto diff : doublediff)\n {\n vector<int> ans= getsolution(nums,diff);\n if (ans.size() == (n/2)) return ans;\n }\n vector<int>res;\n return res;\n \n }\n};\n\n// Plz upvote as it encourage me to write more detailed solution | 6 | 1 | [] | 0 |
recover-the-original-array | Java - find and check k fits or not || PriorityQueue | java-find-and-check-k-fits-or-not-priori-dapn | \nclass Solution {\n public int[] recoverArray(int[] nums) {\n \n \tint i,n=nums.length;\n \tint ans[]=new int[n/2];\n \tArrays.sort(nums);\n | pgthebigshot | NORMAL | 2021-12-26T04:01:55.979233+00:00 | 2021-12-26T04:16:35.592613+00:00 | 604 | false | ````\nclass Solution {\n public int[] recoverArray(int[] nums) {\n \n \tint i,n=nums.length;\n \tint ans[]=new int[n/2];\n \tArrays.sort(nums);\n \tPriorityQueue<Integer> pq=new PriorityQueue<>();\n \tfor(i=0;i<n;i++)\n \t\tpq.add(nums[i]);\n \tfor(i=1;i<n;i++)\n \t{\n \t\tPriorityQueue<Integer> pq1=new PriorityQueue<>(pq);\n \t\tint p=0;\n \t\tif((nums[0]+nums[i])%2==0)\n \t\t{\n \t\t\tint k=(nums[0]+nums[i])/2-nums[0];\n \t\t\tif(k==0)\n \t\t\t\tcontinue;\n \t\t\tint curr=pq1.poll();\n \t\t\twhile(pq1.contains((curr+k+k))) {\n \t\t\t\n \t\t\t\tpq1.remove(curr+k+k); \n\t\t\t\t\tans[p++]=curr+k;\n\t\t\t\t\tif(p==n/2)\n\t\t\t\t\t\tbreak;\n \t\t\t\tcurr=pq1.poll();\n \t\t\t}\n \t\t\tif(p==n/2)\n \t\t\t\tbreak;\n \t\t}\n \t}\n \treturn ans;\n }\n}\n````\n\nIf you guys get it then please upvote it:)) | 5 | 1 | ['Heap (Priority Queue)', 'Java'] | 2 |
recover-the-original-array | C++ Simple Solution using queue | c-simple-solution-using-queue-by-deepaks-m0q1 | Approach\nWe need to find K such that orginalArray[i] - k , orginalArray[i] + k both exist in the nums array but we have low and high arrays merged so we can sa | DeepakSharma72 | NORMAL | 2022-09-15T02:16:05.864505+00:00 | 2022-09-15T02:18:24.193315+00:00 | 389 | false | **Approach**\nWe need to find **K** such that orginalArray[i] - k , orginalArray[i] + k both exist in the *nums* array but we have *low* and *high* arrays merged so we can say *high[i] - 2k = low[i]*.Since *N* is just 1000 we can try to find elements in low and high arrays for all possible values of *K*.\n\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n for(int i=1;i<nums.size();i++)\n {\n if((nums[i] - nums[0])%2 == 0 && (nums[i] - nums[0]) > 0)\n {\n int k = nums[i]-nums[0];\n queue<int> q;\n q.push(nums[0]);\n vector<int> ans;\n for(int i=1;i<nums.size();i++)\n {\n if(!q.empty() && nums[i] - k == q.front())\n {\n ans.push_back(nums[i] - k/2);\n q.pop();\n }\n else\n {\n q.push(nums[i]);\n }\n }\n if(q.empty())\n {\n return ans;\n }\n }\n }\n return {};\n }\n};\n```\n\nsolve the given below simple version of this problem using queue:\n[https://leetcode.com/problems/find-original-array-from-doubled-array/](http://)\n | 4 | 0 | ['Queue', 'C', 'Sorting'] | 2 |
recover-the-original-array | simple c++ solution with explanation(n^2) | simple-c-solution-with-explanationn2-by-fskl5 | since it\'s given that atleast one valid answer is always possible , therefore for every index i of array there is one index j (i!=j) \nsuch that |array[ j | zombiedub | NORMAL | 2021-12-26T04:01:40.976288+00:00 | 2021-12-26T04:03:59.436961+00:00 | 345 | false | since it\'s given that atleast one valid answer is always possible , therefore for every index i of array there is one index j (i!=j) \nsuch that |array[ j ] - array[ i ] | == 2*k ,\nwhere k is the positive integer given in question.\n\nlets first sort the array to simplify things for us.\n\nnow let\'s say we start checking for all valid k\'s from first element ( 0th element index wise) . there can be as many as n-1 different k we can get \ni.e (arr[ 1 ] -arr [ 0 ] ), (arr[ 2 ] -arr [ 0 ] ) , (arr[ 3 ] -arr [ 0 ] ) ..................... (arr[ n-1 ] -arr [ 0 ] )\nat max this number can be 1000 as given in constraints.\n\nnow for each such even value of k we try to build our original array in O(n) time and if possible we will return that array as \nour answer . we will try to find our valid answer till we get one using these ( n-1 ) k\'s.\n\nTime - as there can be n-1 values of k and for each k to check valid ans o(n) time will require \n O(n^2)\n\t\t \n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n vector<int> ans;\n int n=nums.size();\n sort(nums.begin(),nums.end());\n for(int i=1;i<n;i++){\n int k=(nums[i]-nums[0])/2;\n if((nums[i]-nums[0])%2==1 || k<1)continue;\n\n bool possible=true;\n vector<bool> left(n,true);\n vector<int> temAns;\n int upper=i;\n \n for(int lower=0;lower<n;lower++){\n if(!left[lower])continue;\n if(upper==lower)upper++;\n while(upper<n && nums[upper]-nums[lower]<=2*k){\n if(nums[upper]-nums[lower]==2*k){\n temAns.push_back(nums[lower]+k);\n left[upper]=left[lower]=false;\n upper++;\n break;\n }\n upper++;\n }\n if(left[lower]){\n possible=false;\n break;\n }\n \n }\n if(possible){\n ans=temAns;\n break;\n }\n }\n return ans;\n }\n};\n```\n | 4 | 0 | ['C'] | 0 |
recover-the-original-array | C++ | O(N^2) | Identify all K and use the concept of "954. Array of Doubled Pairs" | c-on2-identify-all-k-and-use-the-concept-1sk2 | Logic:\nSimilar to "954. Array of Doubled Pairs" or "2007. Find Original Array From Doubled Array"\n\nStep 1: Identify the possible K\'s\nStep 2: Maintain a cou | kshitijSinha | NORMAL | 2022-01-16T13:58:32.635861+00:00 | 2022-01-16T13:58:32.635902+00:00 | 227 | false | Logic:\nSimilar to "[954. Array of Doubled Pairs](https://leetcode.com/problems/array-of-doubled-pairs/)" or "[2007. Find Original Array From Doubled Array](https://leetcode.com/problems/find-original-array-from-doubled-array/)"\n\nStep 1: Identify the possible K\'s\nStep 2: Maintain a counter of all values of array\nStep 3: Check if for given K, the array can be divided into two arrays(smaller and larger arrays)\nStep 3.1: for any certain K, if \'arr[i]\' is present in arr, then \'arr[i] + 2k\' should also be present in arr\n\nFor Step 1: \nWe need to sort the arr, for example for nums = [2,10,6,4,8,12], we should make nums = [2,4,6,8,10,12]\nNote 1: 2 and 10 can\'t be a pair, as 2 is minimum of array and hence we can never be able to find the pair for 6 or 8\nNote 2: For a valid K, nums[0] + 2K, which is 2 + 2K can either be 4,6, or 8 (which are nums[1] to nums[3])\nNote 3: We can easily ignore other values than 2(nums[0]) to identify K\n\nFor Step 3.1: We can use hashmap, multiset etc. One should try either of the following problems to understand the concept:\n* [954. Array of Doubled Pairs](https://leetcode.com/problems/array-of-doubled-pairs/)\n* [2007. Find Original Array From Doubled Array](https://leetcode.com/problems/find-original-array-from-doubled-array/)\n\n\n```\nclass Solution {\npublic:\n vector<int> findOriginalArray(vector<int>& arr, int k, unordered_map<int, int> counter) {\n vector<int> ans;\n vector<int> emptyArr;\n /*Step 3.1\n For each J, reduce the counter of arr[i] and arr[i] + 2*K by 1\n If for some arr[i], arr[i] + 2*K doesn\'t exist or it\'s count can\'t be reduced further, then the K is invalid\n */\n for(int i = 0; i < arr.size(); i++){\n if(counter[arr[i]] > 0){\n ans.push_back(arr[i] + k);\n counter[arr[i]]--;\n if(counter[arr[i] + 2*k] <= 0)\n return emptyArr;\n counter[arr[i] + 2*k]--;\n }\n }\n return ans;\n }\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n vector<int> ans;\n vector<int> listOfValidKs;\n /*Step 1: Find the list of valid K\'s*/\n for(int i = 1; i <= nums.size()/2; i++){\n if(nums[i] != nums[0] && (nums[i] - nums[0])%2 == 0){\n listOfValidKs.push_back((nums[i] - nums[0])/2);\n }\n }\n /*!Step 1*/\n /*Step 2: Maintain the counter*/\n unordered_map<int, int> counter;\n for(int i = 0; i < nums.size(); i++)\n counter[nums[i]]++;\n /*!Step 2*/\n /*Step 3: Validate each K*/\n for(int i = 0; i < listOfValidKs.size(); i++){\n ans = findOriginalArray(nums, listOfValidKs[i], counter);\n if(ans.size() > 0)\n return ans;\n }\n /*!Step 3*/\n ans.clear();\n return ans;\n }\n};\n```\n\nPlease share your feedbacks if any. | 3 | 0 | [] | 0 |
recover-the-original-array | Java : check all possible Ks | java-check-all-possible-ks-by-dimitr-fox4 | nums contains permutation of {a-k,a+k, b-k,b+k,...,z-k,z+k}\n- we can sort permutation array and find all possible K : (nums[i]-nums[0])/2, for i>=1 and even (n | dimitr | NORMAL | 2021-12-28T07:51:23.845936+00:00 | 2021-12-30T10:38:30.218773+00:00 | 170 | false | - **nums** contains permutation of **{a-k,a+k, b-k,b+k,...,z-k,z+k}**\n- we can sort permutation array and find all possible **K** : **(nums[i]-nums[0])/2**, for **i>=1** and **even (nums[i]-nums[0])**\n- we can map all occurrences of values into **value:count**\n- we have to iterate though all possible **K**s and check whether every **K** fits **nums** array\n- we can check by removing faced **nums** {**value**} and {**value +2 * k**} from map, if there is no corresponding {**value +2 * k**}, then **K** doesn\'t fit nums array\n```\n public int[] recoverArray(int[] nums) {\n int len = nums.length;\n int[] res = new int[len/2];\n Map<Integer,Integer> map = new HashMap<>();\n Set<Integer> setK = new HashSet<>();\n\n for(int n : nums)\n map.put(n, map.getOrDefault(n,0)+1);\n\n Arrays.sort(nums);\n\n for(int i=1;i<len;i++){\n int diff2k = nums[i]-nums[0];\n if(diff2k%2==0 && diff2k!=0)\n setK.add(diff2k/2);\n }\n\n for(int k : setK){\n int i=0,j=0;\n while(j<len/2){\n int low = nums[i];\n if(map.get(low)!=0) {\n int high = low + 2 * k;\n if(map.getOrDefault(high,0)!=0){\n map.put(low, map.get(low)-1);\n map.put(high, map.get(high)-1);\n res[j++] = low+k;\n }else{\n while(--j >= 0){\n map.put(res[j]+k, map.getOrDefault(res[j]+k, 0)+1);\n map.put(res[j]-k, map.getOrDefault(res[j]-k,0)+1);\n }\n break;\n }\n }\n i++;\n }\n if(j==len/2)\n return res;\n }\n return null;\n }\n``` | 3 | 0 | [] | 1 |
recover-the-original-array | JAVA | HashMap trying all possible k | java-hashmap-trying-all-possible-k-by-my-hd3q | After sorting, k can be (nums[i]-nums[0])/2 for any i in 1 ~ n, then use a HashMap to check if such k is valid.\n\n\nclass Solution {\n Map<Integer, Integer> | myih | NORMAL | 2021-12-26T04:01:09.973693+00:00 | 2021-12-26T04:01:55.416534+00:00 | 304 | false | After sorting, k can be (nums[i]-nums[0])/2 for any i in 1 ~ n, then use a HashMap<element, count> to check if such k is valid.\n\n```\nclass Solution {\n Map<Integer, Integer> countMap;\n public int[] recoverArray(int[] nums) {\n int n = nums.length/2;\n Arrays.sort(nums);\n countMap = new HashMap<>();\n for(int i=0; i<nums.length; i++) {\n countMap.put(nums[i], countMap.getOrDefault(nums[i], 0) + 1);\n }\n\n for(int i=1; i<=n; i++) {\n int k = (nums[i]-nums[0])/2;\n if(k == 0) continue; // k is positive\n int[] ret = helper(nums, k);\n if(ret != null) {\n return ret;\n }\n }\n\n return null;\n }\n \n int[] helper(int[] nums, int k) { // check if k is valid and generate return array\n Map<Integer, Integer> map = new HashMap<>(countMap);\n List<Integer> list = new ArrayList<>();\n for(int i:nums) {\n if(!map.containsKey(i)) continue;\n int counterPart = i + 2*k;\n if(!map.containsKey(counterPart)) return null;\n list.add(i+k);\n \n map.put(i, map.get(i) - 1);\n if(map.get(i) == 0) map.remove(i);\n map.put(counterPart, map.get(counterPart) - 1);\n if(map.get(counterPart) == 0) map.remove(counterPart);\n }\n int[] ret = new int[list.size()];\n for(int j=0; j<list.size(); j++) {\n ret[j] = list.get(j);\n }\n return ret;\n }\n} \n``` | 3 | 0 | [] | 0 |
recover-the-original-array | Simple Solution using multiset!!!⚡🔥💕💕 | simple-solution-using-multiset-by-yashpa-3pow | \n# Code\n\nclass Solution {\npublic:\n bool f(multiset<int>ms,int n,int k,vector<int>&ans){\n while(!ms.empty()){\n int smallest1=*ms.begi | yashpadiyar4 | NORMAL | 2023-05-24T18:15:03.205619+00:00 | 2023-05-24T18:15:03.205661+00:00 | 75 | false | \n# Code\n```\nclass Solution {\npublic:\n bool f(multiset<int>ms,int n,int k,vector<int>&ans){\n while(!ms.empty()){\n int smallest1=*ms.begin();\n int smallest2=smallest1+2*k;\n if(ms.find(smallest2)==ms.end())return false;\n ans.push_back(smallest1+k);\n ms.erase(ms.begin());\n auto it=ms.find(smallest2);\n ms.erase(it);\n }\n return true;\n }\n vector<int> recoverArray(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n multiset<int>ms(nums.begin(),nums.end());\n int lowest=nums[0];\n for(int i=1;i<n;i++){\n vector<int>ans;\n int highest=nums[i];\n if((highest-lowest)%2)continue;\n int k=(highest-lowest)/2;\n if(k && f(ms,n,k,ans))return ans;\n }\n return {};\n \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
recover-the-original-array | Java HashMap O(n^2) with comments and explaination | java-hashmap-on2-with-comments-and-expla-j7n2 | \n\nThe idea is smallest element in the array would always be part of lower array so we can fix that element and iterate through rest of array to find possible | pathey | NORMAL | 2022-10-11T16:29:48.433654+00:00 | 2022-10-11T16:29:48.433696+00:00 | 427 | false | \n\nThe idea is smallest element in the array would always be part of lower array so we can fix that element and iterate through rest of array to find possible k values, k would be equal to (nums[i]-nums[0])/2, now the next step is to verify if the taken k value is correct or not. For that we iterate over the array again and check if nums[j]+2*k or nums[j]-2*k element is present or not if none of this entries are present then k value we have taken is incorrect and we can move to new k value. If the element were present then we decrease frequency in hashmap so we can keep track if it was already checked or not.\n\n\n\n\n\n```\n\nclass Solution {\n public int[] recoverArray(int[] nums) {\n Arrays.sort(nums);\n HashMap<Integer,Integer> hm=new HashMap<>();\n for(int i=0;i<nums.length;i++){\n hm.put(nums[i],hm.getOrDefault(nums[i],0)+1); //Stroing frequency of elements in hashmap\n }\n int ans[]=new int[nums.length/2];\n for(int i=1;i<nums.length;i++){\n int k=(nums[i]-nums[0])/2; // Finding k values\n if(k==0)\n continue; //K should be positive only\n HashMap<Integer,Integer> hm2=new HashMap<>(hm); //Making copy of original hashmap\n int index=0;\n for(int j=0;j<nums.length;j++){\n if(hm2.get(nums[j])>=1){\n\t\t\t\t\t//If element was not previously checked\n if(hm2.getOrDefault(nums[j]+2*k,0)>=1){\n ans[index]=nums[j]+k; //Original element is nums[j]+k\n hm2.put(nums[j],hm2.get(nums[j])-1);\n hm2.put(nums[j]+2*k,hm2.get(nums[j]+2*k)-1); // Decreasing frequency of both nums[j]&&nums[j]+k\n }\n else if(hm2.getOrDefault(nums[j]-2*k,0)>=1){\n ans[index]=nums[j]-k; //Original element was nums[j]-k\n hm2.put(nums[j],hm2.get(nums[j])-1); \n hm2.put(nums[j]-2*k,hm2.get(nums[j]-2*k)-1); //Decreasing frequency of both nums[j]&&nums[j]+k\n \n }\n else{\n\t\t\t\t\t\t//Invalid k value \n break;\n }\n index++;\n }\n }\n if(index==nums.length/2)\n break; //Found the solution\n \n }\n return ans;\n }\n}\n\n``` | 2 | 0 | ['Java'] | 1 |
recover-the-original-array | Step By Step Explaination | step-by-step-explaination-by-bhavya0020-v6m6 | Logic\nThis Problem is all about finding K which is subtracted from original array (lower[i] = ar[i] - K) or added to the original array (higher[i] = ar[i] + K) | bhavya0020 | NORMAL | 2022-01-06T09:40:47.827658+00:00 | 2022-01-06T09:40:47.827707+00:00 | 194 | false | ## Logic\nThis Problem is all about finding K which is subtracted from original array (lower[i] = ar[i] - K) or added to the original array (higher[i] = ar[i] + K)\n\n## Code\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n = nums.size();\n// step - 1: arrange elements in ascending order\n sort(nums.begin(), nums.end());\n// Now, the smallest element will always belong to "lower" array\n// so, let it be lower[0]\n// now 2c = higher[0] - lower[0] \n// step - 2: find higher[0]\n for(int i = 1; i < n; i++){\n vector<int> v;\n v.push_back(nums[0]);\n// lets say ar[i] is highest[0] then\n// say k = 2c\n// 1. k should be even and not equal to 0\n// 2. for every element present in lower there must exist an element in higher\n// as lower[i] = higher[i] + k\n// Step-3: find k\n int k = nums[i] - v.back();\n// Step-4: check condition 1\n if(k & 1 || k == 0){\n continue;\n }\n // cout << k << " ";\n// Step-5: Check condition 2\n// Create a Multiset to check if the element exist or not in log n time\n multiset<int> s(nums.begin(), nums.end());\n// now we don\'t need the used elements so remove nums[0] and nums[i]\n s.erase(s.find(nums[0])), s.erase(s.find(nums[i]));\n// check if k is valid for all remaining elements of set\n while(!s.empty()){\n// get lowerest element\n int x = *(s.begin());\n// and push x in answer vector\n v.push_back(x); \n// remove x from se to avoid repeating elements\n s.erase(s.find(x));\n// find if x + k exist\n if(s.find(x+k) == s.end()){\n// if is doesn\'t exist then k is invalid\n break;\n }\n// if it exist then remove x + k\n s.erase(s.find(x + k));\n }\n if(s.empty()){\n// this means k is valid\n// original array = arr[i]\n// lower = arr[i] - c\n// k = 2c;\n for(int j = 0; j < v.size(); j++){\n v[j] += k/2;\n }\n return v;\n }\n }\n return {};\n }\n};\n```\nI wasn\'t able to solve the Question on my own at first, But then I read and understood all the discussions and finally created this solution which seems like the easiest possible solution to me. Hopefully, this solution can help you better understand and solve this problem. | 2 | 0 | ['C'] | 0 |
recover-the-original-array | Need Help , O(n^2) Sol getting tle | need-help-on2-sol-getting-tle-by-kingray-rhjn | I am checking for all the possible differences which may give answer in O(n) so expected time complexity should be O(n^2) but its getting tle , can someone poin | KingRayuga | NORMAL | 2021-12-26T04:08:36.959119+00:00 | 2021-12-26T04:08:36.959148+00:00 | 157 | false | I am checking for all the possible differences which may give answer in O(n) so expected time complexity should be O(n^2) but its getting tle , can someone point out the mistake\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n set<int>diff;\n int n = nums.size();\n for(int i=1;i<n;i++){\n diff.insert(abs(nums[i] - nums[0]));\n }\n vector<int>ans(n/2,0);\n sort(nums.begin(),nums.end());\n unordered_map<int,int>mp1;\n for(auto x:diff){\n if(x==0 || x&1){\n continue;\n }\n mp1.clear();\n int cnt = 0;\n for(int i=0;i<n;i++){\n mp1[nums[i]]++;\n }\n for(int i=0;i<n;i++){\n if(mp1[nums[i]] && mp1[nums[i] + x]){\n mp1[nums[i]]--;\n mp1[nums[i] + x]--;\n cnt++;\n }\n else if(mp1[nums[i]]){\n break;\n }\n }\n if(cnt==n/2){\n for(int i=0;i<n;i++){\n mp1[nums[i]]++;\n }\n cnt =0;\n for(int i=0;i<n;i++){\n if(mp1[nums[i]] && mp1[nums[i] + x]){\n mp1[nums[i]]--;\n mp1[nums[i] + x]--;\n ans[cnt] = nums[i] + x/2;\n cnt++;\n }\n } \n return ans;\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | [] | 1 |
recover-the-original-array | can't we use binary search on K ?? need help || why this fails | cant-we-use-binary-search-on-k-need-help-5d0j | i did binary search on value of k (0 to (maxelement-minelement)) \nif more elements r less than our current assumed k than high=k-1\nelse low=k+1\n\nANSWER:\nth | meayush912 | NORMAL | 2021-12-26T04:07:22.827177+00:00 | 2021-12-26T04:20:38.400277+00:00 | 156 | false | i did binary search on value of k (0 to (maxelement-minelement)) \nif more elements r less than our current assumed k than high=k-1\nelse low=k+1\n\nANSWER:\nthis fails because our function here is not monotonic in nature\ni thought maybe counting elements will be enough to steer in one direction but it doesn\'t gaurantee the solution in that case\n\n\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n unordered_map<int,vector<int>> ump;\n int n=nums.size();\n int low=nums[0],high=nums[0];\n for(int i=0;i<n;++i){\n ump[nums[i]].push_back(i);\n low=min(low,nums[i]);\n high=max(high,nums[i]);\n }\n vector<int> ans(n/2,0);\n \n high=(high-low);\n const int mini=low;\n low=0;\n \n while(low<=high){\n int k=low+((high-low)>>1);\n vector<int> ans;\n int count=n/2,lt=0,gt=0;\n vector<int> index(n,0);\n \n for(int i=0;i<n;++i){\n if(index[i]!=0)continue;\n if(nums[i]>k+mini)gt++;\n else lt++;\n \n if(ump.find(2*k+nums[i])!=ump.end()){\n bool s=0;\n for(int go:ump[2*k+nums[i]]){\n if(index[go]==0){\n s=1;\n index[go]+=1;\n break;\n }\n }\n if(s){\n ans.push_back(nums[i]+k);\n index[i]+=1;\n count--;\n }\n }\n \n }\n \n cout<<k<<" ";\n if(count==0){\n return ans;\n }else{\n if(lt>=gt){\n high=k-1;\n }else{\n low=k+1;\n }\n }\n \n }\n \n return nums;\n \n }\n};\n``` | 2 | 0 | [] | 2 |
recover-the-original-array | C++ solution, use brute-foce to try each k. | c-solution-use-brute-foce-to-try-each-k-k56f8 | \n\n1. sort the array\n2. because nums[0] is orginal[0] - k, then we can assume that nums[i] (i > 0) is original[0] + k, then k = (nums[i] - nums[0]) / 2\n3. tr | 11235813 | NORMAL | 2021-12-26T04:00:38.371735+00:00 | 2021-12-27T04:22:14.955516+00:00 | 379 | false | \n\n1. sort the array\n2. because nums[0] is orginal[0] - k, then we can assume that nums[i] (i > 0) is original[0] + k, then k = `(nums[i] - nums[0]) / 2`\n3. try all k to find the valid answer.\n \n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n multiset<int> ms;\n for(auto x : nums) ms.insert(x);\n for(int i = 1; i < nums.size(); i++) {\n int d = nums[i] - nums[0];\n if(d == 0 || d % 2) continue;\n int k = d / 2;\n auto t = ms;\n vector<int> ans;\n for(int i = 0; i < nums.size(); i++) {\n auto it = t.find(nums[i]);\n if(it == t.end()) continue;\n if(nums[i] != *t.begin()) break;\n auto it2 = t.find(nums[i] + 2 * k);\n if(it2 == t.end()) continue;\n t.erase(it);\n t.erase(it2);\n ans.push_back(nums[i] + k);\n }\n if(t.size() == 0) return ans;\n }\n return {};\n }\n};\n``` | 2 | 1 | [] | 3 |
recover-the-original-array | Just a runnable solution | just-a-runnable-solution-by-ssrlive-tp1c | Code\n\nimpl Solution {\n pub fn recover_array(nums: Vec<i32>) -> Vec<i32> {\n let mut nums = nums;\n nums.sort();\n let n = nums.len() | ssrlive | NORMAL | 2023-03-04T03:00:39.984971+00:00 | 2023-03-04T03:00:39.985004+00:00 | 12 | false | # Code\n```\nimpl Solution {\n pub fn recover_array(nums: Vec<i32>) -> Vec<i32> {\n let mut nums = nums;\n nums.sort();\n let n = nums.len() / 2;\n let a = nums[0];\n let mut v1 = Vec::with_capacity(n);\n let mut v2 = Vec::with_capacity(n);\n for i in 1..nums.len() {\n let k = nums[i] - a;\n if k % 2 == 1 || k == 0 || nums[i] == nums[i - 1] {\n continue;\n }\n v1.clear();\n v2.clear();\n v1.push(a);\n let mut x = 0;\n for &num in nums.iter().skip(1) {\n if x < v1.len() && num == v1[x] + k {\n v2.push(num);\n x += 1;\n } else {\n v1.push(num);\n }\n if v1.len() > n || v2.len() > n {\n break;\n }\n }\n if v1.len() != n || v2.len() != n {\n continue;\n }\n let mut ans = Vec::with_capacity(n);\n for i in 0..n {\n ans.push((v1[i] + v2[i]) / 2);\n }\n return ans;\n }\n vec![]\n }\n}\n``` | 1 | 0 | ['Rust'] | 0 |
recover-the-original-array | Simple C++ Solution | simple-c-solution-by-_mrvariable-wsgc | \nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n u | _MrVariable | NORMAL | 2022-08-03T05:15:34.571748+00:00 | 2022-08-03T05:15:34.571797+00:00 | 264 | false | ```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n unordered_map<int, int> mp, mpp;\n for(int i = 0; i < nums.size(); i++) {\n mp[nums[i]]++;\n mpp[nums[i]]++;\n }\n for(int i = 1; i < n; i++) {\n bool ok = true;\n int k = (nums[i]-nums[0])/2;\n if(k == 0) continue;\n vector<int> res;\n for(int j = 0; j < n; j++) {\n if(mpp[nums[j]] == 0) continue;\n if(mpp[nums[j]+2*k] == 0) {\n ok = false;\n break;\n }\n mpp[nums[j]]--, mpp[nums[j]+2*k]--;\n res.push_back(nums[j]+k);\n }\n mpp = mp;\n if(ok) return res;\n }\n return {};\n }\n};\n``` | 1 | 0 | ['Greedy', 'C'] | 0 |
recover-the-original-array | Go // O(n^2) // Trying all values of k // Full explanation with optimizations | go-on2-trying-all-values-of-k-full-expla-hcs6 | Approach:\nThe problem is twofold -- firstly, we need to find a valid value of k, and secondly, we need to pair terms up in a way such that each pair has a diff | cyclic | NORMAL | 2022-07-24T08:10:59.778946+00:00 | 2022-07-24T08:10:59.778976+00:00 | 85 | false | **Approach:**\nThe problem is twofold -- firstly, we need to find a valid value of `k`, and secondly, we need to pair terms up in a way such that each pair has a difference of `2k`.\n\nSo, how can we find values of `k` to test? Well, if a value of `k` is valid, two numbers in `nums` must have difference `2k`, since one has had `k` added and one has had `k` subtracted from the original number. There are up to `O(n^2)` differences, so this is going to take too long. The first observation we need to make is that there is always a lowest member of `nums`, let this be called `x`. Then `x + 2k` must be in the array, since `k > 0`. Therefore, we can check each of the other members of `nums` and find the corresponding `k` for each. This is only `O(n)` potential values of `k` to check, which is already a pretty good improvement.\n\nNext, we need to find whether a value of `k` works or not. To do this, we proceed iteratively. Remember when we considered the lowest value of `nums` earlier to find a value of `k`? Well, we\'re going to use the lowest member again. In particular, let\'s think about this by iterating through a sorted version of `nums`. Let the current element be `c`. If `c` has already been used because `c - 2k` is also in the array, we continue. Otherwise, we see if `c + 2k` is in the array and has not yet been used. If `c + 2k` is not in the array, then we know that this value of `k` does not work -- we know a corresponding `c - 2k` is not in the array, since it would otherwise have used up this `c` already. If `c + 2k` is in the array, then we mark both as used and move to the next value. If we can empty out the array without any problems, then this is a valid value of `k`.\n\nWell, now we want to efficiently check if a value is in an array. We could use binary search, but this adds an extra log factor for no good reason. What\'s a data structure that supports `O(1)` checking whether an integer is contained? Hash maps! In particular, in our hash map, we store each number in the array and how many of them there are (so `[1, 1, 3, 3]` would have a hash map `{1 -> 2, 3 -> 2}`. When we want to "use up" a number, we can just subtract 1 from the value stored in the hash map.\n\nTo make getting the final result easier, every time we identify a pair `c` and `c + 2k`, we add `c + k` to an array `res`, keeping track of where we are as we go. Once we finish processing all of `nums`, we will have completely filled in `res`, which can be directly returned.\n\n**Optimizations:**\n\nInstead of counting the number of times each number appears in `nums` on every iteration of the main loop, which would be inefficient, we do the counting once and create a "master copy" of the hash table, which is `origCounts` in my code. Afterward, we create another hash table `remaining`. On each iteration, we copy the values from `origCounts` into `remaining`, which represents the number of each number we still have left. By re-using `remaining` we are able to avoid having to allocate an extra hash table each iteration, which is expensive.\n\nOur further optimizations deal with limiting the number of times each loop runs, and determining when an iteration can be skipped.\n\nTo reduce the number of iterations the main loop runs, we cap it at `n / 2` rather than `n` where `n` is the length of `nums`. Why? Consider if the value of `k` was created by pairing up element `0` and element `n / 2 + 1`. There are then too many elements left below index `n / 2 + 1`, each of which needs to get paired up with an element above index `n / 2 + 1` or else their difference is less than `nums[n / 2 + 1] - nums[0]`. (This doesn\'t actually end up mattering because there is always one valid solution guaranteed.)\n\nWe also skip an `i` if `nums[i] == nums[i - 1]`, because this means `nums[i] - nums[0] == nums[i - 1] - nums[0]`, indicating that the corresponding value of `k` has been checked already, or `i == 1` and we would get that `k` is 0, which is not allowed. Likewise, if the difference between `nums[i]` and `nums[0]` is odd, then we cannot divide by `2` to find the corresponding value of `k`, so we bail out early of an iteration in this situation.\n\nFinally, we use the value of `k` as a flag to show whether pairing up numbers was successful. If we aren\'t able to pair up a number, then we set `k = -1`, and break out of the inner loop (which pairs up numbers). If we see that `k > 0` after the inner loop, then we know that we have found a valid `k` and can return the contents of `res`, otherwise, we know that this value of `k` failed and we need to test the next one.\n\n**Code:**\n```\nfunc recoverArray(nums []int) []int {\n sort.Ints(nums)\n n := len(nums)\n origCounts := make(map[int]int)\n for _, b := range nums {\n origCounts[b]++\n }\n remaining := make(map[int]int)\n res := make([]int, n / 2)\n \n for i := 1; i <= n / 2; i++ {\n if nums[i] == nums[i - 1] {\n continue\n }\n for a, b := range origCounts {\n remaining[a] = b\n }\n k := nums[i] - nums[0]\n if k % 2 == 1 {\n continue\n }\n k /= 2\n rp := 0\n for j := 0; j < n; j++ {\n if remaining[nums[j]] == 0 {\n continue\n }\n candidate := nums[j] + 2 * k\n if remaining[candidate] == 0 {\n k = -1\n break\n }\n res[rp] = nums[j] + k\n rp++\n remaining[nums[j]]--\n remaining[candidate]--\n }\n if k > 0 {\n break\n }\n }\n return res\n}\n```\n\nIf this helped you, please upvote! | 1 | 0 | ['Sorting', 'Go'] | 0 |
recover-the-original-array | Easy to understand Hashmap solution C++ | easy-to-understand-hashmap-solution-c-by-3718 | \nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n \n | bhavit123 | NORMAL | 2022-06-08T11:14:53.910575+00:00 | 2022-06-08T11:15:50.119263+00:00 | 424 | false | ```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n \n map<int,int> mp;\n for(int i=0;i<n;i++)\n mp[nums[i]]++;\n int l=0;\n int r=(n/2);\n int gap=0;\n while(l<r)\n {\n int dif=nums[r]-nums[l];\n if(dif%2!=0)\n {\n r--;\n continue;\n }\n map<int,int> temp=mp;\n for(auto it=temp.begin();it!=temp.end();it++)\n {\n if(temp[it->first]==0)\n continue;\n int ele1=it->first;\n int ele2=it->first+dif;\n if(temp.find(ele2)==temp.end())\n break;\n if(temp[ele1]>temp[ele2])\n break;\n else\n {\n temp[ele2]-=temp[ele1];\n temp[ele1]=0;\n }\n \n }\n bool is=true;\n for(auto it=temp.begin();it!=temp.end();it++)\n {\n if(temp[it->first]>0)\n {\n is=false;\n break;\n }\n \n }\n if(is && dif%2==0)\n {\n gap=dif;\n break;\n }\n r--;\n }\n \n vector<int> ans;\n for(auto it= mp.begin();it!=mp.end();it++)\n {\n if(mp[it->first]==0)\n continue;\n int sz=mp[it->first];\n int ele2=it->first+gap;\n for(int i=0;i<sz;i++)\n ans.push_back((it->first+ele2)/2);\n mp[ele2]-=mp[it->first];\n \n }\n \n return ans;\n \n \n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 1 |
recover-the-original-array | [26ms] || Compression solution || With Explanation|| C++ | 26ms-compression-solution-with-explanati-aus2 | \nclass Solution {\npublic:\n /*\n Hint:\n PLEASE AS A PREREQUISITE DO SOLVE: https://leetcode.com/problems/find-original-array-from-double | i_see_you | NORMAL | 2022-05-10T20:24:32.182158+00:00 | 2022-05-10T20:35:22.275271+00:00 | 160 | false | ```\nclass Solution {\npublic:\n /*\n Hint:\n PLEASE AS A PREREQUISITE DO SOLVE: https://leetcode.com/problems/find-original-array-from-doubled-array/ \n 1. There are basically 2 types of elements (X + k) or (X - k), and the problem is you don\'t know which is which or do you?\n 2. You can atleast say the smallest element in the array is a (X - k) type and the biggest element is a (X + k) type\n 3. And if you do know that the smallest element is (smallest - k) how can you use that?\n 4. If there is a (smallest - k) in the array that means there must be a (smallest + k) as well.\n 5. (smallest + k) - (smallest - k) = 2 * k\n 6. You can try with all other elements assuming that it is the (smallest + k) element, and guess a [possible_k]\n 7. Then you need to check if enough freq of [arr_val + possilbe_k] and [arr_val - possible_k] exists or not.\n 8. If you have already solved the prerequisite problem then the last part would be a piece of cake.\n \n Complexity:\n Time: O(N * logN + N * N)\n Space: O(N)\n */\n \n \n #define inf 0x3f3f3f3f\n #define all(a) a.begin(),a.end()\n #define Unique(a) sort(all(a)),a.erase(unique(all(a)),a.end())\n int org_frq[2001], frq[2001];\n unordered_map <int, int> val_to_id;\n vector<int> recoverArray(vector<int>& nums) {\n vector <int> compressed; compressed.push_back(-inf);\n for (int &val: nums) compressed.push_back(val); Unique(compressed);\n \n for (int i = 0; i < nums.size(); i++) {\n int index = lower_bound(compressed.begin(), compressed.end(), nums[i]) - compressed.begin();\n val_to_id[ nums[i] ] = index;\n nums[i] = index;\n org_frq[ index ]++;\n }\n \n vector <int> result;\n for (int arr_plus_k_id = 2; arr_plus_k_id < compressed.size(); arr_plus_k_id++) {\n int possible_k = (compressed[arr_plus_k_id] - compressed[1]);\n if (possible_k & 1) continue;\n possible_k /= 2;\n \n memcpy(frq, org_frq, sizeof org_frq);\n \n for (int plus_k_id = compressed.size() - 1; plus_k_id > 0; plus_k_id--) {\n if (frq[ plus_k_id ] == 0) continue;\n int minus_k_id = val_to_id[ compressed[plus_k_id] - 2 * possible_k ];\n if (minus_k_id == 0 || frq[ minus_k_id ] < frq[ plus_k_id ]) {\n result.clear();\n break;\n } \n \n frq[minus_k_id] -= frq[ plus_k_id ];\n for (int time = 0; time < frq[ plus_k_id ]; time++) result.push_back(compressed[plus_k_id] - possible_k);\n if (result.size() * 2 == nums.size()) break;\n }\n \n if (result.size()) break;\n }\n \n return result;\n }\n};\n``` | 1 | 0 | [] | 0 |
recover-the-original-array | Easy to understand | All Possible K | TC - O(k*n) | k is all possible k values | easy-to-understand-all-possible-k-tc-okn-v6wt | cpp\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n = nums.size(); \n if(n==2) return {(nums[0]+nums[1])/2}; | bgoel4132 | NORMAL | 2022-02-13T17:32:16.659284+00:00 | 2022-02-13T17:32:16.659332+00:00 | 220 | false | ```cpp\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n = nums.size(); \n if(n==2) return {(nums[0]+nums[1])/2};\n sort(nums.begin(), nums.end()); \n \n set<int> lower; \n for(int i = 1; i < n; i++) {\n if((nums[i]-nums[0])%2==0 and nums[i]!=nums[0]) lower.insert((nums[i]-nums[0])/2);\n }\n \n unordered_map<int, int> temp; \n for(int i = 0; i < n; i++) {\n temp[nums[i]]++;\n }\n \n unordered_map<int, int> check; \n for(auto &it : lower) {\n int low = it; \n \n vector<int> res; \n int size = 4;\n \n check = temp; \n \n res.push_back(nums[0]+low);\n check[nums[0]]--;\n check[nums[0]+2*low]--; \n \n \n res.push_back(nums[n-1]-low);\n check[nums[n-1]]--;\n \n if(!check[nums[n-1]-2*low]) continue; \n \n check[nums[n-1]-2*low]--;\n\n for(int i = 0; i < n; i++) {\n \n if(!check[nums[i]]) continue; \n \n if(check[nums[i]+2*low]) {\n res.push_back(nums[i]+low);\n check[nums[i]]--;\n check[nums[i]+2*low]--;\n size += 2;\n }\n\n else if(check[nums[i]-2*low]){\n res.push_back(nums[i]-low);\n check[nums[i]]--;\n check[nums[i]-2*low]--;\n size += 2;\n }\n\n } \n if(size == n) {\n return res; \n }\n }\n \n return {}; \n }\n};\n``` | 1 | 0 | ['C'] | 0 |
recover-the-original-array | Python Hash Table, sorting with detailed explanation, fast and efficient | python-hash-table-sorting-with-detailed-yv4s4 | \nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n counter = Counter(nums) # counter\n nums = sorted(counter) # sor | KC19920313 | NORMAL | 2022-02-02T18:00:59.833906+00:00 | 2022-02-02T18:01:49.543422+00:00 | 179 | false | ```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n counter = Counter(nums) # counter\n nums = sorted(counter) # sorted unique numbers\n\n hm = nums[-1] # the max number must be the max in the "higher" group\n for num in nums[:-1]: # test the corresponding number in the "lower" group. Not necessarily the min.\n k, m = divmod(hm - num, 2) # derived "k"\n if m: # there is a remainder, so they are partners\n continue\n ans = [] # to store the answer in case this will succeed\n cnt = counter.copy() # not sure if there is a better way than this\n for n in nums: # validation starts now. start with the smallest value\n c = cnt.pop(n) # its number\n if c == 0: # this value must have been fully considered in the "higher" group\n continue\n o = n + k # derived origin\n p = o + k # derived partner\n if cnt[p] >= c: # "p" should have enough number. If it has more, the remaining join "lower".\n cnt[p] -= c # reduce the count\n ans.extend([o] * c) # add them into "ans"\n else: # validation failed\n break\n else:\n return ans\n``` | 1 | 0 | ['Hash Table', 'Sorting'] | 0 |
recover-the-original-array | Java O(N^2)|Pruning Same differences | java-on2pruning-same-differences-by-yu-n-d7hv | We can see the range of the array is so small. The largest array length is just 1000. So we can guess the k by two different indices elements, and then use hash | yu-niang-niang | NORMAL | 2022-01-22T01:34:42.768326+00:00 | 2022-01-22T02:09:10.265929+00:00 | 227 | false | We can see the range of the array is so small. The largest array length is just **1000**. So we can guess the **k** by two different indices elements, and then use hash map to check the answer is right or not.\nSpecifically, the smallest element must be in the lower array,if it in the higher array, we can not find the smaller one put in the lower. If the second element is the same as previous, it means it must not be the right answer, because we checked the previous by same value.\nAnother noteworthy thing is the **k** is positive, so we cannot assign **k** to **0**.\n\n``` java\nclass Solution {\n public int[] recoverArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n // the first index element, must be one of the lower elements,so we just need to calculate all the difference between the first element with other\n for(int i = 1; i < n; i++){\n //If the seond element is the same as the previous, don\'t check it\n if(i>1&&nums[i]==nums[i-1])\n continue;\n\n int diff = nums[i]-nums[0];\n //If the difference between two elements is odd, it means we cannot find the answer here\n //k cannot be zero\n if(diff%2!=0 || diff == 0)\n continue;\n int[] tmp = findOriginalArray(nums,diff/2);\n if(tmp.length>0)\n return tmp;\n }\n return nums;\n }\n\n public int[] findOriginalArray(int[] changed,int t) {\n int n = changed.length;\n if(n%2!=0)\n return new int[0];\n\n int[] ans = new int[n/2];\n int i = 0;\n Map<Integer,Integer> map = new HashMap<>();\n for(int item:changed){\n //if we find the smaller elements saved ever before,delete it\n //otherwise, save it in the hash map\n if(!map.containsKey(item-2*t)){\n map.putIfAbsent(item,0);\n map.put(item,map.get(item)+1);\n }else if(map.get(item-2*t)==1){\n map.remove(item-2*t);\n ans[i++]=item-t;\n }else{\n map.put(item-2*t,map.get(item-2*t)-1);\n ans[i++]=item-t;\n }\n }\n\n return i==n/2&&map.isEmpty()?ans:new int[0];\n }\n}\n```\n | 1 | 0 | ['Java'] | 0 |
recover-the-original-array | Golang simple brute force solution | golang-simple-brute-force-solution-by-tj-tky7 | go\nfunc recoverArray(nums []int) []int {\n\tsort.Ints(nums)\n\tfor pairIndex0 := 1; pairIndex0 < len(nums); pairIndex0++ {\n\t\tif (nums[pairIndex0]-nums[0])%2 | tjucoder | NORMAL | 2021-12-28T04:37:30.665568+00:00 | 2021-12-28T04:37:30.665602+00:00 | 108 | false | ```go\nfunc recoverArray(nums []int) []int {\n\tsort.Ints(nums)\n\tfor pairIndex0 := 1; pairIndex0 < len(nums); pairIndex0++ {\n\t\tif (nums[pairIndex0]-nums[0])%2 != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tk := (nums[pairIndex0] - nums[0]) / 2\n\t\tif k == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpairs := make(map[int]int, len(nums))\n\t\toriginal := make([]int, 0, len(nums)/2)\n\t\tfor _, v := range nums {\n\t\t\tif pairs[v] > 0 {\n\t\t\t\tpairs[v]--\n\t\t\t} else {\n\t\t\t\tpairs[v+k+k]++\n\t\t\t\toriginal = append(original, v+k)\n\t\t\t}\n\t\t}\n\t\tok := true\n\t\tfor _, v := range pairs {\n\t\t\tif v != 0 {\n\t\t\t\tok = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif ok {\n\t\t\treturn original\n\t\t}\n\t}\n\treturn nil\n}\n``` | 1 | 0 | ['Go'] | 0 |
recover-the-original-array | Super easy to understand C++ Code, beat 100% | super-easy-to-understand-c-code-beat-100-9a5c | Idea is straight forward - try every possible k.\n1. First we sort array and get minimum value - minV in this array, then try all possible high value of minV to | dogmimi | NORMAL | 2021-12-27T13:51:09.155646+00:00 | 2021-12-27T13:51:09.155677+00:00 | 241 | false | Idea is straight forward - try every possible k.\n1. First we sort array and get minimum value - minV in this array, then try all possible `high` value of minV to calculate k.\nTo get k, minV plus its high value s hould be even, and k can only be larger than 0.\n2. Then we need to verify if k is valid. Here I use a `used` vector to make sure we didn\'t use same index again, then use just two pointers to iterate the sorted array. If we can\'t find matching, just break and try other k.\n3. During iteration, fill in result array. If we can iterate `n` times, then we found the result.\n\n```\nclass Solution {\npublic:\n bool kernel(int n, vector<int>& nums, int k, vector<bool>& used, vector<int>& result){\n int k2 = k + k;\n int i = 0;\n int lIndex = 0;\n int hIndex = 0;\n int v1, v2, v;\n int n2 = n * 2;\n for(; i < n; i++){\n while(lIndex < n2 && used[lIndex]){\n lIndex++;\n }\n if(lIndex == n2){\n break;\n }\n v1 = nums[lIndex];\n used[lIndex] = true;\n v = v1 + k2;\n while(hIndex < n2 && (used[hIndex] || nums[hIndex] != v)){\n hIndex++;\n }\n if(hIndex == n2){\n break;\n }\n used[hIndex] = true;\n result[i] = v1 + k;\n }\n \n return i == n;\n }\n vector<int> recoverArray(vector<int>& nums) {\n sort(begin(nums), end(nums));\n \n int n = nums.size() / 2;\n int minV = nums[0];\n vector<int> result(n);\n int total = n + n;\n vector<bool> used(total);\n for(int i = 1; i <= n; i++){\n if((minV + nums[i]) % 2 == 0){\n int k = (nums[i] - minV) / 2;\n if(k == 0){\n continue;\n }\n fill(begin(used), end(used), false);\n bool found = kernel(n, nums, k, used, result);\n if(found){\n break;\n } \n }\n }\n \n return result;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'Greedy', 'C'] | 1 |
recover-the-original-array | Java solution using 2 pointer along with every possible value of k (11ms) | java-solution-using-2-pointer-along-with-zqpt | \nclass Solution {\n \n int[] res;\n public int[] recoverArray(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n ArrayLi | akshobhyapal | NORMAL | 2021-12-27T12:51:23.106393+00:00 | 2021-12-27T12:51:52.454323+00:00 | 157 | false | ```\nclass Solution {\n \n int[] res;\n public int[] recoverArray(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n ArrayList<Integer> diffs = new ArrayList<>();\n int smallest = nums[0];\n for(int i = 1; i < n; i++){\n int k =(nums[i] - smallest) / 2;\n if((nums[i] - smallest) % 2 == 0 && k !=0){\n diffs.add(k);\n }\n }\n for(int k : diffs){\n if(check(n,k,nums)) break;\n }\n return res;\n }\n \n public boolean check(int n, int k, int[] nums){\n res = new int[n/2];\n boolean[] visited = new boolean[n];\n int lower = 0;\n int higher = 1;\n int count = 0;\n while(lower < n){\n \n if(visited[lower]){\n lower++;\n continue;\n }\n int lowerVal = nums[lower];\n int higherVal = lowerVal + (2 * k);\n while(higher < n){\n if(nums[higher] == higherVal && !visited[higher]) break;\n higher++;\n }\n if(higher == n) return false;\n visited[lower] = true;\n visited[higher] = true;\n res[count] = lowerVal + k;\n count++;\n if(count == n/2) return true;\n lower++;\n higher++;\n }\n return false;\n } \n \n}\n``` | 1 | 0 | ['Two Pointers', 'Java'] | 0 |
recover-the-original-array | Python O(N^2) | python-on2-by-miaomicode-dp20 | ```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n n = int(len(nums) / 2)\n nums.sort() \n \n | miaomicode | NORMAL | 2021-12-26T23:56:03.320923+00:00 | 2021-12-26T23:56:03.320955+00:00 | 75 | false | ```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n n = int(len(nums) / 2)\n nums.sort() \n \n for i in range(1, n * 2):\n k = nums[i] - nums[0]\n if k != 0 and not k % 2:\n higher = collections.defaultdict(int)\n original = []\n for num in nums:\n if num in higher and higher[num]:\n higher[num] -= 1\n else:\n higher[num + k] += 1\n original.append(num + int(k / 2))\n if len(original) == n:\n return original | 1 | 0 | [] | 0 |
recover-the-original-array | Check common possible k from both sides[Java][8ms][100%] | check-common-possible-k-from-both-sidesj-fqta | Idea\nIf we sort nums, then nums[0] must be is the lower value of the smallest value of the original array(min(arr) - k).\nThen, we can check the differences nu | akokoz | NORMAL | 2021-12-26T20:24:26.674524+00:00 | 2021-12-26T20:25:04.968319+00:00 | 81 | false | **Idea**\nIf we sort `nums`, then `nums[0]` must be is the `lower` value of the smallest value of the original array(`min(arr) - k`).\nThen, we can check the differences `nums[i] - nums[0]` for the one that matches all pairs. The differences to consider must be positive and even.\n\n**Optimizations**\n1. We can check only the differences `nums[i] - nums[0]` for `1 <= i < n`, since nums[n] is the rightmost possible match for `nums[0]`.\n2. Similarly to `nums[0]` being the `lower` value of the smallest number in te original array, `nums[2n - 1]` must be the `higher` value of the largest number in the original array(`max(arr) + k`). So we can also find the (positive and even) differences `nums[2n - 1] - nums[i]` (`2n - 1 - n <= i < 2n`) and check only the ones that appear also in the differences found from `nums[i] - nums[0]`.\n\n**Complexity**\nTime: O(n^2)\nSpace: O(n)\n\n**Code**\n```\nclass Solution {\n public int[] recoverArray(int[] nums) {\n int n2 = nums.length;\n int n = n2 / 2;\n int[] arr = new int[n];\n \n Arrays.sort(nums);\n // find valid differences: nums[i] - nums[0]\n Set<Integer> diffs1 = new HashSet<>();\n for (int i = 1; i <= n; i++) {\n int cand = nums[i] - nums[0];\n if (cand > 0 && (cand & 1) == 0) {\n diffs1.add(cand);\n }\n }\n \n // find valid differences: nums[2n - 1] - nums[i] that also appear in the nums[i] - nums[0] differences\n\t\t// \n Set<Integer> diffs2 = new HashSet<>();\n for (int i = n2 - n - 1; i < n2 - 1; i++) {\n int cand = nums[n2 - 1] - nums[i];\n if (cand > 0 && (cand & 1) == 0 && diffs1.contains(cand)) {\n diffs2.add(cand);\n }\n }\n \n // check each candidate difference\n outer:\n for (int diff : diffs2) {\n Deque<Integer> dq = new ArrayDeque<>();\n int p = 0;\n int k = diff / 2;\n for (int num : nums) {\n if (!dq.isEmpty() && num == dq.peekFirst()) {\n dq.pollFirst();\n continue;\n } else {\n if (p == n) continue outer;\n arr[p++] = num + k;\n dq.addLast(num + diff);\n }\n \n }\n if (p == n) break;\n }\n \n return arr;\n }\n \n}\n``` | 1 | 0 | ['Greedy', 'Java'] | 0 |
recover-the-original-array | (C++) 2122. Recover the Original Array | c-2122-recover-the-original-array-by-qee-thj9 | \n\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end()); \n \n map<int, int> cnt; | qeetcode | NORMAL | 2021-12-26T17:33:11.045080+00:00 | 2021-12-26T17:33:11.045138+00:00 | 226 | false | \n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end()); \n \n map<int, int> cnt; \n for (auto& x : nums) ++cnt[x]; \n \n vector<int> ans; \n for (int i = 1; i < nums.size(); ++i) {\n int diff = nums[i] - nums[0]; \n if (diff && diff % 2 == 0) {\n ans.clear(); \n bool found = true; \n map<int, int> freq = cnt; \n for (auto& [k, v] : freq) {\n if (v) {\n if (freq[k + diff] < v) {found = false; break;}\n freq[k+diff] -= v; \n for (; v; --v) ans.push_back(k+diff/2); \n }\n }\n if (found) break; \n }\n }\n return ans; \n }\n};\n``` | 1 | 0 | ['C'] | 0 |
recover-the-original-array | golang | golang-by-eesketit-uorv | we know the smallest number in nums, is the smallest number in result + k. From there, try out all possible k from nums[i] - nums[0].\n\n\nfunc recoverArray(num | eesketit | NORMAL | 2021-12-26T09:47:13.975408+00:00 | 2021-12-26T09:47:13.975441+00:00 | 54 | false | we know the smallest number in nums, is the smallest number in result + k. From there, try out all possible k from nums[i] - nums[0].\n\n```\nfunc recoverArray(nums []int) []int {\n sort.Ints(nums)\n freq := make(map[int]int)\n for _, n := range nums {\n freq[n]++\n }\n for i := 1; i<len(nums); i++ {\n k := nums[i] - nums[0]\n if k % 2 == 1 || k == 0 { // k must be positive\n continue\n }\n k /= 2\n temp := make(map[int]int)\n for k, v := range freq {\n temp[k] = v\n }\n res := make([]int, 0)\n for _, v := range nums {\n if temp[v] > 0 {\n temp[v]--\n if temp[v + 2*k] == 0 { // invalid k\n break\n }\n temp[v + 2*k]--\n res = append(res, v + k)\n }\n }\n if len(res) == len(nums) / 2 {\n return res\n }\n }\n \n return nil\n}\n\n\n/*\n\nwe know the smallest number in nums is lowest val in res + k\n\nwe can reduce bounds of k to try\n\n*/\n``` | 1 | 0 | [] | 1 |
recover-the-original-array | Java | Sort and try all Ks | brute force with two pointers (6ms) | java-sort-and-try-all-ks-brute-force-wit-7qpi | Sort the mixed up array and use two pointers within it (i1, i2) to point to elements of the smaller and larger arrays.\nTry all possible Ks: the first element o | prezes | NORMAL | 2021-12-26T06:32:21.391094+00:00 | 2021-12-26T07:46:10.283941+00:00 | 98 | false | Sort the mixed up array and use two pointers within it (i1, i2) to point to elements of the smaller and larger arrays.\nTry all possible Ks: the first element of the larger array after sorting can be at index in range [1...n]. K is then equal to (nums[i2]-nums[i1])/2 (must be positive).\n```\n // i - index of resulting array (ans)\n // i1/i2next - indexes of smaller array (as subsequence of nums)\n // i2/i2next - indexes of larger array (as subsequence of nums)\n\nclass Solution {\n public int[] recoverArray(int[] nums) {\n Arrays.sort(nums);\n int ans[]= null, n= nums.length/2;\n for(int i2=1; i2<=n; i2++)\n if((ans= attempt(nums, i2))!=null) break;\n return ans;\n }\n\n int[] attempt(int[] nums, int i2){\n int twoN= nums.length, n= twoN/2, i=0, i1= 0;\n boolean[] used= new boolean[twoN];\n used[i1]= used[i2]= true;\n\n int twoK= nums[i2]-nums[i1], k= twoK/2;\n if(twoK==0 || twoK%2==1) return null;\n \n int[] ans= new int[n];\n ans[i++]= nums[i1]+k;\n while(i<n){\n int i1next= i1+1;\n while(i1next<twoN && used[i1next]) i1next++;\n if(i1next==twoN) return null;\n used[i1next]= true;\n \n int diff= nums[i1next]-nums[i1], num2next= nums[i2]+diff;\n int i2next= i2+1;\n while(i2next<twoN && nums[i2next]<num2next) i2next++;\n if(i2next==twoN || nums[i2next]!=num2next) return null;\n used[i2next]= true;\n \n ans[i++]= nums[i1next]+k;\n i1= i1next;\n i2= i2next;\n }\n return ans;\n }\n} | 1 | 0 | [] | 0 |
recover-the-original-array | [Python3] Try All Valid K Values | python3-try-all-valid-k-values-by-simone-7e6b | ```\nclass Solution:\n def recoverArray(self, nums):\n self.n, self.nums = len(nums) // 2, sorted(nums)\n\n small = self.nums[0]\n for x | simonesestili | NORMAL | 2021-12-26T04:53:14.846269+00:00 | 2021-12-26T04:57:19.845913+00:00 | 142 | false | ```\nclass Solution:\n def recoverArray(self, nums):\n self.n, self.nums = len(nums) // 2, sorted(nums)\n\n small = self.nums[0]\n for x in self.nums[1:]:\n k = x - small # this represents 2 * k from the problem statement\n if k % 2 or not k: continue\n temp = self.valid(k)\n if temp: return temp\n return []\n\n def valid(self, k):\n counts = defaultdict(list)\n for i in range(len(self.nums) - 1, -1, -1):\n counts[self.nums[i]].append(i)\n\n # go through each value from smallest to largest\n # at each value check for corresponding (val + k)\n # keep track of which values are used when checking\n # ahead for the (val + k)\n # finally add (val + k / 2) if we find the corresponding\n\t\t# (val + k) as it is the value from the original array\n ans, used = [], [False] * len(self.nums)\n for i, v in enumerate(self.nums):\n if used[i]: continue\n if not counts[v + k]: return []\n used[counts[v + k].pop()] = True\n ans.append(v + k // 2)\n return ans | 1 | 0 | ['Python3'] | 0 |
recover-the-original-array | Multiset O(n^2logn) Time Complexity | multiset-on2logn-time-complexity-by-yash-0kcl | Intuition
Find all possible k values.
We can do it by fixing one element and iterating aover all elements and getting corresponding k value thinking that this i | yash559 | NORMAL | 2025-01-31T02:12:31.365988+00:00 | 2025-01-31T02:12:31.365988+00:00 | 10 | false | # Intuition
- Find all possible k values.
- We can do it by fixing one element and iterating aover all elements and getting corresponding k value thinking that this is a possible result.
- Now, check whether this k matches.
- Now we need an efficient data structure which can store the **duplicates and as well deletion in logn time complexity.**
- Yes, it's multiset.
- for each **k** find it fits the bill or not.
- if so return original array otherwise go on for other possible k values.
# Complexity
- Time complexity: $$O(n^2logn)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<int> check(multiset<int> mset, int k) {
//now it is sorted
//so we are getting x - k at top of set
//now find x + k
vector<int> ans;
while(!mset.empty()) {
int smallest = *mset.begin();
//x - k
//large is smallest + 2*k => ((x - k) + 2*k = x + k)
int largest = smallest + 2*k;
//find the other element
auto iter = mset.find(largest);
if(iter == mset.end()) {
return {}; //if not found means this k value is not satisfied
}
ans.push_back((smallest + largest)/2); //get original element
mset.erase(iter); //erase pair
mset.erase(mset.find(*mset.begin()));
}
return ans;
}
vector<int> recoverArray(vector<int>& nums) {
int n = nums.size();
multiset<int> mset(nums.begin(),nums.end());
//get all possible k values;
int first = nums[0];
for(int i = 1;i < n;i++) {
int second = nums[i];
//k should be integer so diff should be even
if(abs(first - second) & 1) continue; //odd diff
int k = abs(first - second)/2; //we don't know it might be bigger or smaller
//k = (x - k) - (x + k) => 2*k/2 = k
//now check this k value
if(k == 0) continue; //k should be positive integer
vector<int> ans = check(mset, k);
if(!ans.empty()) return ans;
}
return {};
}
};
``` | 0 | 0 | ['C++'] | 0 |
recover-the-original-array | 2122. Recover the Original Array | 2122-recover-the-original-array-by-g8xd0-dszk | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-18T03:09:28.900147+00:00 | 2025-01-18T03:09:28.900147+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public int[] RecoverArray(int[] nums) {
Array.Sort(nums);
int n = nums.Length;
for (int i = 1; i < n; i++) {
int candidateK = (nums[i] - nums[0]) % 2 == 1 ? -1 : (nums[i] - nums[0]) / 2;
if (candidateK <= 0) continue;
var numberFrequency = new Dictionary<int, int>();
var outputArray = new List<int>();
foreach (var num in nums) {
if (numberFrequency.ContainsKey(num) && numberFrequency[num] > 0) {
outputArray.Add(num - candidateK);
numberFrequency[num]--;
if (numberFrequency[num] == 0) {
numberFrequency.Remove(num);
}
} else {
numberFrequency[num + 2 * candidateK] = numberFrequency.GetValueOrDefault(num + 2 * candidateK, 0) + 1;
}
}
if (outputArray.Count == n / 2 && numberFrequency.Count == 0) {
return outputArray.ToArray();
}
}
return Array.Empty<int>();
}
}
``` | 0 | 0 | ['C#'] | 0 |
recover-the-original-array | Checking pairs | checking-pairs-by-vats_lc-a7f5 | Code | vats_lc | NORMAL | 2025-01-09T05:11:58.756918+00:00 | 2025-01-09T05:11:58.756918+00:00 | 8 | false | # Code
```cpp []
class Solution {
public:
vector<int> recoverArray(vector<int>& a) {
int n = a.size(), diff = 0;
sort(a.begin(), a.end());
map<int, int> mpp;
for (int i = 0; i < n; i++)
mpp[a[i]]++;
for (int i = 1; i < n; i++) {
diff = a[i] - a[0];
if (diff & 1)
continue;
map<int, int> mp1 = mpp;
bool c = true;
for (int j = 0; j < n; j++) {
if (mp1[a[j]] == 0)
continue;
if (mp1[a[j] + diff] == 0) {
c = false;
break;
}
mp1[a[j]]--;
mp1[a[j] + diff]--;
}
if (c && diff > 0)
break;
}
vector<int> ans;
for (int i = 0; i < n; i++) {
if (mpp[a[i]] == 0)
continue;
if (mpp[a[i]] && mpp[a[i] + diff]) {
ans.push_back(a[i] + diff / 2);
mpp[a[i]]--;
mpp[a[i] + diff]--;
}
}
return ans;
}
};
``` | 0 | 0 | ['C++'] | 0 |
recover-the-original-array | SImple hashmap solution | simple-hashmap-solution-by-risabhuchiha-3h58 | null | risabhuchiha | NORMAL | 2024-12-26T12:34:31.895413+00:00 | 2024-12-26T12:34:31.895413+00:00 | 5 | false |
```java []
class Solution {
public int[] recoverArray(int[] nums) {
Arrays.sort(nums);
int s=nums[0];
for(int i=1;i<nums.length;i++){
int k=(nums[i]-s);
if(k==0)continue;
if(k%2!=0)continue;
k=k/2;
//if(k==0)continue;
if(s+k!=nums[i]-k)continue;
HashMap<Integer,Integer>hm=new HashMap<>();
ArrayList<Integer>al=new ArrayList<>();
al.add(s+k);
// al.add(nums[i]-k);
for(int j=1;j<nums.length;j++){
if(j==i)continue;
hm.put(nums[j],hm.getOrDefault(nums[j],0)+1);
}
for(int j=1;j<nums.length;j++){
if(j==i)continue;
if(!hm.containsKey(nums[j]))continue;
if(hm.containsKey(nums[j]+2*k)){
hm.put(nums[j]+2*k,hm.getOrDefault(nums[j]+2*k,0)-1);
if(hm.get(nums[j]+2*k)<=0)hm.remove(nums[j]+2*k);
hm.put(nums[j],hm.getOrDefault(nums[j],0)-1);
if(hm.get(nums[j])<=0)hm.remove(nums[j]);
al.add(nums[j]+k);
// al.add(nums[j]+2*k);
}
else{
}
}
// System.out.println(hm+" "+al+" "+i+" "+k+" "+nums[i]);
if(al.size()==nums.length/2){
int[]ans=new int[al.size()];
for(int ll=0;ll<al.size();ll++){
ans[ll]=al.get(ll);
}
return ans;
}
}
return new int[]{};
}// 2 4 6 8 10 12 nums[0]<nums[1]-k||nums[0]>=nums[1]+k nums[l]+k;
}
``` | 0 | 0 | ['Java'] | 0 |
recover-the-original-array | Recover the Original Array | recover-the-original-array-by-naeem_abd-eb0e | 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 | Naeem_ABD | NORMAL | 2024-12-03T04:55:38.420737+00:00 | 2024-12-03T04:55:38.420772+00:00 | 2 | 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```javascript []\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar recoverArray = function (nums) {\n nums.sort((a, b) => (a - b));\n\n for (let i = 1; i <= nums.length / 2; i++) {\n let twiceK = nums[i] - nums[0];\n if (twiceK === 0 || twiceK % 2 === 1) continue;\n let result = [];\n let map = new Map();\n for (let num of nums) {\n let count = map.get(num - twiceK);\n if (!count) {\n map.set(num, (map.get(num) || 0) + 1);\n } else {\n result.push(num - twiceK / 2);\n map.set(num - twiceK, count - 1);\n }\n }\n if (result.length === nums.length / 2) {\n return result;\n }\n }\n\n return [];\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
recover-the-original-array | Python (Simple Hashmap) | python-simple-hashmap-by-rnotappl-qyeg | 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 | rnotappl | NORMAL | 2024-11-02T15:10:21.757536+00:00 | 2024-11-02T15:10:21.757567+00:00 | 9 | 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```python3 []\nclass Solution:\n def recoverArray(self, nums):\n n = len(nums)\n\n nums.sort()\n\n def function(k):\n dict1, res = Counter(nums), []\n\n for i in nums:\n if i not in dict1:\n continue \n elif i in dict1 and i+2*k in dict1:\n res.append(i+k)\n dict1[i] -= 1 \n dict1[i+2*k] -= 1 \n if dict1[i] == 0:\n del dict1[i]\n if dict1[i+2*k] == 0:\n del dict1[i+2*k]\n else:\n return []\n\n return res \n\n for i in range(1,n):\n val = nums[i] - nums[0]\n if val != 0 and val%2 == 0:\n p = function(val//2)\n if p: return p\n\n return []\n``` | 0 | 0 | ['Python3'] | 0 |
recover-the-original-array | 2122. Recover the Original Array.cpp | 2122-recover-the-original-arraycpp-by-20-cg7p | Code\n\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end()); \n \n map<int, int> | 202021ganesh | NORMAL | 2024-11-01T10:53:21.078503+00:00 | 2024-11-01T10:53:21.078532+00:00 | 0 | false | **Code**\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end()); \n \n map<int, int> cnt; \n for (auto& x : nums) ++cnt[x]; \n \n vector<int> ans; \n for (int i = 1; i < nums.size(); ++i) {\n int diff = nums[i] - nums[0]; \n if (diff && diff % 2 == 0) {\n ans.clear(); \n bool found = true; \n map<int, int> freq = cnt; \n for (auto& [k, v] : freq) {\n if (v) {\n if (freq[k + diff] < v) {found = false; break;}\n freq[k+diff] -= v; \n for (; v; --v) ans.push_back(k+diff/2); \n }\n }\n if (found) break; \n }\n }\n return ans; \n }\n};\n``` | 0 | 0 | ['C'] | 0 |
recover-the-original-array | Python (Simple Hashmap) | python-simple-hashmap-by-rnotappl-zvd0 | 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 | rnotappl | NORMAL | 2024-10-31T08:26:14.614646+00:00 | 2024-10-31T08:26:14.614673+00:00 | 6 | 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```python3 []\nclass Solution:\n def recoverArray(self, nums):\n n = len(nums)\n\n nums.sort()\n\n def function(k):\n dict1, res = Counter(nums), []\n\n for i in nums:\n if i not in dict1:\n continue \n elif i in dict1 and i+2*k in dict1:\n res.append(i+k)\n dict1[i] -= 1 \n dict1[i+2*k] -= 1 \n if dict1[i] == 0:\n del dict1[i]\n if dict1[i+2*k] == 0:\n del dict1[i+2*k]\n else:\n return []\n\n return res \n\n for i in range(1,n):\n val = nums[i] - nums[0]\n if val != 0 and val%2 == 0:\n p = function(val//2)\n if p: return p\n\n return []\n``` | 0 | 0 | ['Python3'] | 0 |
recover-the-original-array | Easy Solution || try diff values of k | easy-solution-try-diff-values-of-k-by-ab-0zr9 | 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 | Abhi5114 | NORMAL | 2024-10-18T15:46:15.697573+00:00 | 2024-10-18T15:46:15.697602+00:00 | 2 | 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```java []\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\n\nclass Solution {\n // Method to get the possible doubled differences\n public List<Integer> getDoubledDiff(int[] nums) {\n int n = nums.length;\n List<Integer> diff = new ArrayList<>();\n for (int i = 1; i <n/2+1; i++) {\n int dif = nums[i] - nums[0];\n if (dif > 0 && dif % 2 == 0) {\n diff.add(dif); // Add valid doubled difference\n }\n }\n return diff;\n }\n\n // Method to get the solution based on a specific doubled difference\n public List<Integer> getSolution(int[] nums, int diff) {\n int n = nums.length;\n HashMap<Integer, Integer> mp = new HashMap<>();\n List<Integer> res = new ArrayList<>();\n\n // Count frequencies of each element\n for (int x : nums) {\n mp.put(x, mp.getOrDefault(x, 0) + 1);\n }\n\n for (int i = 0; i < n; i++) {\n // If current element exists in the map\n if (mp.containsKey(nums[i])) {\n mp.put(nums[i], mp.get(nums[i]) - 1);\n if (mp.get(nums[i]) == 0) {\n mp.remove(nums[i]); // Remove if frequency is zero\n }\n\n int val = nums[i] + diff; // Calculate A + K\n // Check if A + K exists in the map\n if (!mp.containsKey(val)) {\n return res; // Return empty if not found\n } else {\n mp.put(val, mp.get(val) - 1);\n if (mp.get(val) == 0) {\n mp.remove(val); // Remove if frequency is zero\n }\n\n // Add the original value A to the result\n res.add(nums[i] + diff / 2);\n }\n }\n }\n return res; // Return the successfully reconstructed array\n }\n\n public int[] recoverArray(int[] nums) {\n int n = nums.length;\n java.util.Arrays.sort(nums); // Sort the input array\n\n List<Integer> doubledDiff = getDoubledDiff(nums); // Get possible doubled differences\n\n for (int diff : doubledDiff) {\n List<Integer> ans = getSolution(nums, diff); // Try to reconstruct with each diff\n if (ans.size() == (n / 2)) { // If valid, return the result\n int[] result = new int[ans.size()];\n for (int i = 0; i < ans.size(); i++) {\n result[i] = ans.get(i); // Convert List to array\n }\n return result;\n }\n }\n return new int[0]; // Return empty if no valid solution found\n }\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
recover-the-original-array | Python (Simple Sorting + Hashmap) | python-simple-sorting-hashmap-by-rnotapp-y0ss | 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 | rnotappl | NORMAL | 2024-10-09T09:11:48.086965+00:00 | 2024-10-09T09:11:48.087001+00:00 | 5 | 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```python3 []\nclass Solution:\n def recoverArray(self, nums):\n n = len(nums)\n\n nums.sort()\n\n def function(k):\n dict1, res = Counter(nums), []\n\n for i in nums:\n if i not in dict1:\n continue \n elif i in dict1 and i+2*k in dict1:\n res.append(i+k)\n dict1[i] -= 1 \n dict1[i+2*k] -= 1 \n if dict1[i] == 0:\n del dict1[i]\n if dict1[i+2*k] == 0:\n del dict1[i+2*k]\n else:\n return []\n\n return res \n\n for i in range(1,n):\n val = nums[i] - nums[0]\n if val != 0 and val%2 == 0:\n p = function(val//2)\n if p: return p\n\n return []\n``` | 0 | 0 | ['Python3'] | 0 |
recover-the-original-array | C# Greedy with Two Pointer Solution | c-greedy-with-two-pointer-solution-by-ge-w78v | Intuition\n- Describe your first thoughts on how to solve this problem. First Thoughts: The intuition behind solving this problem is to realize that the array | GetRid | NORMAL | 2024-10-07T15:37:16.856591+00:00 | 2024-10-07T15:37:16.856626+00:00 | 3 | false | # Intuition\n- <!-- Describe your first thoughts on how to solve this problem. -->First Thoughts: The intuition behind solving this problem is to realize that the array you are given (nums) is actually the result of performing an operation that involves an original array with a certain offset (k). The key challenge here is to figure out the original elements and the correct value of k.\n\n- The main observation is that the original array consists of pairs in nums that are separated by 2 * k. Therefore, the approach is to iterate through possible values for k and check if they can successfully reconstruct the original array.\n___\n# Approach\n- <!-- Describe your approach to solving the problem. -->First, sort the given array to make it easier to identify potential pairs.\n- Start by trying different values for k. Since k must be positive, a natural place to look is the difference between the smallest element (nums[0]) and other elements in the sorted list.\n- Use the first two elements (nums[0] and nums[i]) to calculate a candidate value for k. Only valid candidates are considered if k > 0 and the difference is even ((nums[i] - nums[0]) % 2 == 0).\n- Once a candidate k is identified, use a two-pointer approach to verify whether all elements of the given array can be paired in a way that follows the required pattern (nums[right] == nums[left] + 2 * k). Use a visited array to mark which elements have been used.\n- If a candidate value for k successfully pairs all elements, the original array is reconstructed and returned.\n___\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n^2), where \'n\' is the length of the \'nums\' array.\n- The outer loop iterates over the possible values for \'k\', which is O(n).\n- For each candidate \'k\', the two-pointer traversal takes O(n) to find pairs in the original array.\n___\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n), where \'n \'is the length of the \'nums\' array.\n- The \'visited\' boolean array takes O(n) space.\n- The \'originalArray\' list also takes O(n) space.\n___\n\n# Code\n```csharp []\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Solution {\n public int[] RecoverArray(int[] nums) {\n Array.Sort(nums);\n int n = nums.Length / 2;\n \n for (int i = 1; i < nums.Length; i++) {\n int potentialK = (nums[i] - nums[0]) / 2;\n if (potentialK <= 0 || (nums[i] - nums[0]) % 2 != 0) continue;\n \n int k = potentialK;\n var originalArray = new List<int>();\n var visited = new bool[nums.Length];\n \n int left = 0, right = i;\n while (right < nums.Length) {\n if (visited[left]) {\n left++;\n continue;\n }\n if (visited[right] || nums[right] != nums[left] + 2 * k) {\n right++;\n continue;\n }\n \n originalArray.Add(nums[left] + k);\n visited[left] = true;\n visited[right] = true;\n left++;\n right++;\n }\n \n if (originalArray.Count == n) {\n return originalArray.ToArray();\n }\n }\n \n return new int[0];\n }\n}\n\n// Sorting the Input: First, we sort nums to ensure we can easily find pairs.\n// Finding Possible k: We iterate through possible pairs to determine a potential k. This is done by using the difference between the smallest value (nums[0]) and another value (nums[i]). k must be positive, and we ensure it divides evenly.\n// Pairing Values: We use a greedy approach to pair values. For each k, we attempt to pair each element in nums with another value that matches the expected difference (2 * k). We skip elements that have already been visited.\n// Checking Validity: If we successfully pair all values and reconstruct the original array, we return it.\n``` | 0 | 0 | ['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'C#'] | 0 |
recover-the-original-array | ruby 2-liner | ruby-2-liner-by-_-k-mjj7 | ruby []\ndef recover_array(a) =\n\n a.sort!.uniq[1..].map{ 1>1&d=_1-a[0] and t=a.tally and break a.map{|x|\n t[x]-=1 and 1/~t[x+d]-=1 and x+d/2 if t[x]>0 } | _-k- | NORMAL | 2024-09-28T05:59:29.403852+00:00 | 2024-09-28T06:46:28.716516+00:00 | 5 | false | ```ruby []\ndef recover_array(a) =\n\n a.sort!.uniq[1..].map{ 1>1&d=_1-a[0] and t=a.tally and break a.map{|x|\n t[x]-=1 and 1/~t[x+d]-=1 and x+d/2 if t[x]>0 } rescue 0 }.compact\n``` | 0 | 0 | ['Ruby'] | 0 |
recover-the-original-array | [Python3] Just Working Code - 27.09.2024 | python3-just-working-code-27092024-by-pi-19wz | \npython3 [1 python3]\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n cnt = Counter(nums)\n for | Piotr_Maminski | NORMAL | 2024-09-27T14:42:40.107781+00:00 | 2024-09-27T14:44:54.189657+00:00 | 7 | false | \n```python3 [1 python3]\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n cnt = Counter(nums)\n for i in range(1, len(nums)): \n diff = nums[i] - nums[0]\n if diff and diff&1 == 0: \n ans = []\n freq = cnt.copy()\n for k, v in freq.items(): \n if v: \n if freq[k+diff] < v: break \n ans.extend([k+diff//2]*v)\n freq[k+diff] -= v\n else: return ans \n```\n```python3 [2 python3]\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n val, n = nums[0], len(nums)\n\n for j in range(1, n) :\n if nums[j] == val :\n continue \n\n if nums[j] % 2 == val % 2 :\n k = (nums[j] - val) // 2 \n\n visit, i, ans = [False for _ in range(len(nums))], 0, []\n\n while j < n :\n if visit[i] :\n i += 1 \n elif visit[j] :\n j += 1 \n elif nums[i] + 2 * k == nums[j] :\n ans.append(nums[i] + k)\n visit[i] = True \n visit[j] = True \n i += 1 \n j += 1 \n elif nums[i] + 2 * k > nums[j] :\n j += 1 \n else :\n break \n\n if len(ans) == n // 2 :\n return ans\n```\n | 0 | 0 | ['Python3'] | 0 |
recover-the-original-array | Python (Simple Maths) | python-simple-maths-by-rnotappl-lld4 | 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 | rnotappl | NORMAL | 2024-07-24T13:57:03.521218+00:00 | 2024-07-24T13:57:03.521251+00:00 | 3 | 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 def recoverArray(self, nums):\n n = len(nums)\n\n nums.sort()\n\n def function(k):\n res, dict1 = [], Counter(nums)\n\n for i in nums:\n if dict1[i] and dict1[i+2*k]:\n res.append(i+k)\n dict1[i] -= 1 \n dict1[i+2*k] -= 1 \n\n if len(res) == n//2:\n return res \n\n return []\n\n for i in range(n):\n if (nums[i]-nums[0]) > 0 and (nums[i]-nums[0])%2 == 0:\n ans = function((nums[i]-nums[0])//2)\n if ans: return ans\n\n return []\n``` | 0 | 0 | ['Python3'] | 0 |
recover-the-original-array | Check for all possible Ks | check-for-all-possible-ks-by-akshay_gupt-tqu9 | Intuition\nCheck with all possible k.\n\n# Approach\nCheck of each possible pair what K could be. THen with one K try pairing exisitng numbers, if there\'s some | akshay_gupta_7 | NORMAL | 2024-07-12T18:44:52.427896+00:00 | 2024-07-12T18:44:52.427928+00:00 | 3 | false | # Intuition\nCheck with all possible k.\n\n# Approach\nCheck of each possible pair what K could be. THen with one K try pairing exisitng numbers, if there\'s some numbers which are pending and can\'t be paired, this K is not possibe.\n\n# Complexity\n- Time complexity:\n$$O(n^3)$$\n\n- Space complexity:\n$$O(n)$$\n\n\n# Code\n```\nclass Solution {\n public int[] recoverArray(int[] nums) {\n Arrays.sort(nums);\n ArrayBuilder builder=new ArrayBuilder();\n for(int i=0;i<nums.length;i++){\n for(int j=i+1;j<nums.length;j++){\n int k=nums[j]-nums[i];\n if(k%2!=0 || k==0){\n continue;\n }\n k/=2;\n int[] withThisK=builder.getArray(nums,k);\n if(withThisK!=null){\n return withThisK;\n }\n }\n }\n return null;\n }\n}\nclass ArrayBuilder{\n Pending pendingNumbers;\n int orignalArray[];\n int orignalArrayIndex;\n int k;\n int[] getArray(int nums[],int k){\n pendingNumbers=new Pending();\n orignalArrayIndex=0;\n this.k=k;\n orignalArray=new int[nums.length/2];\n for(int i=0;i<nums.length;i++){\n boolean canPair=pairNumber(nums[i]);\n if(!canPair){\n pendingNumbers.add(nums[i]);\n }\n }\n if(!pendingNumbers.isEmpty()){\n return null;\n }\n return orignalArray;\n }\n boolean pairNumber(int number){\n return canPair(number-2*k,k) || canPair(number+2*k,-k);\n }\n boolean canPair(int number,int diff){\n if(pendingNumbers.continas(number)){\n pendingNumbers.remove(number);\n orignalArray[orignalArrayIndex++]=number+diff;\n return true;\n }\n return false;\n }\n}\nclass Pending{\n Map<Integer,Integer> pendingNumbers;\n public String toString(){\n return pendingNumbers.toString();\n }\n Pending(){\n pendingNumbers=new HashMap<>();\n }\n boolean isEmpty(){\n return pendingNumbers.isEmpty();\n }\n boolean continas(int number){\n return pendingNumbers.containsKey(number);\n }\n void add(int number){\n int oldFreq=pendingNumbers.getOrDefault(number, 0);\n pendingNumbers.put(number,oldFreq+1);\n }\n void remove(int number){\n int oldFreq=pendingNumbers.get(number);\n if(oldFreq==1){\n pendingNumbers.remove(number);\n }else{\n pendingNumbers.put(number,oldFreq-1);\n }\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
recover-the-original-array | Greedy + Sorting + Hashmap 💯💯💯💯 Easy To understand!!!! With Comments | greedy-sorting-hashmap-easy-to-understan-kbmf | Approach\nFirst sort the nums, this way we can tell that nums[0] is lower[i] for some ith index in the original array.\nNow we know that higher[i] - lower[i] = | adira42004 | NORMAL | 2024-07-01T10:27:57.792424+00:00 | 2024-07-01T10:27:57.792462+00:00 | 41 | false | # Approach\nFirst sort the nums, this way we can tell that nums[0] is lower[i] for some ith index in the original array.\nNow we know that **higher[i] - lower[i] = 2*k.**\nTry for all possible value of 2*k fixing lower[i]==nums[0], now for each value of 2*k check wether this value is valid or not. This can be checked if using 2*k can we consume the whole nums array or not. If we can then we have found our k, now construct the original array.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n = nums.size();\n \n //Storing the frequencies of each element\n unordered_map<int,int> freq;\n for(auto x : nums){\n freq[x]++;\n }\n \n/*After we have sorted the nums, we are sure that nums[0] is lower[i], now we will fix its valid upper[i] \none by one and then check whether the diff btw them i.e. 2*k is possible for other left numbers or not*/\n sort(nums.begin(),nums.end());\n\n int k{}; //Storing final value of K\n for(int i{1}; i<n; i++){\n int potentialK = (nums[i]-nums[0]);\n\n if(potentialK%2!=0 || potentialK==0) continue; \n potentialK/=2;\n \n unordered_map<int,int> temp = freq;\n\n //Check wether potentialK*2 is possible or not\n bool flag = true;\n for(int i{}; i<n; i++){\n //As difference between higher[i]-lower[i]==2*k, higher[i]=lower[i]+2*k\n int loweri = nums[i];\n int higheri = nums[i]+(2*potentialK);\n\n //loweri left or already used\n if(temp[loweri]!=0){\n if(temp[higheri]!=0){\n temp[loweri]--;\n temp[higheri]--;\n }\n else{\n flag = false;\n break;\n }\n }\n }\n //Found Valid K\n if(flag){\n k = potentialK;\n break;\n }\n }\n\n //Constructing the original array using K we found\n vector<int> ans;\n for(int i{}; i<n; i++){\n int loweri = nums[i];\n int higheri = nums[i]+(2*k);\n if(freq[loweri]!=0){\n int ele = nums[i]+k;\n ans.push_back(ele);\n freq[loweri]--;\n freq[higheri]--;\n }\n }\n return ans;\n }\n};\n\n\n\n``` | 0 | 0 | ['C++'] | 0 |
recover-the-original-array | sorting + greedy + hashmap | sorting-greedy-hashmap-by-maxorgus-dvhg | the smallest number could pair with any number strictly larger than it so long as their difference is even, since n<=1000, we can enumerate them in one pass\n\n | MaxOrgus | NORMAL | 2024-06-19T02:30:31.197026+00:00 | 2024-06-19T02:30:31.197087+00:00 | 14 | false | the smallest number could pair with any number strictly larger than it so long as their difference is even, since n<=1000, we can enumerate them in one pass\n\nthen for every possible k stored, see if it is possible to pair all numbers with it. that is, go through the nums, see if there is any a - 2*k before it, if yes, both of them are paired, remove the previous one and do not record the current one -- and of course we append a-k to the list of possible original list with current k. otherwise store the corrent one as unpaired. when no number is left after the loop, this k is a plausible solution and we return the original array we have recorded.\n\n# Code\n```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n maxk = (nums[-1] - nums[0]) // 2\n n = len(nums)\n possiblek = set([])\n for i in range(1,n):\n if nums[i]!=nums[0] and (nums[i] - nums[0]) % 2 == 0 and (nums[i] - nums[0]) // 2 <= maxk:\n possiblek.add((nums[i] - nums[0]) // 2) \n for k in possiblek:\n seen = {}\n res = []\n for a in nums:\n if a - 2*k in seen:\n seen[a - 2*k] -= 1\n if seen[a - 2*k] == 0:\n del seen[a - 2*k]\n res.append(a-k)\n else:\n if a not in seen:\n seen[a] = 0\n seen[a] += 1\n if not seen: return res\n\n\n\n \n``` | 0 | 0 | ['Hash Table', 'Greedy', 'Sorting', 'Python3'] | 0 |
recover-the-original-array | C++ Recovering an Array from a Given 2n Array Using Sorting and Hash Maps | c-recovering-an-array-from-a-given-2n-ar-4oll | Intuition\n\nThe problem requires recovering an array of n integers from a given array of 2n integers such that each element in the original array is the midpoi | orel12 | NORMAL | 2024-06-15T17:09:15.221815+00:00 | 2024-06-15T17:09:15.221841+00:00 | 15 | false | # Intuition\n\nThe problem requires recovering an array of n integers from a given array of 2n integers such that each element in the original array is the midpoint of two elements in the given array. We need to determine a value k such that when adding and subtracting k from each element in the recovered array, the result matches the given array. Using sorting and hash maps, we can efficiently track and verify pairs to reconstruct the original array.\n\n# Approach\nSort the Array: Begin by sorting the given array to simplify finding pairs.\nIterate Over Potential k: For each possible k (determined by examining pairs of elements in the sorted array), check if it can be used to form the required array.\nValidation of k: Use a hash map to track the frequency of each number and verify if we can consistently find pairs (x-k, x+k) in the sorted array. If we can form such pairs for the entire array, we have found the correct k.\nReturn the Result: If a valid k is found, return the recovered array; otherwise, continue until all possibilities are exhausted.\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$ for sorting the array and $$O(n)$$ for the hash map operations within the loop. Thus, the overall time complexity is $$O(nlogn)$$.\n\n- Space complexity:\n$$O(n)$$ for storing the hash map and temporary vectors.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n = nums.size() / 2;\n\n for (int start = 1; start < nums.size(); ++start) {\n int potential_k = (nums[start] - nums[0]) / 2;\n\n if (potential_k <= 0 || (nums[start] - nums[0]) % 2 != 0) {\n continue;\n }\n\n unordered_map<int, int> count;\n for (int num : nums) {\n count[num]++;\n }\n\n bool valid = true;\n vector<int> tempArray;\n\n for (int num : nums) {\n if (count[num] == 0) continue;\n if (count[num + 2 * potential_k] == 0) {\n valid = false;\n break;\n }\n tempArray.push_back(num + potential_k);\n count[num]--;\n count[num + 2 * potential_k]--;\n }\n\n if (valid) {\n return tempArray;\n }\n }\n\n return {};\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
recover-the-original-array | Elixir sort then O(n^2) | elixir-sort-then-on2-by-minamikaze392-wtdz | Code\n\ndefmodule Solution do\n @spec recover_array(nums :: [integer]) :: [integer]\n def recover_array(nums) do\n n = length(nums) |> div(2)\n list = E | Minamikaze392 | NORMAL | 2024-05-31T14:10:37.133391+00:00 | 2024-05-31T14:10:37.133453+00:00 | 0 | false | # Code\n```\ndefmodule Solution do\n @spec recover_array(nums :: [integer]) :: [integer]\n def recover_array(nums) do\n n = length(nums) |> div(2)\n list = Enum.sort(nums)\n find_original(list, list, n)\n end\n\n defp find_original(list = [a | _], [prev, b | tail], n) do\n with true <- b > prev,\n true <- rem(b - a, 2) == 0,\n k = div(b - a, 2),\n {ans, _, _} <- Enum.reduce_while(list, {[], :queue.new(), 0}, fn x, {ans, q, len} ->\n cond do\n {:value, x - k} == :queue.peek(q) ->\n {:cont, {[x - k | ans], :queue.drop(q), len}}\n len == n ->\n {:halt, nil}\n true ->\n {:cont, {ans, :queue.in(x + k, q), len + 1}}\n end\n end) do\n Enum.reverse(ans)\n else\n _ -> find_original(list, [b | tail], n)\n end\n end\nend\n``` | 0 | 0 | ['Sorting', 'Elixir'] | 0 |
recover-the-original-array | C++ Clear Solution with Queue | Beats 85% in Runtime and 79% in Memory | c-clear-solution-with-queue-beats-85-in-gx4yj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. Sort nums[] and test | danieltseng | NORMAL | 2024-05-26T08:49:47.571268+00:00 | 2024-05-26T08:49:47.571286+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort ```nums[]``` and test every possible K by ```nums[i] - nums[0]```\n2. Conduct early termination if ```ele``` is greater than the smallest numbers by ```twoK```\n3. Check all element has been paired by ```deq.size() == 0```\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 {\nprivate:\n bool recover(vector<int>& nums, int twoK, vector<int>& answer){\n\n //invalid k\n if(twoK % 2 == 1 || twoK == 0) return false;\n\n deque<int> deq;\n for(int ele : nums){\n if(deq.size() > 0 && ele - twoK > deq.front()){\n return false;\n }else if(deq.size() > 0 && ele - twoK == deq.front()){\n answer.push_back(deq.front() + (twoK/2));\n deq.pop_front();\n }else{\n deq.push_back(ele);\n }\n }\n return deq.size() == 0;\n }\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n for(int i = 0; i < n; ++i){\n vector<int> answer;\n if(recover(nums, nums[i]-nums[0], answer)){\n return answer;\n }\n }\n // should never be here\n return vector<int>();\n }\n};\n```\n\n | 0 | 0 | ['Array', 'Queue', 'Sorting', 'C++'] | 0 |
recover-the-original-array | limit candidate k's to those with at least n counts in all pairwise diffs | limit-candidate-ks-to-those-with-at-leas-im48 | Intuition & Approach\n Describe your approach to solving the problem. \nInstead of only computing candidate k\'s using the smallest element of nums, we compute | jyscao | NORMAL | 2024-05-21T17:29:30.279209+00:00 | 2024-05-21T17:29:30.279233+00:00 | 2 | false | # Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\nInstead of only computing candidate `k`\'s using the smallest element of `nums`, we compute all pairwise differences between all elements of `nums`, while tracking their counts. Valid candidate `k`\'s must have counts of at least `n`, the length of the original array.\n\n# Code\n```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n\n # get counts of all possible pairwise differences\n N, diff_cnts = len(nums) // 2, Counter()\n for i in range(2 * N):\n for j in range(i):\n diff_cnts[nums[i] - nums[j]] += 1\n\n # candidates for 2k must have a difference-count of >= number of elements\n # in the original array, and the difference value must be an even integer\n candidate_k2s = sorted([(dc, dv) for dv, dc in diff_cnts.items() if dv % 2 == 0 and dc >= N], reverse=True)\n\n nc = Counter(nums)\n for _, k2 in candidate_k2s:\n arr, ncc = [], copy.copy(nc)\n\n for x in nums:\n if ncc[x] == 0:\n continue\n\n # there is a corresponding higher[i] to the current x as the lower[i]\n if x + k2 in ncc and ncc[x + k2] > 0:\n arr.append(x + k2 // 2)\n ncc[x] -= 1\n ncc[x + k2] -= 1\n # there isn\'t, thus we stop matching early for the current `k`\n else:\n break\n\n # all lower[i] & higher[i] elements in `nums` have been accounted for using\n # the current value of `k`, thus the reconstructed `arr` is a valid answer\n if len(arr) == N and ncc.total() == 0:\n return sorted(arr)\n``` | 0 | 0 | ['Sorting', 'Counting', 'Python3'] | 0 |
recover-the-original-array | rust 13ms simple solution with explain | rust-13ms-simple-solution-with-explain-b-w8fk | \n\n\n# Intuition\nSort the array. For the first item and any other item, their differenca can be a $2k$. For every possible $k$, verify the nums weather this $ | sovlynn | NORMAL | 2024-05-09T18:50:49.227679+00:00 | 2024-05-09T18:50:49.227706+00:00 | 0 | false | \n\n\n# Intuition\nSort the array. For the first item and any other item, their differenca can be a $2k$. For every possible $k$, verify the nums weather this $k$ can recover the array.\n\nSince the array is sorted, the programm will always meet the $arr[i]-k$ before $arr[i]+k$. So you can assume if you meet some number not registered, it adds $k$ is an element in the array. Then register it adds $2*k$ and expect you may meet it in the future. After the scan, there are no any number registered to be met, it is valid.\n\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nuse std::collections::VecDeque;\n\nimpl Solution {\n pub fn recover_array(nums: Vec<i32>) -> Vec<i32> {\n let mut nums=nums.clone();\n nums.sort_unstable();\n for i in 1..nums.len(){\n if (nums[i]-nums[0])%2!=0||nums[i]==nums[0]{continue;}\n let k=(nums[i]-nums[0])/2;\n match Self::velify(&nums, k){\n Some(res)=>{return res;}\n None=>()\n }\n }\n Vec::new()\n }\n\n fn velify(nums: &Vec<i32>, k: i32)->Option<Vec<i32>>{\n let mut res=Vec::new();\n let mut to_match=VecDeque::new();\n for &i in nums{\n if to_match.len()==0||to_match[0]!=i{\n to_match.push_back(i+k*2);\n res.push(i+k);\n }else{\n to_match.pop_front();\n }\n // early return to save time\n if res.len()>nums.len()/2{return None;}\n }\n // theoretically every invalid array will cause early return\n // the else branch will never be select\n if to_match.len()==0{Some(res)}else{None}\n }\n}\n\n``` | 0 | 0 | ['Rust'] | 0 |
recover-the-original-array | JS Solution | js-solution-by-nanlyn-0w77 | Code\n\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar recoverArray = function (nums) {\n nums.sort((a, b) => (a - b));\n\n for (let i = | nanlyn | NORMAL | 2024-05-04T17:42:31.152494+00:00 | 2024-05-04T17:42:31.152510+00:00 | 2 | false | # Code\n```\n/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar recoverArray = function (nums) {\n nums.sort((a, b) => (a - b));\n\n for (let i = 1; i <= nums.length / 2; i++) {\n let twiceK = nums[i] - nums[0];\n if (twiceK === 0 || twiceK % 2 === 1) continue;\n let result = [];\n let map = new Map();\n for (let num of nums) {\n let count = map.get(num - twiceK);\n if (!count) {\n map.set(num, (map.get(num) || 0) + 1);\n } else {\n result.push(num - twiceK / 2);\n map.set(num - twiceK, count - 1);\n }\n }\n if (result.length === nums.length / 2) {\n return result;\n }\n }\n\n return [];\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
recover-the-original-array | C++ || CLEAN SHORT CODE || GREEDY | c-clean-short-code-greedy-by-gauravgeekp-1eb1 | \n\n# Code\n\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& a) {\n sort(a.begin(),a.end());\n vector<int> v;\n for(i | Gauravgeekp | NORMAL | 2024-04-30T07:06:43.464497+00:00 | 2024-04-30T07:06:43.464533+00:00 | 17 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& a) {\n sort(a.begin(),a.end());\n vector<int> v;\n for(int i=1;i<=a.size()/2;i++)\n if(a[i]-a[0]!=0 && a[i]-a[0]!=1 && (a[i]-a[0])%2==0) v.push_back(a[i]-a[0]);\n \n int n=a.size()/2;\n for(auto i : v)\n {\n vector<int> r,f;int c=0;\n unordered_map<int,int> p;\n for(int j=0;j<2*n;j++)\n {\n if(p.count(a[j]-i)){\n f.push_back(a[j]);\n p[a[j]-i]--;\n if(p[a[j]-i]==0) p.erase(a[j]-i);\n }\n else\n {\n p[a[j]]++;\n r.push_back(a[j]);\n }\n }\n bool b=1;\n if(f.size()==r.size())\n {\n for(int j=0;j<n;j++)\n if(f[j]-r[j]!=i) b=0;\n \n if(b)\n {\n for(int j=0;j<n;j++) r[j]=(r[j]+i/2);\n return r;\n }\n }\n } \n return {};\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
recover-the-original-array | Easy to understand || Using map and sorting || c++ | easy-to-understand-using-map-and-sorting-gim0 | 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 | Yuvraj161 | NORMAL | 2024-04-13T11:42:03.140805+00:00 | 2024-04-13T11:42:03.140832+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 log n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n=nums.size(),a=INT_MAX,b=INT_MAX;\n sort(nums.begin(),nums.end());\n for(int i=1;i<n;i++){\n int k=(nums[i]-nums[0])%2==1 ? -1:(nums[i]-nums[0])/2;\n if(k<=0) continue;\n\n map<int,int> mp;\n vector<int> v;\n for(int j=0;j<n;j++){\n if(mp.find(nums[j])!=mp.end()){\n v.push_back(nums[j]-k);\n mp[nums[j]]--;\n if(mp[nums[j]]==0) mp.erase(nums[j]);\n } else {\n mp[nums[j]+2*k]++;\n }\n }\n\n if(v.size()==n/2 && mp.size()==0) return v;\n }\n\n return {};\n }\n};\n``` | 0 | 0 | ['Array', 'Hash Table', 'Math', 'Greedy', 'Sorting', 'Enumeration', 'C++'] | 0 |
recover-the-original-array | Clear typescript solution (beats 100%) | clear-typescript-solution-beats-100-by-i-e1bd | 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 | igor_muram | NORMAL | 2024-01-25T14:08:02.539836+00:00 | 2024-01-25T14:28:44.295275+00:00 | 4 | 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\n- Space complexity: $$O(n)$$\n\n# Code\n```\nfunction recoverArray(nums: number[]): number[] {\n nums = nums.sort((a, b) => a - b)\n const half: number = nums.length / 2\n\n const getResultForK = (k: number): number[] => {\n const result: number[] = []\n\n const counts: Map<number, number> = nums.reduce((acc, cur) => {\n acc.set(cur, (acc.get(cur) || 0) + 1)\n return acc\n }, new Map<number, number>())\n\n for (let num of nums) {\n if (counts.get(num) === 0) {\n continue\n }\n\n if (counts.get(num + k) === 0) {\n return []\n }\n\n counts.set(num, counts.get(num) - 1)\n counts.set(num + k, counts.get(num + k) - 1)\n\n result.push(num + k / 2)\n }\n\n if (result.length !== half) {\n return []\n }\n\n return result\n }\n\n for (let i = 1; i <= half; i++) {\n const k: number = nums[i] - nums[0]\n\n if (k !== 0 && k % 2 === 0) {\n const result = getResultForK(k)\n\n if (result.length > 0) {\n return result\n }\n }\n }\n}\n``` | 0 | 0 | ['TypeScript'] | 0 |
recover-the-original-array | Try all possible k values | try-all-possible-k-values-by-user1675rq-lpnd | Intuition\nBrute force try all possible k values, don\'t try impossible solutions or duplicates.\n\n# Approach\nFirst get all the potential k values for the fir | user1675rQ | NORMAL | 2024-01-04T03:31:52.901999+00:00 | 2024-01-04T03:31:52.902023+00:00 | 2 | false | # Intuition\nBrute force try all possible k values, don\'t try impossible solutions or duplicates.\n\n# Approach\nFirst get all the potential k values for the first entry in the array, one of them must be the right one.\n\nNext try to eliminate the pairs of values from the input corresponding to x - k, x + k recording x as you go. If all the values were eliminated, that\'s a solution.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nfunc copyMap(orig map[int]int) map[int]int {\n copy := make(map[int]int, len(orig))\n\n\tfor key, value := range orig {\n\t\tcopy[key] = value\n\t}\n return copy\n}\n\nfunc decrement(lookup map[int]int, key int) {\n if _, ok := lookup[key]; ok {\n lookup[key]--\n if lookup[key] == 0 {\n delete(lookup, key)\n }\n }\n\n}\n\nfunc recoverArray(nums []int) []int {\n sort.Ints(nums)\n sampleSpace := make(map[int]struct{}, len(nums) - 1)\n lookup := make(map[int]int, len(nums))\n lookup[nums[0]] = 1\n for i := 1; i < len(nums); i++ {\n if _, ok := lookup[nums[i]]; !ok {\n lookup[nums[i]] = 0\n }\n lookup[nums[i]]++\n diff := int(math.Abs(float64(nums[i] - nums[0])))\n if diff % 2 == 0 && diff != 0 {\n sampleSpace[diff / 2] = struct{}{}\n }\n }\n\n for k, _ := range sampleSpace {\n lookupCopy := copyMap(lookup)\n candidate := []int{}\n for _, num := range nums {\n if _, ok := lookupCopy[num]; !ok {\n continue\n }\n val := num + k * 2\n decrement(lookupCopy, num)\n if _, ok := lookupCopy[val]; ok {\n candidate = append(candidate, val - k)\n decrement(lookupCopy, val)\n } else {\n break\n }\n }\n if len(lookupCopy) == 0 {\n return candidate\n }\n }\n\n return []int{}\n}\n``` | 0 | 0 | ['Go'] | 0 |
recover-the-original-array | Easy to understand CPP Solution || Using map and sorting | easy-to-understand-cpp-solution-using-ma-83zv | Intuition\nsort the nums array and store all the values of nums in the map\nthen calculate each posible value of k wrt nums[0].\n\n# Approach\n1 -> sort the nu | Joshiiii | NORMAL | 2023-11-17T10:18:14.025591+00:00 | 2023-11-17T10:18:14.025619+00:00 | 35 | false | # Intuition\nsort the nums array and store all the values of nums in the map\nthen calculate each posible value of k wrt nums[0].\n\n# Approach\n1 -> sort the nums array\n2 -> store all the values of nums in the map\n3 -> calculate all posible values of k\n4 -> check for all values of K that the solution exists or not.\n\n\n# Code\n```\nclass Solution {\npublic:\n \n bool solve(int k, unordered_map<int, int> mp, vector<int> & nums, vector<int> &ans) {\n int n = nums.size();\n int i = 0;\n \n for(int i=0; i<n; i++){\n if(mp[nums[i]] > 0) {\n mp[nums[i]]--;\n int next = nums[i] + 2*k;\n if(mp[next] > 0) {\n mp[next]--;\n ans.push_back(nums[i] + k);\n }\n else\n return false;\n }\n }\n return true;\n }\n \n vector<int> recoverArray(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n vector<int> AllValuesOfK;\n unordered_map<int, int> mp;\n \n // storing all values in map...\n for(auto it : nums) {\n mp[it]++;\n }\n \n // calculating all posible values of K...\n for(int i=1; i<n; i++) {\n int diff = nums[i] - nums[0]; // checking for all values of k wrt nums[0].\n if(diff > 0 && diff % 2 == 0)\n AllValuesOfK.push_back(diff/2); // divided by 2 because the values are either (nums[i]+k) or (nums[i]-k)..\n }\n \n int sz = AllValuesOfK.size();\n // check for all values of K..\n for(int i=0; i<sz; i++) {\n vector<int> ans;\n if(solve(AllValuesOfK[i], mp, nums, ans))\n return ans;\n }\n return {};\n }\n};\n``` | 0 | 0 | ['Hash Table', 'Greedy', 'Sorting', 'C++'] | 0 |
recover-the-original-array | fast solution | fast-solution-by-punyreborn-b4t5 | 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 | punyreborn | NORMAL | 2023-11-05T08:37:07.677809+00:00 | 2023-11-05T08:37:07.677826+00:00 | 3 | 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)$$ -->\nsort: $$O(NlogN)$$\nfind: $$O(N)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n\n# Code\n```\nfunc recoverArray(nums []int) []int {\n sort.Ints(nums)\n n:=len(nums)-1\n k1,k2 := (nums[1]-nums[0])/2, (nums[n]-nums[0])/2\n if k1==0 {\n k1=1\n }\n dict := make(map[int][]int)\n\n for i:=0;i<=n;i++ {\n if _,ok:= dict[nums[i]];!ok {\n dict[nums[i]]=make([]int,0)\n }\n dict[nums[i]]=append(dict[nums[i]],i)\n }\n\n for k:=k1;k<=k2;k++ {\n seen := make(map[int]bool)\n res := make([]int,0)\n f := true\n for i:=0;i<=n;i++ {\n if seen[i] {\n continue\n }\n seen[i]=true\n t := nums[i]+2*k\n if v,ok:=dict[t];!ok {\n f= false\n break\n }else {\n j := len(v)-1 \n for j>=0 && seen[v[j]] {\n j--\n }\n if j< 0 {\n f= false\n break\n }\n tail := v[j]\n seen[tail]=true\n res=append(res,nums[i]+k)\n }\n }\n\n if f {\n return res\n }\n\n // if len(res)== len(nums)/2 {\n // return res\n // }\n }\n return []int{}\n\n}\n\n\n\n\n``` | 0 | 0 | ['Go'] | 0 |
recover-the-original-array | My Solutions | my-solutions-by-hope_ma-con5 | 1. Use the std::unordered_map2. Don't use the std::unordered_map | hope_ma | NORMAL | 2023-07-14T04:56:08.480714+00:00 | 2025-02-01T00:58:17.022690+00:00 | 8 | false | **1. Use the `std::unordered_map`**
```
/**
* Time Complexity: O(n * n)
* Space Complexity: O(n)
* where `n` is the length of the vector `nums`
*/
class Solution {
public:
vector<int> recoverArray(vector<int> &nums) {
const int n = static_cast<int>(nums.size()) >> 1;
sort(nums.begin(), nums.end());
unordered_map<int, int> num_to_count;
for (const int num : nums) {
++num_to_count[num];
}
vector<int> ret;
for (int i = 1; i < n + 1; ++i) {
const int twice_k = nums[i] - nums.front();
if (twice_k > 0 && twice_k % 2 == 0 && valid(nums, num_to_count, twice_k, ret)) {
return ret;
}
}
throw "impossible path";
}
private:
bool valid(const vector<int> &nums, unordered_map<int, int> num_to_count, const int twice_k, vector<int> &result) {
for (const int lower : nums) {
auto itr_lower = num_to_count.find(lower);
if (itr_lower == num_to_count.end()) {
continue;
}
const int lower_count = itr_lower->second;
const int higher = lower + twice_k;
auto itr_higher = num_to_count.find(higher);
if (itr_higher == num_to_count.end() || itr_higher->second < lower_count) {
result.clear();
return false;
}
for (int i = 0; i < lower_count; ++i) {
result.emplace_back((lower + higher) >> 1);
}
num_to_count.erase(itr_lower);
if ((itr_higher->second -= lower_count) == 0) {
num_to_count.erase(itr_higher);
}
}
return true;
}
};
```
**2. Don't use the `std::unordered_map`**
```
/**
* Time Complexity: O(n * n)
* Space Complexity: O(n)
* where `n` is the length of the vector `nums`
*/
class Solution {
public:
vector<int> recoverArray(vector<int> &nums) {
const int n = static_cast<int>(nums.size()) >> 1;
sort(nums.begin(), nums.end());
vector<int> ret;
for (int i = 1; i < n + 1; ++i) {
const int twice_k = nums[i] - nums.front();
if (twice_k > 0 && (twice_k & 1) == 0) {
ret.clear();
bool visited[n << 1];
memset(visited, 0, sizeof(visited));
int i_lower = 0;
int i_higher = i;
while (ret.size() < n &&
i_higher < (n << 1) &&
nums[i_higher] - nums[i_lower] == twice_k) {
visited[i_lower] = true;
visited[i_higher] = true;
ret.emplace_back(nums[i_lower] + (twice_k >> 1));
for (; i_lower < (n << 1) && visited[i_lower]; ++i_lower) {
}
for (;
i_higher < (n << 1) && (visited[i_higher] || nums[i_higher] < nums[i_lower] + twice_k);
++i_higher) {
}
}
if (ret.size() == n) {
return ret;
}
}
}
throw "impossible path";
}
};
``` | 0 | 0 | ['C++'] | 0 |
recover-the-original-array | Simple approach | Using map and all possible values of K | C++ Solution | simple-approach-using-map-and-all-possib-sngv | Intuition\n Describe your first thoughts on how to solve this problesm. \nFinding all the possible values of K from the nums and then using map tp find out whet | ayushpanday612 | NORMAL | 2023-06-30T20:26:27.760902+00:00 | 2023-06-30T20:26:27.760940+00:00 | 68 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problesm. -->\nFinding all the possible values of K from the nums and then using map tp find out whether given vlue of K is posiible or not.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStep 1: Sort nums.\nStep 2: Storing all possible values of K by finding (nums[i]-nums[0])/2;\nStep 3: Storing frequency of each element of nums in unordered map.\nStep 4: Using map to figure out whether given value of K is valid.\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 /* void solve(int ans)\n {\n ans = ans - 1;\n cout<<ans<<"\\n";\n }*/\n \n int solve(unordered_map<int , int> m , vector<int>& ans , int k , vector<int>&nums)\n {\n \n int i,j,l , p;\n p = 0;\n for(i=0;i<=nums.size()-1;i++)\n {\n if(m[nums[i]]>0)\n {\n cout<<"here"<<"\\n";\n m[nums[i]]--;\n l= nums[i] +2*k;\n if(m[l]>0)\n {\n m[l]--;\n \n ans.push_back(nums[i] + k);\n }else{\n p = -1;\n break;\n }\n \n \n \n \n \n }\n }\n if(ans.size()>0)\n { for(i=0;i<=ans.size()-1;i++)\n {\n cout<<ans[i]<<" ";\n }}\n if(p==-1)\n {\n return -1;\n }\n return 1;\n \n \n }\n vector<int> recoverArray(vector<int>& nums) {\n int i,j,k,l;\n vector<int> ans;\n vector<int> v;\n sort(nums.begin() , nums.end());\n \n for(i =1;i<=nums.size()-1;i++)\n {\n if((nums[i]-nums[0])%2==0)\n {\n k = (nums[i] - nums[0])/2;\n if(k>0)\n {v.push_back(k);}\n }\n }\n \n unordered_map<int, int> m;\n for(i=0;i<=nums.size()-1;i++)\n {\n m[nums[i]]++;\n }\n l =-1;\n for(i=0;i<=v.size()-1;i++)\n {\n vector<int> v1;\n \n if(solve(m ,v1 , v[i] ,nums)==1)\n {\n cout<<v[i]<<"\\n";\n \n return v1;\n break;\n }\n }\n return ans;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
recover-the-original-array | 85+ in speed and memory using Python3 | 85-in-speed-and-memory-using-python3-by-ok5os | 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 | ranilmukesh | NORMAL | 2023-06-19T14:55:52.521841+00:00 | 2023-06-19T14:55:52.521860+00:00 | 30 | 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```\nfrom collections import Counter\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n smallest, largest = nums[0], nums[-1]\n nums_counter = Counter(nums)\n knums = list(nums_counter.keys())\n\n for knum in knums[1:]:\n K = knum - smallest\n if K & 1 or smallest + K not in nums_counter or largest - K not in nums_counter:\n continue\n \n ans = []\n numsc = nums_counter.copy()\n \n for num in knums:\n if numsc[num] == 0:\n continue\n if num + K not in numsc or numsc[num + K] == 0:\n break\n \n count = min(numsc[num], numsc[num + K]) \n numsc[num] -= count\n numsc[num + K] -= count\n\n ans += [num + K//2]*count\n \n if len(ans) == len(nums) // 2:\n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
recover-the-original-array | C++ Hash Table Sorting | c-hash-table-sorting-by-tejaswibishnoi-pq3o | Intuition\n Describe your first thoughts on how to solve this problem. \nThe first thought we may have by looking a this question may have binary search. But as | TejaswiBishnoi | NORMAL | 2023-05-24T17:08:07.960216+00:00 | 2023-05-24T17:08:07.960255+00:00 | 66 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thought we may have by looking a this question may have binary search. But as we see, we have no criteria to decide when to move left or right in binary search. But by looking at the question, we can see the relation between the elements. Each element is either some element + 2k or - 2k. All we have to do is to find a k that fits. But how can we check if a k fits? Also, how to find possible values of k?\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe answer to the first question is, we can check if k satisfies if we take all unique elements of the nums in a sorted order in a array called **vec**. Also we need to store the number of times the unique value has been repeated. To store this we can use an unordered_map called **mp**. Now, when we iterate over the sorted unique values, we check if for any **unique value vec[i]**, does there exist an vec[i] + 2k, as we have already seen the relation. If not, then the k is wrong. Else, we can subtract 1 from the mp[vec[i] + 2k] for each occurence of vec[i]. If we successfully iterate the whole array, then the k is correct. The reason to sort is, we now do not need to care about vec[i] -2k as they have already been visited and they have compensated from vec[i].\n\nComing to the second question, how to find possible values of k? For vec[0], there must exist some vec[i] such that vec[i] - vec[0] = 2k, where k is valid, as we there is a guarantee that a valid k exists. So we start iterating from i = 1 to i = vec.size() - 1. For each i, we take a possible value of k = (vec[i] - vec[0])/2. We test for this k. If successful, we are done and found a k. Else we try for next value.\n\n**Now, how to find the original array from this k?** We so something similar to the first question, the one where we define the test of k. But here instead of checking if k is correct, we know the k is correct. We take another array to store result called res. In the verification, we subtract 1 from mp[vec[i + 2k]] for each mp[vec[i]], we do the same here, **but we also push vec[i] + k in res for each mp[vec[i]]**. This way the res array contains the final solution.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe sorting of vec array takes $$O(nlogn)$$ time. Finding possible values of k and testing them takes $$O(n^2)$$ time. All unordered map operations are of $$O(1)$$. Obtaining final array takes $$O(n)$$ time. Hence the time complexity is $$O(n^2)$$. \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe additional space required is order of $$O(n)$$.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) { \n unordered_map<int, int> m; \n for (auto x: nums) m[x]++;\n int ans = -1;\n vector<int> vec;\n for (auto it = m.begin(); it != m.end(); it++) vec.push_back(it->first);\n sort(vec.begin(), vec.end());\n int n = vec.size();\n for (int i = 1; i < (n); i++){\n int val = vec[i] - vec[0];\n if (val&1) continue;\n unordered_map<int, int> mp;\n mp.insert(m.begin(), m.end());\n bool fail = false;\n for (auto x: vec){\n if (mp[x] == 0) continue;\n auto it = mp.find(x + val);\n if (it == mp.end() || mp[x] > it->second){\n fail = true;\n break;\n } \n it->second -= mp[x];\n mp[x] = 0;\n }\n if (!fail){\n ans = val;\n break;\n } \n }\n vector<int> res;\n //cout << ans;\n int val = ans/2;\n for (auto x: vec){\n if (m[x] == 0) continue;\n //cout << ans << " "; \n int clc = x + val;\n auto it = m.find(x + ans);\n it->second -= m[x];\n int z = m[x];\n m[x] = 0;\n while (z--){\n res.push_back(clc);\n }\n }\n return res;\n }\n};\n``` | 0 | 0 | ['Hash Table', 'Sorting', 'C++'] | 0 |
recover-the-original-array | Java || Like leetcode 954 and 2007 || HashMap || With comments | java-like-leetcode-954-and-2007-hashmap-maypl | // b <=============2122. Recover the Original Array ============>\n // https://leetcode.com/problems/recover-the-original-array/description/\n\n // Consid | JoseDJ2010 | NORMAL | 2023-05-07T03:10:09.570347+00:00 | 2023-05-07T03:10:09.570399+00:00 | 27 | false | // b <=============2122. Recover the Original Array ============>\n // https://leetcode.com/problems/recover-the-original-array/description/\n\n // Consider [a,b,c,d] to be the original array.\n // [a-k,b-k,c-k,d-k] will be the lower array\n // [a+k,b+k,c+k,d+k] will be the higher array.\n\n // Humne agar array ko sort kiya, to hume pata hai ki nums[0] humesha lower\n // array mai he aayega, kyunki wo smallest value hogi.\n\n // So consider a-k to be the smallest element in the sorted array.\n // then (a+k)- (a-k)=2k.\n\n // We know that (a-k) is nums[0].\n\n // So the formula becomes (nums[i] - nums[0]) /2 for getting the various values\n // of k.\n\n // Now for each values of k, check if all the pairs are formed. If yes, then\n // return the array.\n\n```\npublic int[] recoverArray(int[] nums) {\n\n HashMap<Integer, Integer> map = new HashMap<>();\n int n = nums.length;\n for (int ele : nums) {\n map.put(ele, map.getOrDefault(ele, 0) + 1); // getting the frequency.\n }\n\n Arrays.sort(nums);\n\n int[] ans = new int[n / 2];\n for (int i = 1; i < n; i++) {\n int k = (nums[i] - nums[0]) / 2; // getting all the values of k.\n\n if (k <= 0)\n continue; // k cannot be -ve or 0.\n\n HashMap<Integer, Integer> cmap = new HashMap<>(map);\n int idx = 0;\n for (int ele : nums) {\n if (cmap.get(ele) == 0) // Agar kisi element ki frequency 0 hai, to wo already paired hai.\n continue;\n\n int higher = ele + 2 * k;\n int lower = ele - 2 * k;\n\n // If a elements gets paired, then we are decreasing the frequency of both\n // elements of the pair.\n if (cmap.getOrDefault(higher, 0) > 0) {\n cmap.put(ele, cmap.get(ele) - 1);\n cmap.put(higher, cmap.get(higher) - 1);\n ans[idx++] = ele + k;\n } else if (cmap.getOrDefault(lower, 0) > 0) {\n cmap.put(ele, cmap.get(ele) - 1);\n cmap.put(lower, cmap.get(lower) - 1);\n ans[idx++] = ele - k;\n } else {\n // if the higher or lower cease to exist in the map, then the k value is wrong.\n break;\n }\n }\n\n // if all the values are paired, then idx will reach to n/2.\n if (idx == n / 2)\n return ans;\n }\n\n return new int[] {};\n }\n```\n\n\n // b <==========954. Array of Doubled Pairs ==========>\n // https://leetcode.com/problems/array-of-doubled-pairs/description/\n\n // [0,0,2,4,1,8], [-16,-2,-8,-4] : Test cases to dry run\n\n // Hume basically yahan pe pucha hai ki can we rearrange array such that array\n // ` becomes like [a,2a,b,2b,c,2c,d,2d].\n\n // So hume basically har ek element ke liye uska pair dhundhna hai. Aur agar har\n // ek element ke liye uska pair mil jata hai to wo rearrange ho sakta hai.\n\n // Humne hashmap mai har ek element ki frequency nikali\n // Ab agar humne array ko normally sort kiya to hume array aise milega.\n // -16,-8,-4,-2,0,0,1,2,4,8,. Jisme hume -ve elements ke liye unka half check\n // karna padega aur +ve elements ke liye unka double.\n\n // Ab agar mai chahta hun ki mujhe har element ka double he check karna page, to\n // isiliye maine Arr ko apne hisab se sorrt karunga. To do this, mujhe Apna ek\n // Integer class ka array banana padega since int is a primitive type.\n\n // So now the array will be sorted like treating the -ve number as +ve.\n\n // 0,0,1,2,-2,4,-4,-8,8,-16.\n\n```\npublic boolean canReorderDoubled(int[] arr) {\n\n int n = arr.length;\n Integer[] Arr = new Integer[n];\n HashMap<Integer, Integer> map = new HashMap<>();\n\n for (int i = 0; i < n; i++) {\n map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);\n Arr[i] = arr[i];\n }\n\n Arrays.sort(Arr, (a, b) -> { // Sorting the array as if the -ve number are +ve.\n return Math.abs(a) - Math.abs(b);\n });\n\n for (int ele : Arr) {\n if (map.get(ele) == 0) // If frequency is zero, the element has already been paired.\n continue;\n if (map.getOrDefault(ele * 2, 0) <= 0) // If we cannot find a 2*ele, we cannot pair this element. Hence\n // returning false.\n return false;\n\n // Since a pairing requires both elements, decreasing the frequency of both the\n // elements of the pair.\n map.put(ele, map.get(ele) - 1);\n map.put(2 * ele, map.get(ele * 2) - 1);\n }\n\n return true;\n }\n```\n\n \n// b <=========== 2007. Find Original Array From Doubled Array ==========>\n // https://leetcode.com/problems/find-original-array-from-doubled-array/description/\n\n // # Logic is same as above.\n // # But here no -ve elements, so just normally sort the array.\n\n```\npublic int[] findOriginalArray(int[] arr) {\n\n int n = arr.length;\n if (n % 2 == 1)\n return new int[] {};\n HashMap<Integer, Integer> map = new HashMap<>();\n for (int ele : arr)\n map.put(ele, map.getOrDefault(ele, 0) + 1);\n\n Arrays.sort(arr);\n\n int[] ans = new int[n / 2];\n int i = 0;\n for (int ele : arr) {\n if (map.get(ele) == 0)\n continue;\n\n if (map.getOrDefault(ele * 2, 0) <= 0)\n return new int[] {};\n\n map.put(ele, map.get(ele) - 1);\n map.put(2 * ele, map.get(ele * 2) - 1);\n ans[i++] = ele;\n }\n return ans;\n }\n\n``` | 0 | 0 | ['Java'] | 0 |
recover-the-original-array | Ruby Solution in O(n^2) (100%/100%) | ruby-solution-in-on2-100100-by-dtkalla-jxwd | Intuition\nIt\'s easy to check if a possible value of k works, and to create the array if you know k. Find all possible values of k, find one that works, and g | dtkalla | NORMAL | 2023-04-30T00:12:01.301432+00:00 | 2023-04-30T00:12:01.301477+00:00 | 15 | false | # Intuition\nIt\'s easy to check if a possible value of k works, and to create the array if you know k. Find all possible values of k, find one that works, and generate the array.\n\n# Approach\n1. Sort the numbers (to better iterate later)\n2. Find how often each number occurs in the array\n3. Find the possibilities for j. (I\'m using j to represent 2k. Note that j must be even. Also, it can\'t be 0, so we shift to remove 0 from the array.)\n4. Check possible j values until finding one that works\n a. Start with the first element ele, and decrement ele and ele + j in the count. If this isn\'t possible, the value of j is wrong.\n b. Go through the rest of the elements in the array (as long as they haven\'t been removed yet). If you get through all the elements, return true.\n5. Find the array for that j value\n a. Basically the same process as checking j, but in addition to decrementing the count, add ele + k to an array.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\ndef recover_array(nums)\n nums.sort!\n count = Hash.new(0)\n nums.each { |num| count[num] += 1 }\n\n possibilities = nums.uniq.map { |num| num - nums[0] }\n possibilities.shift\n possibilities.reject! { |j| j % 2 == 1 }\n\n j = false\n i = 0\n\n until j\n if valid?(nums,count.dup,possibilities[i])\n j = possibilities[i]\n end\n i += 1\n end\n\n find_arr(nums,count,j)\nend\n\ndef valid?(nums,count,j)\n n = nums.length / 2\n i = 0\n\n while n > 0\n if count[nums[i]] > 0\n count[nums[i]] -= 1\n count[nums[i] + j] -= 1\n return false if count[nums[i] + j] < 0\n n -= 1\n end\n i += 1\n end\n true\nend\n\ndef find_arr(nums,count,j)\n arr = []\n n = nums.length / 2\n k = j / 2\n i = 0\n\n while n > 0\n if count[nums[i]] > 0\n count[nums[i]] -= 1\n count[nums[i] + j] -= 1\n arr << nums[i] + k\n n -= 1\n end\n i += 1\n end\n arr\nend\n``` | 0 | 0 | ['Ruby'] | 0 |
recover-the-original-array | Python Counter: Use it to its fullest. 98ms, fastest solution yet... for slow python. | python-counter-use-it-to-its-fullest-98m-ukxy | Intuition\n Describe your first thoughts on how to solve this problem. \nMany solutions here cleverly create a counter, and yet iterate through each num in the | cswartzell | NORMAL | 2023-04-21T05:41:15.581078+00:00 | 2023-04-21T06:00:57.534776+00:00 | 34 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMany solutions here cleverly create a counter, and yet iterate through each num in the full array to subtract matching pairs. We can do a little better though. Since we *have* the counter, we can iterate through that instead and remove whole chunks of matched sets in one step\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe same basic O(n^2) solution in most other posts, with a twist. Iterate through counter keys rather than the num array. Subtract counter vals to account for EVERY match of num and num + k in one step.\n\nIts a pretty minor optimization, but is neat and you may as well. \n\n\nOriginally I did try deleting key:val pairs in the dict so the dictionary actually gets smaller, and we can exit once its empty (knowing we have the right answer), but this is slower than just checking if the value in the dict == 0. \n\n# Complexity\nInstead of O(n^2), this is technically O(len(counter.keys())^2), though worst case that IS O(n^2). It improves the average and best case analysis though. \n\n\n# Code\n```\nfrom collections import Counter\n\n\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n smallest, largest = nums[0], nums[-1]\n nums_counter = Counter(nums)\n knums = list(nums_counter.keys())\n\n for knum in knums[1:]:\n #technically this is 2k here, but thats less useful.\n #Lets say K = 2k\n K = knum - smallest\n #We know smallest MUST be in the LOWER array, so smallest + K must exist or we have the wrong K. \n # Same logic for largest. We can directly test this and maybe stop early\n # This test accounts for hundreds of ms in runtime speedup\n if K & 1 or smallest + K not in nums_counter or largest - K not in nums_counter:\n continue\n \n #make new copies, dont recreate the counter each time. \n ans = []\n numsc = nums_counter.copy()\n \n for num in knums:\n #already accounted for all these\n if numsc[num] == 0:\n continue\n #Wrong K\n if num + K not in numsc or numsc[num + K] == 0:\n break\n\n #Update ALL matched pairs in one step \n count = min(numsc[num], numsc[num + K]) \n numsc[num] -= count\n numsc[num + K] -= count\n\n # Need to add count many copies of our new num\n ans += [num + K//2]*count\n \n if len(ans) == len(nums) // 2:\n return ans \n\n\n``` | 0 | 0 | ['Python3'] | 0 |
recover-the-original-array | Python. Beats 100%. | python-beats-100-by-russdt-a8ns | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nsort nums\n\ncreate a d | russdt | NORMAL | 2022-12-30T21:55:04.121956+00:00 | 2022-12-30T21:55:04.121996+00:00 | 142 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsort nums\n\ncreate a dictionary with Counter of all vals\n\ncreate a test array testing abs(nums[0] - nums[i]) for i in range(1,n//2+1)\n\nthe n//2+1 upperbound is included because if n == 10, and nums is sorted, for nums[0], the maximum index for which nums[0] could be paired up with is nums[5]. \n\nThen run a for loop testing each possibility. the difference has to be divisible by 2 and > 1. Divisible by 2 because the differences we are testing are 2*k, so if the differnece is 7, k would have to be 3.5 which is not an integer and invalid.\n\ni copy the dicitonary, and -=1 in the copied dictionary for each [val] and [val + c], and i break the forloop as soon i encounter a [val+c] either not in dictionary or with value 0. \n\nbreak the testing for loop as soon as you identify a value that will work, then build the array bestans.\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 def recoverArray(self, nums: List[int]) -> List[int]:\n from collections import Counter\n nums.sort()\n n = len(nums)\n vals = Counter(nums)\n \n test = [abs(x-nums[0]) for x in nums[1:len(nums)//2+1]]\n \n ans = 0\n for c in test:\n if c % 2 != 0 or c==0:\n continue\n cvals = dict(vals)\n flag = 0\n for num in nums:\n if cvals[num] > 0:\n if num+c in cvals and cvals[num + c] > 0:\n cvals[num] -= 1\n cvals[num+c] -= 1\n else:\n flag = 1\n break\n if not flag:\n ans = c\n break\n \n bestans = []\n for num in nums:\n if vals[num] > 0:\n bestans.append(num+ans//2)\n vals[num] -= 1\n vals[num+c] -= 1\n \n return bestans\n \n \n \n``` | 0 | 0 | ['Python', 'Python3'] | 0 |
recover-the-original-array | Dart implementation, O(N^2) | dart-implementation-on2-by-yakiv_galkin-djkt | Intuition\nIf we sort the array, the very first(i.e. min) element will belong to the low array, while one of the i-th elements belongs to the high array.\nSo we | yakiv_galkin | NORMAL | 2022-12-13T02:47:09.898109+00:00 | 2022-12-13T02:47:09.898152+00:00 | 20 | false | # Intuition\nIf we sort the array, the very first(i.e. min) element will belong to the low array, while one of the i-th elements belongs to the high array.\nSo we can iterate trough difference b/w first and i-th element and check our array for the match.\n\n# Approach\nUse containers (splay tree map and hash map) to efficiently find pair element within O(N^2)\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N)\n\n# Code\n```\n\nimport \'dart:collection\';\n\nclass Solution {\n List<int> recoverArray(List<int> nums) {\n final nm = SplayTreeMap<int, int>();\n nums.forEach((n) { // n * log(n)\n if (!nm.containsKey(n))\n nm[n] = 1;\n else\n nm[n] = nm[n]! + 1;\n });\n\n int low = nm.firstKey()!;\n for (int high in nm.keys) // N\n {\n int k = high - low;\n if (k == 0 || k % 2 != 0) continue;\n final check = Map<int, int>.fromEntries(nm.entries);\n bool passed = true;\n for (var v in nm.keys) { // * N\n if (check[v] == 0) continue;\n if (!check.containsKey(v + k) || check[v + k]! < check[v]!) {\n passed = false;\n break;\n }\n check[v + k] = check[v + k]! - check[v]!;\n }\n if (passed) {\n return check.entries\n .where((e) => e.value != 0)\n .map((e) => List.generate(e.value, (index) => e.key + k ~/ 2))\n .expand((element) => element)\n .toList();\n }\n }\n return [];\n }\n}\n``` | 0 | 0 | ['Dart'] | 0 |
recover-the-original-array | Python solution | python-solution-by-vincent_great-lsj4 | \ndef recoverArray(self, nums: List[int]) -> List[int]:\n\tm, cnter = min(nums), Counter(sorted(nums))\n\tfor x in cnter.keys():\n\t\td = x-m\n\t\tif d>0 and d% | vincent_great | NORMAL | 2022-10-28T11:02:03.720191+00:00 | 2022-10-28T11:02:03.720231+00:00 | 33 | false | ```\ndef recoverArray(self, nums: List[int]) -> List[int]:\n\tm, cnter = min(nums), Counter(sorted(nums))\n\tfor x in cnter.keys():\n\t\td = x-m\n\t\tif d>0 and d%2==0:\n\t\t\tcnt, arr = cnter.copy(), []\n\t\t\tfor n, v in cnt.items():\n\t\t\t\tif v:\n\t\t\t\t\tif v<=cnt[n+d]:\n\t\t\t\t\t\tarr.extend([n+d//2]*v)\n\t\t\t\t\t\tcnt[n+d] -= v\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\tif len(arr)==len(nums)//2:\n\t\t\t\treturn arr\n``` | 0 | 0 | [] | 0 |
recover-the-original-array | Two Solutions Explained Python | two-solutions-explained-python-by-sartha-yvey | Try all k\nTime: O(n^2)\n2 <= 2k <= max(nums) - min(nums)\nthe diff higher[i] - lower[i] == 2k, so even is important.\nsort the nums and try all differences num | sarthakBhandari | NORMAL | 2022-10-27T10:44:15.242280+00:00 | 2022-10-27T10:52:06.906798+00:00 | 73 | false | **Try all k**\n**Time: O(n^2)**\n2 <= 2*k <= max(nums) - min(nums)\nthe diff higher[i] - lower[i] == 2*k, so even is important.\nsort the nums and try all differences nums[i] - nums[0].\nYou can check if a difference is valid in O(N) time. Just use two pointers (i, j). \ni is a pointer for elements in lower and j is a pointer for elements in higher.\nif nums[j] - nums[i] == diff then save the j pointer in a set.\nAt the end of iteration when (j == n) if the size of higher set == size of original array, then its a valid difference.\n\n```\ndef recoverArray(self, nums: List[int]) -> List[int]:\n n = len(nums)\n nums.sort()\n\n def isValid(diff):\n i = j = 0\n higher = set()\n while j < n:\n while i in higher:\n i += 1\n if j == i:\n j = i + 1\n continue\n if nums[j] - nums[i] == diff:\n higher.add(j)\n i += 1; j += 1\n else: j += 1\n\n if len(higher) == n//2:\n return higher\n \n for i in range(1, n):\n k = nums[i] - nums[0]\n if k and not k%2:\n higher = isValid(k)\n if higher:\n diff = k//2\n return [nums[i] - diff for i in higher]\n \n return []\n```\n**Diff Counter** -- TLE\n**Time: O(n^2)**\nthe most common difference for each pair in nums, must be a valid difference value. There is no need to check its validity because question states that a valid answer must exist. \n```\ndef recoverArray(self, nums):\n n = len(nums)\n nums.sort()\n \n diffFreq = defaultdict(int)\n max_freq = 0\n for i in range(n):\n for j in range(i+1, n):\n diff = nums[j] - nums[i]\n if diff and not(diff)%2:\n diffFreq[diff] += 1\n\n if diffFreq[diff] > max_freq:\n max_freq_diff = diff\n max_freq = diffFreq[diff]\n \n i = j = 0\n higher = set()\n while j < n:\n while i in higher:\n i += 1\n if j == i:\n j = i + 1\n continue\n if nums[j] - nums[i] == max_freq_diff:\n higher.add(j)\n i += 1; j += 1\n else:\n j += 1\n\n max_freq_diff //= 2\n return [nums[i] - max_freq_diff for i in higher]\n```\n\n\n | 0 | 0 | ['Hash Table', 'Sorting', 'Python'] | 0 |
recover-the-original-array | [Python] Sort and try every possible k while recover origin on the fly | python-sort-and-try-every-possible-k-whi-qcjr | \nfrom collections import defaultdict\n\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n for i in range | cava | NORMAL | 2022-10-26T10:05:54.493253+00:00 | 2022-10-26T10:06:17.427146+00:00 | 22 | false | ```\nfrom collections import defaultdict\n\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n for i in range(1, len(nums)):\n\t\t\t# skip the same k or k is odd\n if nums[i] == nums[i - 1] or (nums[i] - nums[0]) & 1: continue\n k = (nums[i] - nums[0]) // 2\n dt = defaultdict(int)\n cur = [] # cur to store origin\n for v in nums:\n if dt[v]:\n dt[v] -= 1\n cur.append(v - k)\n else: dt[v + 2 * k] += 1\n if len(cur) == len(nums) // 2: return cur\n return []\n``` | 0 | 0 | [] | 0 |
recover-the-original-array | C++ sort + 2 pointers beats 100% | c-sort-2-pointers-beats-100-by-bcb98801x-adxa | find all possible k\n2. sort nums\n3. iterate all possible k and use two pointers to check if it works\n\nTC : O(n^2)\nSC : O(n)\n\nclass Solution {\npublic:\n | bcb98801xx | NORMAL | 2022-10-20T11:14:30.313022+00:00 | 2022-10-20T11:14:52.694081+00:00 | 43 | false | 1. find all possible `k`\n2. sort `nums`\n3. iterate all possible `k` and use two pointers to check if it works\n\nTC : O(n^2)\nSC : O(n)\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n = nums.size();\n\t\t// find all possible k\n unordered_set<long> ks;\n for (int i = 1; i < n; i++) {\n long sum = nums[i]+nums[0];\n if (!(sum&1))\n ks.insert(max(nums[0], nums[i])-(sum>>1));\n }\n sort(nums.begin(), nums.end());\n \n\t\t// iterate all possible k and use two pointers to check if it works\n vector<int> ans;\n for (auto k : ks) {\n if (!k) continue;\n \n long k2 = k<<1;\n\t\t\t// find the start position of upper to nums[0]\n int upperi = lower_bound(nums.begin(), nums.end(), nums[0]+k2) - nums.begin();\n if (upperi == n || nums[upperi] != nums[0]+k2) continue; // no such upper\n \n bool used[2000] = {};\n used[0] = used[upperi++] = true;\n ans.push_back(nums[0]+k);\n \n for (int loweri = 1; upperi < n; loweri++) {\n if (used[loweri]) continue;\n \n long upper = nums[loweri]+k2;\n while (upperi < n && (upper > nums[upperi] || used[upperi])) upperi++;\n \n if (upperi == n || upper != nums[upperi]) break;\n \n used[upperi++] = true;\n ans.push_back(nums[loweri]+k);\n }\n \n if (ans.size() == (n>>1)) break;\n \n ans.clear();\n }\n return ans;\n }\n};\n``` | 0 | 0 | [] | 0 |
recover-the-original-array | [Python] Greedy || Hashmap || Priority Queue | python-greedy-hashmap-priority-queue-by-f442j | \nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n heapify(nums)\n n0, h0 = len(nums), Counter(nums)\n for kk i | coolguazi | NORMAL | 2022-10-14T13:28:40.425839+00:00 | 2022-10-14T13:30:25.388136+00:00 | 112 | false | ```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n heapify(nums)\n n0, h0 = len(nums), Counter(nums)\n for kk in map(lambda x: x - nums[0], nums):\n if kk <= 0 or kk % 2: continue\n ans, nms, n, h = [], nums[:], n0, h0.copy()\n while True:\n if n == 0: return ans\n while not h[nms[0]]: heappop(nms)\n num = heappop(nms)\n if not h[num + kk]: break\n h[num] -= 1\n h[num + kk] -= 1\n ans.append(num + kk // 2)\n n -= 2\n``` | 0 | 0 | ['Greedy', 'Heap (Priority Queue)', 'Python'] | 0 |
recover-the-original-array | rust 105ms | rust-105ms-by-drizz1e-yzcp | rust\nimpl Solution {\n pub fn recover_array(nums: Vec<i32>) -> Vec<i32> {\n use std::collections::HashMap;\n let mut nums = nums.clone();\n | drizz1e | NORMAL | 2022-10-06T14:49:56.868222+00:00 | 2022-10-06T14:49:56.868268+00:00 | 18 | false | ```rust\nimpl Solution {\n pub fn recover_array(nums: Vec<i32>) -> Vec<i32> {\n use std::collections::HashMap;\n let mut nums = nums.clone();\n nums.sort();\n let smallest = nums[0];\n let mut last_k = -1;\n let mut left = HashMap::new();\n for &n in &nums {\n if !left.contains_key(&n) { left.insert(n, 1); }\n else { left.insert(n, left.get(&n).unwrap() + 1); }\n }\n \'out: for &n in (&nums[1..]).iter() {\n let k = n - smallest;\n if k == last_k || k % 2 != 0 || k == 0 { continue; }\n last_k = k;\n // enumeration\n let mut table = left.clone();\n let mut ret = Vec::new();\n for &n in nums.iter() {\n if table.get(&n).unwrap().clone() == 0 { continue; }\n let counterpart = n + k;\n if !table.contains_key(&counterpart) || table.get(&counterpart).unwrap().clone() == 0\n { continue \'out; }\n ret.push(n + k / 2);\n table.insert(n, table.get(&n).unwrap() - 1);\n table.insert(counterpart, table.get(&counterpart).unwrap() - 1);\n }\n return ret;\n }\n return Vec::new();\n }\n}\n``` | 0 | 0 | [] | 0 |
recover-the-original-array | Python Solution using HashMap | python-solution-using-hashmap-by-hemantd-mfm3 | \nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n sz = len(nums)\n nums.sort()\n for i in range(1, sz):\n | hemantdhamija | NORMAL | 2022-09-18T10:41:24.268012+00:00 | 2022-09-18T10:41:24.268058+00:00 | 64 | false | ```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n sz = len(nums)\n nums.sort()\n for i in range(1, sz):\n k, hashMap = nums[i] - nums[0], Counter(nums)\n if k % 2 or k == 0:\n continue\n ans, gotIt = [], True\n for j in range(sz):\n if hashMap[nums[j]]:\n if nums[j] + k in hashMap and hashMap[nums[j] + k] > 0:\n ans.append(nums[j] + k // 2)\n hashMap[nums[j]] -= 1\n hashMap[nums[j] + k] -= 1\n else:\n gotIt = False\n break\n if gotIt:\n return ans\n return []\n``` | 0 | 0 | ['Greedy', 'Python'] | 0 |
recover-the-original-array | Simple Python Solution | simple-python-solution-by-archangel1235-nlah | \nfrom collections import Counter\n\nclass Solution:\n def findOriginalArray(self, changed: List[int], target : int):\n changed.sort()\n c1,c2, | archangel1235 | NORMAL | 2022-09-15T21:03:01.820194+00:00 | 2022-09-15T21:03:41.430501+00:00 | 25 | false | ```\nfrom collections import Counter\n\nclass Solution:\n def findOriginalArray(self, changed: List[int], target : int):\n changed.sort()\n c1,c2,length = 0,0,len(changed)\n count_map = Counter(changed)\n original = []\n if length%2 :\n return original\n while (c1 != length//2 and c2 < length):\n if count_map[changed[c2]] > 0 :\n count_map[changed[c2]] -= 1\n if count_map[changed[c2] + 2*target] > 0:\n original.append(changed[c2])\n count_map[changed[c2] + 2*target] -= 1\n c1 += 1\n else:\n return []\n elif (c2 == length-1):\n return []\n c2 += 1 \n return original\n def getk(self,nums: List[int], k):\n nums_cache = defaultdict(bool)\n for i in nums:\n nums_cache[i] = True\n for i in nums[1:]:\n k = (i-nums[0])//2 if i != nums[0] and (i-nums[0])%2==0 else k+1\n print(k)\n if nums_cache[nums[-1] - 2*k]:\n break\n return k\n \n \n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n k = 1\n original = []\n nums_cache = defaultdict(bool)\n for i in nums:\n nums_cache[i] = True\n while(len(original) == 0):\n for i in nums[1:]:\n k = (i-nums[0])//2 if (i - nums[0]) >= 2 else k+1\n if nums_cache[nums[-1] - 2*k] and nums_cache[nums[0] + 2*k]:\n original = self.findOriginalArray(nums, k)\n if len(original):\n break\n return map(lambda x:x+k, original)\n``` | 0 | 0 | [] | 0 |
recover-the-original-array | C++ || multiset || BRUTE FORCE | c-multiset-brute-force-by-mukesh0765-cgd4 | Approach\nstep 1:- Sort the array.\nstep 2:- The smallest element will be the first element of lower array. So find every possible of values of K with respect t | mukesh0765 | NORMAL | 2022-09-15T20:33:13.268835+00:00 | 2022-09-15T20:33:13.268876+00:00 | 60 | false | ***Approach***\nstep 1:- Sort the array.\nstep 2:- The smallest element will be the first element of lower array. So find every possible of values of K with respect to the smallest element.\nstep 3:- If the total number of count is equal to the size of the array for any K then simply return the array.\n\n\n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n for(int i=1;i<n;i++){\n int k=nums[i]-nums[0];\n if(k==0 || k%2!=0){\n continue;\n }\n\t\t\t// multiset to avoid the problem of duplicate elements in the array.\n multiset<int> ms(nums.begin(),nums.end());\n int cnt=0;\n vector<int> ans;\n while(!ms.empty()){\n int low=*ms.begin();\n int high=low+k;\n if(ms.find(high)!=ms.end()){\n ans.push_back(low+(k/2));\n ms.erase(ms.begin());\n auto it=ms.find(high);\n ms.erase(it);\n cnt+=2;\n }\n else break;\n }\n if(cnt==n){\n return ans;\n }\n }\n return {};\n }\n};\n``` | 0 | 0 | ['C'] | 0 |
recover-the-original-array | c++ | c-by-ramdayalbishnoi29-484w | \n\n"""\n\nclass Solution {\n \nprivate:\n bool solve(multisetms,vector&ans,int k){\n \n while(!ms.empty()){\n int low=ms.begin();\n | ramdayalbishnoi29 | NORMAL | 2022-09-15T18:14:07.514787+00:00 | 2022-09-15T18:14:07.514830+00:00 | 21 | false | \n\n"""\n\nclass Solution {\n \nprivate:\n bool solve(multiset<int>ms,vector<int>&ans,int k){\n \n while(!ms.empty()){\n int low=*ms.begin();\n int high=low+2*k;\n \n if(ms.find(high)==ms.end())return false;\n \n ans.push_back(low+k);\n \n ms.erase(ms.begin());\n auto it=ms.find(high);\n ms.erase(it); \n } \n return true; \n } \n \npublic:\n \n \n vector<int> recoverArray(vector<int>& arr) {\n sort(arr.begin(),arr.end());\n int n=arr.size();\n multiset<int>ms(arr.begin(),arr.end());\n \n int low=arr[0];\n \n for(int i=1;i<n;i++){\n vector<int>ans;\n int high=arr[i];\n if((high-low)%2==0){\n int k=(high-low)/2;\n if(k&&solve(ms,ans,k)){\n return ans;\n } \n \n }\n }\n \n return {};\n }\n \n};\n\n""" | 0 | 0 | [] | 0 |
recover-the-original-array | C++ || O(N^2) || EASY APPROACH EXPLAINED || HASHMAP | c-on2-easy-approach-explained-hashmap-by-s2rg | This solution is next level of question : https://leetcode.com/problems/find-original-array-from-doubled-array/\n\nLets say we have any arbitary value for K ,\n | sumitChoube238 | NORMAL | 2022-09-15T15:39:07.122976+00:00 | 2022-09-15T15:40:24.830427+00:00 | 56 | false | This solution is next level of question : https://leetcode.com/problems/find-original-array-from-doubled-array/\n\nLets say we have any arbitary value for K ,\n* We will first sort the array and store frequency all the element in a map ;\n* We will go by each element and check if that nums[i] and nums[i] +k*2 is present in map if yes we will push it to answers and subtract 1 value in map for both nums[i] and nums[i] +k*2 ;\n* if condition do not staicify we will break loop and solution is not present for given value of K .\n* So we will follow above steps for all possible values of k \n* To get all possible values of k we will sutract first elemt in nums from each value present in nums. (as k will be same for all elements including first ).\n\ncode : \n```\nclass Solution {\npublic:\n vector<int> recoverArray(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n for(int i=1;i<n;i++){\n int k = nums[i]-nums[0];\n if(k%2!=0 || k==0){\n continue;\n }\n unordered_map<int,int> mp;\n for(int i=0;i<n;i++){\n mp[nums[i]]++;\n }\n vector<int> ans;\n bool gotit=true;\n for(int i=0;i<n;i++){\n if(mp[nums[i]]!=0){\n if(mp.count(nums[i]+k)!=0 && mp[nums[i]+k]>0){\n ans.push_back(nums[i]+k/2);\n mp[nums[i]]--;\n mp[nums[i]+k]--;\n }\n else{\n gotit=false;\n break;\n }\n }\n }\n if(gotit){\n return ans;\n }\n \n }\n return {};\n }\n};\n```\n\n\n\n | 0 | 0 | [] | 0 |
recover-the-original-array | ✔️ Clean and well structured Python3 implementation (Top 93.2%) || Very simple | clean-and-well-structured-python3-implem-z662 | I found this Github repository with solutions to Leetcode problems https://github.com/AnasImloul/Leetcode-solutions\nThe ability to find every solution in one l | Kagoot | NORMAL | 2022-08-27T19:05:39.558045+00:00 | 2022-08-27T19:05:39.558081+00:00 | 92 | false | I found this Github repository with solutions to Leetcode problems https://github.com/AnasImloul/Leetcode-solutions\nThe ability to find every solution in one location is very helpful, I hope it helps you too\n```\nclass Solution(object):\n def recoverArray(self, nums):\n nums.sort()\n mid = len(nums) // 2\n # All possible k are (nums[j] - nums[0]) // 2, otherwise there is no num that satisfies nums[0] + k = num - k.\n # For nums is sorted, so that any 2 elements (x, y) in nums[1:j] cannot satisfy x + k = y - k.\n # In other words, for any x in nums[1:j], it needs to find y from nums[j + 1:] to satisfy x + k = y - k, but\n # unfortunately if j > mid, then len(nums[j + 1:]) < mid <= len(nums[1:j]), nums[j + 1:] are not enough.\n # The conclusion is j <= mid.\n\t\t# If you think it\u2019s not easy to understand why mid is enough, len(nums) can also work well\n\t\t# for j in range(1, len(nums)): \n for j in range(1, mid + 1): # O(N)\n if nums[j] - nums[0] > 0 and (nums[j] - nums[0]) % 2 == 0: # Note the problem described k is positive.\n k, counter, ans = (nums[j] - nums[0]) // 2, collections.Counter(nums), []\n # For each number in lower, we try to find the corresponding number from higher list.\n # Because nums is sorted, current n is always the current lowest num which can only come from lower\n # list, so we search the corresponding number of n which equals to n + 2 * k in the left\n # if it can not be found, change another k and continue to try.\n for n in nums: # check if n + 2 * k available as corresponding number in higher list of n\n if counter[n] == 0: # removed by previous num as its corresponding number in higher list\n continue\n if counter[n + 2 * k] == 0: # not found corresponding number in higher list\n break\n ans.append(n + k)\n counter[n] -= 1 # remove n\n counter[n + 2 * k] -= 1 # remove the corresponding number in higher list\n if len(ans) == mid:\n return ans\n\n``` | 0 | 0 | ['Python3'] | 0 |
recover-the-original-array | Simple python solution | simple-python-solution-by-xiemian-jun1 | ```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n \n dis = list(set([nums[i] - nums[0] for i | xiemian | NORMAL | 2022-08-01T03:25:16.736063+00:00 | 2022-08-01T03:25:16.736104+00:00 | 34 | false | ```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n \n dis = list(set([nums[i] - nums[0] for i in range(1, len(nums) // 2 + 1) if (nums[i] - nums[0]) % 2 == 0]))\n rec = OrderedDict()\n pos = defaultdict(deque)\n\n res = []\n \n for i, num in enumerate(nums):\n if num not in rec: rec[num] = 1\n else: rec[num] += 1\n pos[num].append(i)\n \n for d in dis:\n if d == 0: continue\n new = rec.copy()\n fail = False\n\n for k in rec.keys():\n if new[k] == 0: continue\n if k + d not in new or new[k + d] < new[k]:\n fail = not fail\n break\n new[k + d] -= new[k]\n new[k] = 0\n\n if fail: continue\n\n visited = set()\n \n for i, n in enumerate(nums):\n if i in visited: continue\n res.append(n + d // 2)\n visited.add(pos[n].popleft())\n visited.add(pos[n + d].popleft())\n break\n \n return res | 0 | 0 | [] | 0 |
recover-the-original-array | [Java] try all possible k | java-try-all-possible-k-by-aybx96-0jtj | \n public int[] recoverArray(int[] nums) {\n var count = new HashMap<Integer, Integer>();\n int max = 0;\n for (int a : nums) {\n | aybx96 | NORMAL | 2022-07-09T14:27:49.019520+00:00 | 2022-07-09T14:27:49.019546+00:00 | 40 | false | ```\n public int[] recoverArray(int[] nums) {\n var count = new HashMap<Integer, Integer>();\n int max = 0;\n for (int a : nums) {\n max = Math.max(max, a);\n count.put(a, count.getOrDefault(a, 0) + 1);\n }\n var uniques = new ArrayList<Integer>(count.keySet());\n Collections.sort(uniques);\n \n var possibleK = new ArrayList<Integer>();\n for (int i = 1, kk; i<uniques.size(); i++) {\n kk = uniques.get(i) - uniques.get(0);\n if (kk % 2 == 0) {\n possibleK.add(kk / 2);\n }\n }\n \n for (int k : possibleK) {\n var cloneCount = (HashMap<Integer, Integer>) count.clone();\n var res = tryK(uniques, cloneCount, k, nums.length/2);\n if (res != null) {\n return res;\n }\n }\n \n return null;\n\n }\n \n public int[] tryK(List<Integer> uniques, HashMap<Integer, Integer> count, int k, int n) {\n var ans = new int[n];\n int cur = 0;\n for (int a : uniques) {\n if (count.getOrDefault(a, 0) == 0) \n continue;\n int c = count.get(a);\n int d = count.getOrDefault(a + 2*k, 0) - c;\n if (d < 0)\n return null;\n while (c-- > 0) {\n ans[cur++] = a + k;\n }\n count.remove(a);\n count.put(a+2*k, d);\n }\n \n return ans;\n }\n``` | 0 | 0 | [] | 0 |
recover-the-original-array | python soln | python-soln-by-kumarambuj-2ht9 | \nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n \n \n \n nums.sort()\n n=len(nums)\n if | kumarambuj | NORMAL | 2022-06-10T06:10:23.576414+00:00 | 2022-06-10T06:10:23.576447+00:00 | 106 | false | ```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n \n \n \n nums.sort()\n n=len(nums)\n if n==2:\n return [(nums[0]+nums[-1])//2]\n hash={}\n \n for x in nums:\n if x not in hash:\n hash[x]=0\n hash[x]+=1\n mn=nums[0]\n mx=nums[-1]\n \n def check(k,nums,hash1,ans):\n for i in range(len(nums)):\n if nums[i] in hash1:\n if nums[i]+2*k in hash1:\n z=nums[i]+2*k\n ans.append((nums[i]+z)//2)\n \n if hash1[nums[i]]==1:\n del hash1[nums[i]]\n \n else:\n hash1[nums[i]]-=1\n \n if hash1[z]==1:\n del hash1[z]\n \n else:\n hash1[z]-=1\n else:\n break\n \n return len(hash1)==0\n \n \n \n \n \n \n for i in range(1,n):\n \n\n k=nums[i]-nums[0]\n \n if k%2==0 and k!=0:\n ans=[]\n hash1=hash.copy()\n if check(k//2,nums,hash1,ans):\n return ans\n \n \n \n \n \n \n \n \n \n \n \n```\n | 0 | 0 | ['Python'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.