703467. Unique DigitSum

Easy

Unique DigitSum

Summary

The "Unique DigitSum" problem is a basic algorithmic challenge that involves finding unique digit sums in an array. The goal is to write an efficient algorithm that can identify and count the unique digit sums within the given input array.

Detailed Explanation

Given an integer array nums, our task is to find all unique digit sums and return their count. For example, if we have the array [11, 22, 33], the unique digit sums would be [1+1=2, 2+2=4, 3+3=6], so the output should be 3.

To solve this problem, we can iterate through each element in the input array and calculate its digit sum. We can store these sums in a set to keep track of unique ones and then return the count.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty set uniqueSums to store unique digit sums.
  2. Iterate through each element num in the input array nums.
  3. Calculate the digit sum of num by adding up its digits (e.g., for 11, the digit sum is 1+1=2).
  4. Check if this digit sum is already present in uniqueSums. If not, add it to the set.
  5. After iterating through all elements, return the size of uniqueSums, which represents the count of unique digit sums.

Time complexity: O(n), where n is the number of elements in the input array, since we're only performing a single pass through the array. Space complexity: O(n), as we need to store the unique digit sums in the set.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public int uniqueDigitSumCount(int[] nums) {
    Set<Integer> uniqueSums = new HashSet<>();
    for (int num : nums) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        uniqueSums.add(sum);
    }
    return uniqueSums.size();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.