Green Book: Unique Elements
Feb 9, 2026
In the Green Book, there’s is a question in regards to having a sorted array, on how to extract the unique elements from the sorted array. The question goes as following
If you are given a sorted array, can you write some code to extract the unique elements from the array? For example, if the array is
[1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9]
the unique elements should be
[1, 3, 5, 9].
Solution
We start by defining the array which we’re going to work on
1A = [1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9]Declaring the arrayWe start by declaring the array. In this here practical example, we will use Python to solve it.
There’s some different things we can notice from this, given that it’s sorted
- The first elements will always be appended to the output array
- We’re able to, with confidence, compare element and , knowing that;
Here is a practical example of how to solve it in a pragmatic sense using Python:
1def uniqueElements(A: list) -> list:2 unique = []Initialize storageWe start by initializing the list that will capture only the unique values.
unique = []Keeping it empty up front makes every later append explicit.
3 for i in range(len(A)):Range for traversalWe create a range of indices to iterate through:
for i in range(len(A)):If
this produces the sequence:
so every position is inspected exactly once.
4 if i == 0 or (A[i] != A[i-1]):Branching logicWe split the conditional into two cases:
i == 0: the first element is always unique in a sorted list, so we seed the output with it.A[i] != A[i-1]: compares the current value against the previous one. At (i = 2) we check1 != 3→ True, so we append3. At (i = 3) we test3 == 3→ False, so the loop skips duplicates.5 unique.append(A[i])Append uniqueWhen either branch is satisfied we append the current value:
unique.append(A[i])Only fresh values make it through this gate.
6 return uniqueReturn resultFinally we hand back the built list:
return uniqueThe caller now receives the deduplicated spine of
A.
Given this, we can now call the function by using the following code:
1result = uniqueElements(A)Call the functionWe call the function with the array as an argument. The function will return a new list containing only the unique elements.
2print(result) # Output: [1, 3, 5, 9]