Append K Integers with Minimal Sum Problem

Problem Statement:

We are given an integer array of nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum.

Return the sum of the k integers appended to nums.

Java Approach Using HashSet

Output:

Append K Integers with Minimal Sum Problem

Code Explanation:

  • The code aims to find the minimal sum of the first k unique elements in a sorted array. It uses a set to track encountered elements and ensures uniqueness. The array is sorted, and for each element, if it is both unique and less than or equal to k, the value of k is incremented, and the element is added to the sum.
  • The final result is calculated by subtracting the actual sum from the sum of the first k natural numbers.

Time Complexity:

  • The time complexity is defined by this sorting part of an algorithm, which runs in O(n log n), where n stands for length. The second iteration of the array by sorting and set operations introduces a linear time, leaving an aggregate complexity at O(n log n).

Space Complexity:

  • It has a space complexity of O(n) because we use the memory structure HashSet to store unique elements. When all elements are distinct, the size of HashSet will be proportional to the length of an input array, consequently resulting in linear space complexity.

Java Optimal Approach

Output:

Append K Integers with Minimal Sum Problem

Code Explanation:

  • The code aims to find the minimal sum of the first 'k' unique positive integers not present in a given array 'nums.' It starts by sorting the array and then iterates through the sorted elements. For each element, it checks if it is greater than the current 'lo' value. If true, it calculates the range of missing positive integers between 'lo' and 'num-1'.
  • It adds the sum of this range to the answer and updates 'lo' and 'k'. The process continues until 'k' becomes zero or all elements are processed.

Time Complexity:

  • This algorithm's time complexity is O (N log N), which denotes the number of elements in array 'nums'. Sorting is the biggest factor that takes O(N log N) time.

Space Complexity:

  • The space complexity is O(1). For variables such as 'and,' 'lo,''hi, " cnt" and " k," the algorithm requires a constant additional space independent of input size.





Latest Courses