#3712

Sum of Elements With Frequency Divisible by K

Easy
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a hash map to count frequencies in one pass, then sum elements based on their frequencies in a second pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a frequency map of elements in nums.
  2. 2Step 2: Iterate through the frequency map and check if each frequency is divisible by k.
  3. 3Step 3: If divisible, add the element multiplied by its frequency to the total sum.
solution.py4 lines
1def sumDivisibleByK(nums, k):
2    from collections import Counter
3    freq_map = Counter(nums)
4    return sum(num * freq for num, freq in freq_map.items() if freq % k == 0)

Complexity note: Counting frequencies in one pass and summing in another leads to O(n) time complexity.

  • 1Using a hash map allows efficient frequency counting.
  • 2Divisibility checks can be done in a single pass after counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.