Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Remove duplicates from a sorted int[] in place and return the new logical length, for example {1,1,2,3,3,3,4} returns 4 with the first four elements {1,2,3,4}. Then explain how you would do it for an unsorted array.

For a sorted array we use two pointers: a write index w that starts at 1, and a read index i that walks from 1 to the end. Whenever a[i] differs from the last value we kept, a[w - 1], we copy it to a[w] and increase w; at the end w is the new logical length. This runs in O(n) time and O(1) extra space because duplicates in a sorted array are always next to each other. For an unsorted array, we either sort first in O(n log n), track seen values in a HashSet in O(n) time and O(n) space, or use Arrays.stream(a).distinct().toArray(), which keeps first occurrences.

Background to this question

Removing duplicates in place is a classic warm-up problem, but it tests real skills: choosing the right invariant, handling the edges, and respecting an API contract that says in place. The same two-pointer idea appears in compacting buffers, filtering arrays without allocation, and merging sorted data. In this answer, we will recap what in place and logical length mean, build the two-pointer solution step by step, trace it on the example, handle edge cases, and then solve the unsorted version with three different approaches and their costs.

1A Quick Recap: In Place and Logical Length

An array in Java has a fixed length. We cannot shrink {1,1,2,3,3,3,4} to four elements; the array object will always have seven slots. So in place means we rearrange the existing array so that the first w slots hold the answer, and we return w, the logical length. Whatever remains after index w - 1 is left over and the caller must ignore it.

This contract is common in performance-sensitive code because it avoids allocating a new array. The caller decides whether it needs a trimmed copy.

2The Two-Pointer Solution

Because the array is sorted, all copies of a value sit next to each other. So a value is new exactly when it differs from the last value we kept. We keep two indexes: i reads every element, and w points to the next free slot in the result.

Java
static int removeDuplicates(int[] a) {
if (a.length == 0) return 0; // nothing to keep
int w = 1; // a[0] is always kept
for (int i = 1; i < a.length; i++) {
if (a[i] != a[w - 1]) { // differs from the last kept value
a[w++] = a[i]; // keep it and move the write index
}
}
return w;
}
int[] a = {1, 1, 2, 3, 3, 3, 4};
int n = removeDuplicates(a);
System.out.println(n); // 4
System.out.println(Arrays.toString(a)); // [1, 2, 3, 4, 3, 3, 4]: only the first 4 count

The invariant that makes this correct is simple: before each step, a[0..w-1] holds the distinct values seen so far, in order. The first element is always kept, so w starts at 1. Comparing with a[w - 1] rather than a[i - 1] works for sorted input and makes the intent obvious: we compare with what we kept.

Notice that the tail of the array still holds old values. That is expected; the contract says only the first n elements are meaningful.

3Tracing the Example

Walking through the example shows how w lags behind i whenever we skip a duplicate.

removeDuplicates on {1,1,2,3,3,3,4}
ia[i]a[w - 1]Actionw after
111skip, duplicate1
221a[1] = 22
332a[2] = 33
433skip3
533skip3
643a[3] = 44
Each element is read once and written at most once, so the work is linear.

Each element is read exactly once, so the time is O(n), and we use two int variables regardless of the array size, so the extra space is O(1). If the caller needs an array of exactly the right size, it can call Arrays.copyOf(a, n), which returns [1, 2, 3, 4]; that allocates, so it is the caller's choice, not part of the in-place method.

4Edge Cases Worth Testing

An empty array returns 0, which the first line handles; without it, starting with w = 1 would wrongly report one element. A single element returns 1. An array where every value is the same, such as {5, 5, 5}, returns 1 and leaves a[0] = 5. An array with no duplicates returns its full length, and every write copies a value onto itself, which is harmless. Negative numbers and Integer.MIN_VALUE need no special care, because we compare values directly instead of using a sentinel. A null array would throw NullPointerException at a.length; whether to allow it is part of the method's contract.

5The Unsorted Version

If the array is not sorted, duplicates are not adjacent, so comparing neighbours no longer works. We have three reasonable options, and the choice depends on whether we must keep the original order and how much memory we can use.

Java
// Option 1: sort, then reuse the sorted solution. O(n log n) time, O(1) extra space for int[]
int[] b = {3, 1, 3, 2, 1};
Arrays.sort(b); // [1, 1, 2, 3, 3]
int len = removeDuplicates(b); // 3, b starts with [1, 2, 3]: original order lost
// Option 2: a HashSet of seen values. O(n) time, O(n) extra space, keeps first occurrences
static int removeDuplicatesUnsorted(int[] a) {
Set<Integer> seen = new HashSet<>();
int w = 0;
for (int v : a) {
if (seen.add(v)) a[w++] = v; // add returns false for a value already seen
}
return w;
}
int[] c = {3, 1, 3, 2, 1};
System.out.println(removeDuplicatesUnsorted(c)); // 3, c starts with [3, 1, 2]
// Option 3: streams, simplest to write, returns a new array
int[] d = Arrays.stream(new int[]{3, 1, 3, 2, 1}).distinct().toArray(); // [3, 1, 2]

Sorting first keeps the extra space small but loses the original order. The HashSet keeps the order of first occurrences and runs in linear time, but it boxes every int into an Integer and needs memory proportional to the number of distinct values. The stream version is the shortest and also keeps first occurrences, but it allocates a new array, so it does not satisfy an in-place contract; it is the right choice when we just want the distinct values and clarity matters more than allocation.

6Follow-up questions

Why return the length instead of a new array?

Because the contract says in place: the caller passed an array and expects it to be rearranged without allocation. Returning a new array would allocate and leave the caller's array unchanged, which breaks that contract. A separate method, or Arrays.copyOf on the result, serves callers who want a trimmed copy.

How would you allow each value at most twice?

Compare with the element two places back in the kept part: start w at 2 and keep a[i] when a[i] != a[w - 2]. The same idea generalises to at most k copies, with w starting at k and comparing against a[w - k].

Can we avoid boxing in the unsorted version?

Yes, with a primitive set from a library such as fastutil or Eclipse Collections, or with a boolean[] or BitSet when the values are in a small known range, such as 0 to 10,000. That keeps O(n) time without creating Integer objects.

7Conclusion

In this answer, we removed duplicates from a sorted int[] in place with two pointers: a write index starting at 1 and a read index that copies each value differing from the last kept one, giving O(n) time and O(1) space and returning the logical length 4 for the example. We traced it, covered the edge cases, and noted that Arrays.copyOf(a, n) gives a trimmed array when needed. For unsorted input we compared sorting first, a HashSet of seen values, and Arrays.stream(a).distinct().toArray(), each trading time, memory and order differently.

What to say in the interviewAbout 80 seconds aloud

Open with

Since the array is sorted, duplicates are always next to each other, so I'd use two pointers. I keep a write index w starting at 1, because the first element is always kept, and I loop i from 1 to the end.

Then, if they want more

If a[i] is different from a[w - 1], the last value I kept, I write it to a[w] and increment w. At the end, w is the new logical length, and the first w elements are the distinct values in order.

For the example, that gives 4 with 1, 2, 3, 4 at the front; the rest of the array is leftover, and the contract says the caller ignores it. That's O(n) time, since each element is read once, and O(1) extra space.

I'd handle the empty array up front by returning 0, and if the caller needs a properly sized array, Arrays.copyOf(a, w) does that, but I'd keep it outside the in-place method. For an unsorted array, comparing neighbours doesn't work.

I can sort first, which is O(n log n) but loses the original order, or use a HashSet of seen values, which is O(n) time and O(n) space and keeps first occurrences, or, if allocation isn't a concern, Arrays.stream(a).distinct().toArray(), which also keeps first occurrences.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Remove duplicates from a sorted int[] in place and return the new logical length, for...": https://scrivio-interview-library.netlify.app/java/arrays/b17f68c42a/