Skip to content

Commit a983e46

Browse files
committed
Update RemoveDuplicatesFromSortedArray.java
1 parent 9daf334 commit a983e46

File tree

1 file changed

+13
-47
lines changed

1 file changed

+13
-47
lines changed
Lines changed: 13 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,41 @@
11
package com.thealgorithms.others;
22

3-
import java.util.Scanner;
4-
53
/**
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.
4+
* Removes duplicates from a sorted integer array in-place
5+
* using the two-pointer technique and O(1) extra space.
136
*
147
* <p>
8+
* Example:
9+
* Input: [1, 1, 2, 2, 3]
10+
* Output: 3, and the array becomes [1, 2, 3, _, _]
11+
* </p>
1512
*/
1613
public final class RemoveDuplicatesFromSortedArray {
1714

1815
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();
16+
// Utility class, no instantiation
5317
}
5418

5519
/**
56-
* Removes duplicates from a sorted array in-place using O(1) space.
20+
* Removes duplicates from a sorted array in-place.
5721
*
58-
* @param nums The input sorted array
59-
* @return The number of unique elements
22+
* @param nums the sorted input array (non-decreasing order)
23+
* @return the number of unique elements
6024
*/
6125
public static int removeDuplicates(int[] nums) {
6226
if (nums == null || nums.length == 0) {
6327
return 0;
6428
}
6529

66-
int j = 0; // points to last unique element
30+
int j = 0; // Pointer for the last unique element
31+
6732
for (int i = 1; i < nums.length; i++) {
6833
if (nums[j] != nums[i]) {
6934
j++;
7035
nums[j] = nums[i];
7136
}
7237
}
38+
7339
return j + 1;
7440
}
7541
}

0 commit comments

Comments
 (0)