/** Find the Missing Number * * @reference https://www.geeksforgeeks.org/find-the-missing-number/ * * You are given a list of n-1 integers and these integers are in the range of 1 to n. * There are no duplicates in list. One of the integers is missing in the list. * Write an efficient code to find the missing integer. * * @complexity O(n) */ auto FindTheMissingNumberSum(const ArrayType &integers) { assert(not integers.empty()); const auto N = integers.size() + 1u; const auto sum = N * (N + 1) / 2; return std::accumulate(integers.cbegin(), integers.cend(), sum, std::minus<ArrayType::value_type> {}); }
auto RearrangeArrayInPlace(ArrayType elements) { for (ArrayType::size_type i = 0; i < elements.size(); ++i) { elements[elements[i] % elements.size()] += i * elements.size(); } std::transform(elements.cbegin(), elements.cend(), elements.begin(), [&elements](const ArrayType::value_type v) { return v / elements.size(); }); return elements; }
std::pair<int, int> FindSubarrayWithGivenSum(const ArrayType &integers, const ArrayType::value_type SUM) { assert(not integers.empty()); auto start = integers.cbegin(); auto current_sum = *start; for (auto i = start + 1; i != integers.cend(); ++i) { while (current_sum > SUM and start < i - 1) { current_sum -= *start++; } if (current_sum == SUM) { return std::make_pair(start - integers.cbegin(), i - integers.cbegin() - 1); } current_sum += *i; } return NOT_FOUND; }
auto SumTailRecursive(const ArrayType &elements) { return SumTailRecursive(elements.cbegin(), elements.cend()); }
auto SumRecursive(const ArrayType &elements) { return SumRecursiveHelper(elements.cbegin(), elements.cend()); }