LeetCode 2195: Append K Integers With Minimal Sum Solution

Master LeetCode problem 2195 (Append K Integers With Minimal Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2195. Append K Integers With Minimal Sum

Problem Explanation

Explanation

To minimize the sum, we need to append the smallest possible positive integers that are not already present in the given array nums. We can achieve this by iteratively adding the next smallest integer starting from 1 until we have appended k unique positive integers.

Algorithm

  1. Create a HashSet to store unique numbers from nums.
  2. Initialize a variable curr to 1 to track the current number to append.
  3. Iterate from curr until we have appended k unique positive integers, adding each new unique number to the HashSet.
  4. Calculate the sum of all appended unique positive integers.

Time Complexity

The time complexity of this algorithm is O(k) because we iterate at most k times to find and append k unique positive integers.

Space Complexity

The space complexity is O(n) where n is the number of elements in the input array nums.

Solution Code

class Solution {
    public int appendKIntegersWithMinimalSum(int[] nums, int k) {
        Set<Integer> uniqueNums = new HashSet<>();
        for (int num : nums) {
            uniqueNums.add(num);
        }
        
        int curr = 1;
        int sum = 0;
        
        while (k > 0) {
            if (!uniqueNums.contains(curr)) {
                sum += curr;
                uniqueNums.add(curr);
                k--;
            }
            curr++;
        }
        
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2195 (Append K Integers With Minimal Sum)?

This page provides optimized solutions for LeetCode problem 2195 (Append K Integers With Minimal Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2195 (Append K Integers With Minimal Sum)?

The time complexity for LeetCode 2195 (Append K Integers With Minimal Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2195 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2195 in Java, C++, or Python.

Back to LeetCode Solutions