Skip to content

Commit 9daf334

Browse files
committed
Created Remove Duplicate From Sorted Array
Implement in-place duplicate removal from sorted array using two-pointer technique.
1 parent 712ada5 commit 9daf334

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.thealgorithms.others;
2+
3+
import java.util.Scanner;
4+
5+
/**
6+
* Remove duplicates from sorted array.
7+
*
8+
* <p>
9+
* Given an integer array nums sorted in non-decreasing order, remove the
10+
* duplicates in-place such that each unique element appears only once.
11+
* The relative order of the elements should be kept the same. Then return
12+
* the number of unique elements in nums.
13+
*
14+
* <p>
15+
*/
16+
public final class RemoveDuplicatesFromSortedArray {
17+
18+
private RemoveDuplicatesFromSortedArray() {
19+
// private constructor to prevent instantiation
20+
}
21+
22+
/**
23+
* Main method with user input.
24+
*/
25+
public static void main(String[] args) {
26+
Scanner scanner = new Scanner(System.in);
27+
28+
System.out.println("Enter size of sorted array:");
29+
int n = scanner.nextInt();
30+
31+
if (n <= 0) {
32+
System.out.println("Invalid array size.");
33+
scanner.close();
34+
return;
35+
}
36+
37+
int[] nums = new int[n];
38+
System.out.println("Enter " + n + " integers in non-decreasing order:");
39+
for (int i = 0; i < n; i++) {
40+
nums[i] = scanner.nextInt();
41+
}
42+
43+
int k = removeDuplicates(nums);
44+
45+
System.out.println("Number of unique elements: " + k);
46+
System.out.print("Array after removing duplicates: ");
47+
for (int i = 0; i < k; i++) {
48+
System.out.print(nums[i] + " ");
49+
}
50+
System.out.println();
51+
52+
scanner.close();
53+
}
54+
55+
/**
56+
* Removes duplicates from a sorted array in-place using O(1) space.
57+
*
58+
* @param nums The input sorted array
59+
* @return The number of unique elements
60+
*/
61+
public static int removeDuplicates(int[] nums) {
62+
if (nums == null || nums.length == 0) {
63+
return 0;
64+
}
65+
66+
int j = 0; // points to last unique element
67+
for (int i = 1; i < nums.length; i++) {
68+
if (nums[j] != nums[i]) {
69+
j++;
70+
nums[j] = nums[i];
71+
}
72+
}
73+
return j + 1;
74+
}
75+
}

0 commit comments

Comments
 (0)