Removing Duplicate Elements From a 1D Array in ICSE Java

⚡ Direct Answer & Key Takeaway

Java arrays have fixed physical length, so removing duplicates means filtering unique elements while maintaining an updated logical count u. Using a clean auxiliary array unique[], inspect each element arr[i] against entries already placed in unique[0 .. u - 1]. If no match sets the boolean flag found to true, assign unique[u++] = arr[i]. Printing indices 0 through u - 1 produces a deduplicated list in original order without sorting.

1. Why Fixed-Size Arrays Need a Logical Counter

Unlike dynamic collections, a primitive int[] in Java cannot shrink in memory once allocated with new int[n]. Students frequently lose marks by replacing repeated numbers with 0 or -1, which corrupts the output whenever 0 itself is a valid input. Instead, ICSE examiners reward programs that track a separate logical length variable u, initialized to 0. Every time a distinct value is confirmed, it enters the next free slot at unique[u] and u increments by one. Even though unique.length remains n, only positions 0 through u - 1 hold valid deduplicated values. This technique preserves the exact appearance order of first occurrences.

  • Never replace duplicates with sentinel values like 0 or -999 unless the problem explicitly defines one.
  • Initialize logical counter u = 0 so empty or all-duplicate cases remain safe.
  • Loop the final display strictly up to i < u rather than i < unique.length.

2. Comparing Auxiliary Filtering vs. In-Place Left Shifting

Two valid strategies appear in CISCE marking schemes: building a clean unique[] array or shifting elements leftward inside the original array. With an auxiliary array, an outer loop scans arr[i] and an inner loop checks unique[0] to unique[u - 1]. Because found resets to false on every outer pass, only unseen values get copied. By contrast, in-place shifting compares arr[i] with later elements arr[j], shifts arr[k] = arr[k + 1] on a match, decrements the active length n--, and steps j-- so consecutive duplicates are not skipped. Unless a question forbids creating a second array, the auxiliary approach is far less error-prone.

  • Reset boolean found = false at the start of every outer iteration.
  • Break out of the inner check immediately once arr[i] == unique[j] is detected.
  • If using in-place shifting, remember j-- after n-- to inspect the newly shifted element.

3. Step-by-Step Dry Run on Mixed Duplicates

Consider an input array of n = 6 elements: {18, 42, 18, 7, 42, 7}. Initially u = 0. For i = 0, 18 finds nothing in unique[] because 0 < 0 is false, so unique[0] = 18 and u becomes 1. At i = 1, 42 differs from 18, giving unique[1] = 42 and u = 2. At i = 2, the inner loop matches unique[0], sets found = true, and skips insertion. Next, 7 passes both checks and enters unique[2] (u = 3). Finally, the trailing 42 and 7 match existing entries and are ignored, yielding {18, 42, 7}.

  • First element arr[0] always enters unique[0] because the inner loop condition j < 0 is initially false.
  • Repeated values appearing three or more times are filtered identically to pairs.
  • Total elements printed equals u = 3, leaving unused trailing slots untouched.

4. Remove Duplicates From 1D Array Preserving Order (Java)

import java.util.*;

public class RemoveDuplicatesArray {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of elements (n): ");
        int n = sc.nextInt();
        int[] arr = new int[n];

        System.out.println("Enter " + n + " integers:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        int[] unique = new int[n];
        int u = 0; // Logical size of deduplicated array

        for (int i = 0; i < n; i++) {
            boolean found = false;
            for (int j = 0; j < u; j++) {
                if (arr[i] == unique[j]) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                unique[u] = arr[i];
                u++;
            }
        }

        System.out.print("Array without duplicates: ");
        for (int i = 0; i < u; i++) {
            System.out.print(unique[i] + " ");
        }
        System.out.println("\nUnique element count: " + u);
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter number of elements (n): 6
Enter 6 integers:
18 42 18 7 42 7
Array without duplicates: 18 42 7 
Unique element count: 3

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
nintPhysical size of input array (e.g., 6)
arr[]int[]Original input array with possible repeats ({18, 42, 18, 7, 42, 7})
unique[]int[]Stores distinct elements in first-seen order ({18, 42, 7, 0, 0, 0})
uintLogical count of unique items stored so far (final u = 3)
foundbooleanFlag checking whether arr[i] already exists in unique[] (true / false)
i, jintOuter index over arr[] and inner index over unique[0 .. u-1]
🎯 1-on-1 Live Mentorship & Free Study Kit

Crack ICSE Array Deduplication With Guided Dry Runs

Book a live 1-on-1 BlueJ session to compare auxiliary vs. in-place shifting and ace Section B array questions.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Printing unique.length elements instead of u elements, which outputs trailing default zeroes after the deduplicated numbers.
  • Avoid Mistake: Declaring boolean found = false outside the outer for loop, causing all subsequent elements to stay skipped after the first duplicate.
  • Avoid Mistake: Forgetting j-- when performing in-place shifting, which skips checking an adjacent triple duplicate like {5, 5, 5}.
  • Examiner / Mentor Tip: Ask yourself during the exam whether order preservation matters: auxiliary filtering keeps original order, whereas sorting first alters sequence.
  • Examiner / Mentor Tip: Use break inside the inner comparison loop—viva examiners often ask why break improves efficiency once a match is found.
  • Examiner / Mentor Tip: Highlight the distinction between physical length (n) and logical length (u) in your VDT comments to earn full documentation credit.

7. Interactive Concept Check Quiz

Question: What happens if you forget to decrement j after shifting elements left in an in-place duplicate removal loop on {10, 10, 10}?

8. Frequently Asked Questions

Should I sort the array before removing duplicates in ICSE Class 10 Java?
Only sort first if the question explicitly allows altering element order or asks for sorted unique output. Most ICSE Section B questions expect elements to remain in their original input order. Using an auxiliary unique[] array with a boolean flag preserves first-occurrence sequence cleanly without needing an extra Bubble or Selection Sort pass.
Can I remove duplicates in place without creating a second array in Java?
Yes, compare arr[i] with arr[j] for j > i. Whenever arr[i] == arr[j], shift every element from j onward one index left, reduce the active length n by one, and decrement j by one so the element that just shifted into slot j is also checked for further repetition.
Why shouldn't I use HashSet or LinkedHashSet in ICSE board exams?
The CISCE Class 9 and 10 Computer Applications syllabus restricts array questions to primitive 1D and 2D arrays using standard loops and conditional logic. Collection classes like HashSet are outside the Class 10 scope, and relying on them instead of writing loop-based deduplication logic can cost algorithm marks in Section B.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class