Insert an adjacent duplicate for all occurrences of a given element

 

Input: arr[] = [1, 0, 2, 3, 0, 4, 5, 0], K = 0 
Output: [1, 0, 0, 2, 3, 0, 0, 4]
Explanation: The given array [1, 0, 2, 3, 0, 4, 5, 0] is modified to [1, 0, 0, 2, 3, 0, 0, 4] after insertion of two 0's and truncation of two extra elements.

Input: arr[] = [7, 5, 8], K = 8 
Output: [7, 5, 8] 
Explanation: After inserting an adjacent 8 into the array, it got truncated to restore the original size of the array.  

 

 class GFG {

    public int[] insertDuplicateK(int[] arr, int k) {
        int n = arr.length;
        int[] res = new int[n];
        int j = 0; 

        for (int i = 0; i < n && j < n; i++) {
            res[j++] = arr[i];
            if (arr[i] == k && j < n) {
                res[j++] = k;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        GFG obj = new GFG();
        int[] arr = {1, 0, 2, 3, 0, 4, 5, 0};
        int k = 0;

        int[] result = obj.insertDuplicateK(arr, k);
        for (int num : result) {
            System.out.print(num + " ");
        }
    }
}

Comments

Popular Posts