Problem 1748

Abstract / Summary

Given an array, add the values that appear only once.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1748.py

class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        freq = defaultdict(int)
        for i in nums:
            freq[i] += 1

        result = 0
        for i in freq:
            if freq[i] == 1:
                result += i

        return result
12 lines | 282 bytes | submitted August 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (300k+ submissions).
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method sumOfUnique that receives a list of integers and returns the sum of the elements that appear exactly once in the input. The algorithm proceeds in two distinct phases: first it records the occurrence count of each integer, then it aggregates the values whose count equals one.

Building the Frequency Table

The method begins by creating a defaultdict of integers named freq. This container automatically supplies a default value of zero for any new key, allowing the code to increment counts without explicit existence checks.

freq = defaultdict(int)
for i in nums:
    freq[i] += 1

During the single traversal of nums, each element i is used as a key in freq, and its associated count is increased by one. This step captures the complete frequency distribution of the input list.

Summing the Unique Elements

After the frequency table is populated, the method iterates over the keys of freq. For each key, it checks whether the recorded count is exactly one. If the condition holds, the key itself (the integer value) is added to an accumulator variable result.

result = 0
for i in freq:
    if freq[i] == 1:
        result += i

When the loop finishes, result holds the sum of all integers that occurred a single time in the original list.

Returning the Computed Sum

The final statement simply returns the accumulated sum to the caller.

return result

Edge Cases Handled

When the input list is empty, the frequency table remains empty, the summation loop does not execute, and the method returns the initial value of result, which is zero. This correctly reflects that there are no unique elements to sum.

If every element in the list appears more than once, the condition freq[i] == 1 never becomes true, leaving result unchanged at zero. The method therefore returns zero, indicating that no unique values exist.

When all elements are distinct, each key in freq has a count of one, so the summation loop adds every element to result. The returned value is the total sum of the original list, matching the expected behavior.

The algorithm also accommodates negative integers and large magnitude values because it treats each integer uniformly as a dictionary key and performs arithmetic using Python’s arbitrary-precision integer type.

Performance Optimizations Observed

The use of defaultdict(int) eliminates the need for explicit key existence checks, reducing overhead in the frequency-building phase. By separating the counting and summation into two passes-first over the input list, then over the distinct keys-the implementation avoids repeated scanning of the original data, ensuring that each element contributes to the work only once per phase.

Iterating over freq rather than the original list for the summation step means the second loop processes at most the number of unique values, which can be substantially smaller than the length of nums when many duplicates exist. This selective iteration reduces unnecessary arithmetic operations.

Overall, the design leverages Python’s built-in dictionary hashing for constant-time updates and lookups, providing an efficient solution for the problem at hand.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of colorful building blocks and you want to find the ones that are special because they are the only ones of their color. You start by going through the whole pile and making a little tally sheet to keep track of how many blocks you have for every color. You look at one block, check your sheet, and add a mark for that color so you can remember exactly how many you have altogether.

Once you finish counting all the blocks and your tally sheet is complete, you look over the list one more time. You look for any color that has exactly one mark on your paper. If you find a color with just one block, you keep that block to put in a special box. You do this for every single color on your list. By the end, the special box will hold only those unique blocks, and you can add up the numbers on them to see what you found.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.52 | σ = 1.42

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go PHP Rust TS
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, PHP, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
34 links | 21 authors | 11 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

20 solutions   August 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality