array
distinct values
absolute value
algorithm
data processing

count the number of distinct absolute values among the elements of the array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Counting distinct absolute values means treating -5 and 5 as the same value, then asking how many unique magnitudes remain. It is a small problem, but it shows up often in interview questions because the best solution depends on whether the array is already sorted.

For unsorted input, a set-based approach is simple and correct. For sorted input, a two-pointer solution can do the same job in linear time with constant extra space.

Simple Set-Based Solution

If the input can be in any order, the most direct approach is to take the absolute value of each element and insert it into a set.

python
1def count_distinct_absolute(nums):
2    seen = set()
3    for value in nums:
4        seen.add(abs(value))
5    return len(seen)
6
7
8print(count_distinct_absolute([-5, -3, -3, 0, 3, 6]))

This works because a set keeps only unique values. Its time complexity is O(n) on average, and the extra space is also O(n).

That is usually the right answer unless the problem explicitly asks for lower space usage or tells you the input is sorted already.

Better Space Usage for a Sorted Array

When the array is sorted, the largest absolute value must be at one of the ends. That makes a two-pointer scan possible.

python
1def count_distinct_absolute_sorted(nums):
2    left = 0
3    right = len(nums) - 1
4    count = 0
5
6    while left <= right:
7        left_abs = abs(nums[left])
8        right_abs = abs(nums[right])
9        current = max(left_abs, right_abs)
10        count += 1
11
12        while left <= right and abs(nums[left]) == current:
13            left += 1
14
15        while left <= right and abs(nums[right]) == current:
16            right -= 1
17
18    return count
19
20
21print(count_distinct_absolute_sorted([-7, -3, -3, -1, 0, 3, 3, 5]))

The logic is:

  • compare the absolute values at both ends
  • count the larger magnitude once
  • skip all duplicates of that magnitude on both sides

Because each index moves inward only once, the algorithm stays O(n) and uses O(1) extra space.

Walk Through an Example

Take the sorted array [-4, -4, -2, 0, 2, 2, 5].

The distinct absolute values are 4, 2, 0, and 5, so the answer is 4.

With the two-pointer method:

  • start at -4 and 5, count 5
  • move past all 5 values on the right
  • compare -4 and 2, count 4
  • skip both -4 values
  • compare -2 and 2, count 2 once
  • skip every 2 and -2
  • finally count 0

The benefit is that you never build another array and never insert into a hash set.

Choose the Algorithm Based on the Input Contract

A lot of confusion comes from mixing the two scenarios. If the input is not sorted, the two-pointer method is wrong unless you sort first. Sorting gives you a valid solution, but it changes the time complexity to O(n log n).

So the practical rule is:

  • unsorted input and simplicity matters: use a set
  • sorted input and space matters: use two pointers

That is a better answer than forcing one technique for every case.

Common Pitfalls

The biggest mistake is forgetting that absolute values can collide across signs. If you just count distinct original numbers, -2 and 2 are incorrectly treated as different.

Another common issue is using the two-pointer solution on unsorted input. That method relies completely on the sorted order.

In fixed-width integer languages, be careful with the smallest negative integer because abs can overflow. Python handles big integers safely, but languages such as Java and C# need extra care around their minimum integer values.

Finally, do not forget to skip duplicates on both sides in the sorted solution. If you only move one pointer, you can double-count the same magnitude.

Summary

  • Distinct absolute values treat positive and negative versions of the same magnitude as one value.
  • A set-based solution is the simplest choice for unsorted arrays.
  • A sorted array allows a linear two-pointer solution with constant extra space.
  • The algorithm choice depends on the guarantees the input gives you.
  • Handle duplicates carefully or the count will be wrong.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms