C# AC - check if number and number+2*k exists
checking if the array is valid for K logic is similar to these 2 problems. so solve these first\nhttps://leetcode.com/problems/find-original-array-from-doubled-
checking if the array is valid for K logic is similar to these 2 problems. so **solve these first**\nhttps://leetcode.com/problems/find-original-array-from-doubled-array/discuss/1735246/c-ac-check-frequencies\nhttps://leetcode.com/problems/array-of-doubled-pairs/discuss/1735322/C-AC-check-frequencies\n\n\nIf we check every value of k it will time out.  As we know there is a valid output, for nums[0] there should be a value exist in the array for which \n```\nnum[i] = nums[0] + 2* k\nk = (nums[i]-nums[0])/2;\n```\n![image](https://assets.leetcode.com/users/images/8c9771e5-fadb-4d9d-8e4e-deea16e14306_1643680705.3570833.png)\n\n\n```\npublic int[] RecoverArray(int[] nums)\n{\n\tint n = nums.Length;\n\tif(n%2 != 0) return new int[0];\n\tArray.Sort(nums);\n\tint[] result = new int[n/2];\n\n\tDictionary<int, int> counts = new Dictionary<int, int>();\n\tforeach (var num in nums)\n\t{\n\t\tif (counts.ContainsKey(num)) counts[num]++;\n\t\telse counts.Add(num, 1);\n\t}\n\n\tfor (int i = 1; i < n; i++)\n\t{\n\t\tint k = nums[i] - nums[0];\n\t\tif(k== 0 || k%2 != 0) continue; \n\t\tk = k/2;\n\t\tif(IsKValid(nums, k, new Dictionary<int, int>(counts), result ))\n\t\t{\n\t\t\treturn result;\n\t\t}\n\t}\n\treturn result;\n}\n\nprivate bool IsKValid(int[] nums, int k, Dictionary<int, int> counts, int[] result)\n{\t\n\tint carry = 2*k;\n\tint index=0;\n\tforeach (var num in nums)\n\t{\n\t\tif(counts[num]==0) continue;\n\t\t\n\t\t// lower(num) = value-k so value = num+k\n\t\t// higher = num+k+k = 2*k + num\n\t\tint target = carry+num;\n\t\tif(!counts.ContainsKey(target) || counts[target] == 0)\n\t\treturn false;\n\t\t\n\t\tresult[index++] = num+k;\n\t\tcounts[num]--;\n\t\tcounts[target]--;\n\t}\t\n\treturn true;\t\n}\n\n```
[]