This is another popular coding interview question. I had faced this question during my interview with Reliance Jio.
You are given a sorted array like { 2,2,2,2}, so the final array would be {2}.
Examples:
Input: arr[]={5,5,5,5}
Output: arr[]={5}
Input: arr[]={1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[]={1,2,3,4,5}
Logic: To solve this problem, we will take another variable as j. Every time we will check i th element with i+1 th element. If it does not match, will increase j with j+1.
Program:
public class DuplicateArrayElement {
static int removeDuplicates(int arr[], int n)
{
if (n == 0 || n == 1)
return n;
//Taking extra index which will be increased based on iTh and i+1 Th index
int j = 0;
for (int i = 0; i < n-1; i++)
if (arr[i] != arr[i+1])
arr[j++] = arr[i];
arr[j++] = arr[n-1];
return j;
}
//** Main method to test the method removeDuplicates()**//
public static void main (String[] args)
{
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = arr.length;
n = removeDuplicates(arr, n);
for (int i=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}
You are given a sorted array like { 2,2,2,2}, so the final array would be {2}.
Examples:
Input: arr[]={5,5,5,5}
Output: arr[]={5}
Input: arr[]={1, 2, 2, 3, 4, 4, 4, 5, 5}
Output: arr[]={1,2,3,4,5}
Logic: To solve this problem, we will take another variable as j. Every time we will check i th element with i+1 th element. If it does not match, will increase j with j+1.
Program:
public class DuplicateArrayElement {
static int removeDuplicates(int arr[], int n)
{
if (n == 0 || n == 1)
return n;
//Taking extra index which will be increased based on iTh and i+1 Th index
int j = 0;
for (int i = 0; i < n-1; i++)
if (arr[i] != arr[i+1])
arr[j++] = arr[i];
arr[j++] = arr[n-1];
return j;
}
//** Main method to test the method removeDuplicates()**//
public static void main (String[] args)
{
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = arr.length;
n = removeDuplicates(arr, n);
for (int i=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}
No comments:
Post a Comment