# Insert duplicate of K adjacent to it for it’s every occurrence in array

Given an array arr consisting of N integers and an integer K, the task is to insert an adjacent K for every occurrence of it in the original sequence and then truncate the array to the original length using O(1) auxiliary space.
Examples:

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 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.

Approach 1: Using STL functions
This problem can be solved by using built-in functions pop_back() and insert() .

Below is the implementation of the above approach:

## C++

 `// C++ implementation to update each entry of zero ` `// with two zero entries adjacent to each other ` `#include ` `using` `namespace` `std; ` ` `  `// Function to update each entry of zero ` `// with two zero entries adjacent to each other ` `vector<``int``> duplicateK(vector<``int``>& arr) ` `{ ` `    ``int` `N = arr.size(); ` `    ``for``(``int` `i=0;i arr  ` `= { 1, 0, 2, 3, 0, 4, 5, 0  }; ` ` `  `    ``vector<``int``> ans = duplicateK(arr); ` ` `  `    ``for` `(``int` `i = 0; i < ans.size(); i++) ` `        ``cout << ans[i] << ``" "``; ` ` `  `    ``return` `0; ` `} `

## Java

 `// Java implementation to update each  ` `// entry of zero with two zero entries ` `// adjacent to each other ` `import` `java.util.*; ` ` `  `class` `GFG{ ` ` `  `// Function to update each entry of ` `// zero with two zero entries  ` `// adjacent to each other ` `static` `Vector duplicateK(Vector arr) ` `{ ` `    ``int` `N = arr.size(); ` `    ``for``(``int` `i = ``0``; i < N; i++) ` `    ``{ ` `       ``if``(arr.get(i) == ``0``) ` `       ``{ ` `            `  `           ``// Insert an adjacent 0 ` `           ``arr.add(i + ``1``, ``0``); ` `            `  `           ``i++; ` `            `  `           ``// Pop the last element ` `           ``arr.remove(arr.size() - ``1``); ` `       ``} ` `    ``} ` `    ``return` `arr; ` `} ` ` `  `// Driver code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``Integer []arr = { ``1``, ``0``, ``2``, ``3``, ``0``, ``4``, ``5``, ``0` `}; ` `     `  `    ``Vector vec = ``new` `Vector();; ` `    ``for``(``int` `i = ``0``; i < arr.length; i++) ` `       ``vec.add(arr[i]); ` `         `  `    ``Vector ans = duplicateK(vec); ` ` `  `    ``for``(``int` `i = ``0``; i < ans.size(); i++) ` `       ``System.out.print(ans.get(i) + ``" "``); ` `} ` `} ` ` `  `// This code is contributed by gauravrajput1 `

## C#

 `// C# implementation to update each  ` `// entry of zero with two zero entries ` `// adjacent to each other ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG{ ` ` `  `// Function to update each entry of ` `// zero with two zero entries  ` `// adjacent to each other ` `static` `List<``int``> duplicateK(List<``int``> arr) ` `{ ` `    ``int` `N = arr.Count; ` `    ``for``(``int` `i = 0; i < N; i++) ` `    ``{ ` `        ``if``(arr[i] == 0) ` `        ``{ ` `                 `  `            ``// Insert an adjacent 0 ` `            ``arr.Insert(i + 1, 0); ` `                 `  `            ``i++; ` `                 `  `            ``// Pop the last element ` `            ``arr.RemoveAt(arr.Count - 1); ` `        ``} ` `    ``} ` `    ``return` `arr; ` `} ` ` `  `// Driver code ` `public` `static` `void` `Main(String[] args) ` `{ ` `    ``int` `[]arr = { 1, 0, 2, 3, 0, 4, 5, 0 }; ` `     `  `    ``List<``int``> vec = ``new` `List<``int``>();; ` `    ``for``(``int` `i = 0; i < arr.Length; i++) ` `    ``vec.Add(arr[i]); ` `         `  `    ``List<``int``> ans = duplicateK(vec); ` ` `  `    ``for``(``int` `i = 0; i < ans.Count; i++) ` `    ``Console.Write(ans[i] + ``" "``); ` `} ` `} ` ` `  `// This code is contributed by gauravrajput1  `

Output:

```1 0 0 2 3 0 0 4
```

Approach 2: Using Two Pointer Technique

• Since each K needs to be updated with two K entries adjacent to each other, the array will increase in length by an amount equal to the number of K that are present in the original array arr[].
• Find the total number of K, then we assume we have an array with enough space to accommodate every element.
• Initialize a variable write_idx that will point to the index at the end of this imaginary array and another pointer curr at the end of actual array that is arr[N-1].
• Iterate from the end and for each element we assume that we are copying the element to its actual position, but copy only if the write_idx < N, and keep updating the write_idx each time. For an element with value zero write it twice.

Below is the implementation of the above approach:

## C++

 `// C++ implementation to update each entry of zero ` `// with two zero entries adjacent to each other ` `#include ` `using` `namespace` `std; ` ` `  `// Function to update each entry of zero ` `// with two zero entries adjacent to each other ` `vector<``int``> duplicateZeros(vector<``int``>& arr) ` `{ ` `    ``const` `int` `N = arr.size(); ` ` `  `    ``// Find the count of total number of zeros ` `    ``int` `cnt = count(arr.begin(), arr.end(), 0); ` ` `  `    ``// Variable to store index where elements ` `    ``// will be written in the final array ` `    ``int` `write_idx = N + cnt - 1; ` ` `  `    ``// Variable to point the current index ` `    ``int` `curr = N - 1; ` ` `  `    ``while` `(curr >= 0 && write_idx >= 0) { ` `        ``// Keep the current element to its correct ` `        ``// position, if that is within teh size N ` `        ``if` `(write_idx < N) ` `            ``arr[write_idx] = arr[curr]; ` ` `  `        ``write_idx -= 1; ` ` `  `        ``// Check if the current element is also ` `        ``// zero then again write its duplicate ` `        ``if` `(arr[curr] == 0) { ` `            ``if` `(write_idx < N) ` `                ``arr[write_idx] = 0; ` ` `  `            ``write_idx -= 1; ` `        ``} ` ` `  `        ``--curr; ` `    ``} ` ` `  `    ``// Return the final result ` `    ``return` `arr; ` `} ` ` `  `// Driver code ` `int` `main(``int` `argc, ``char``* argv[]) ` `{ ` `    ``vector<``int``> arr = { 1, 0, 2, 3, 0, 4, 5, 0 }; ` ` `  `    ``vector<``int``> ans = duplicateZeros(arr); ` ` `  `    ``for` `(``int` `i = 0; i < ans.size(); i++) ` `        ``cout << ans[i] << ``" "``; ` ` `  `    ``return` `0; ` `} `

## Java

 `// Java implementation to update  ` `// each entry of zero with two zero  ` `// entries adjacent to each other ` `class` `GFG{ ` ` `  `// Function to update each  ` `// entry of zero with two zero  ` `// entries adjacent to each other ` `static` `int``[] duplicateZeros(``int` `[]arr) ` `{ ` `     `  `    ``int` `N = arr.length; ` `     `  `    ``// Find the count of ` `    ``// total number of zeros ` `    ``int` `cnt = count(arr, ``0``); ` `     `  `    ``// Variable to store index  ` `    ``// where elements will be  ` `    ``// written in the final array ` `    ``int` `write_idx = N + cnt - ``1``; ` `     `  `    ``// Variable to point the current index ` `    ``int` `curr = N - ``1``; ` `     `  `    ``while` `(curr >= ``0` `&& write_idx >= ``0``) ` `    ``{ ` `         `  `        ``// Keep the current element  ` `        ``// to its correctposition, if  ` `        ``// that is within teh size N ` `        ``if` `(write_idx < N) ` `            ``arr[write_idx] = arr[curr]; ` `     `  `        ``write_idx -= ``1``; ` `     `  `        ``// Check if the current element is also ` `        ``// zero then again write its duplicate ` `        ``if` `(arr[curr] == ``0``) ` `        ``{ ` `            ``if` `(write_idx < N) ` `                ``arr[write_idx] = ``0``; ` `                 `  `            ``write_idx -= ``1``; ` `        ``} ` `        ``--curr; ` `    ``} ` `     `  `    ``// Return the final result ` `    ``return` `arr; ` `} ` ` `  `static` `int` `count(``int` `[]arr, ``int` `num) ` `{ ` `    ``int` `ans = ``0``; ` `    ``for``(``int` `i : arr) ` `     `  `       ``if``(i == num) ` `          ``ans++; ` `    ``return` `ans; ` `} ` ` `  `// Driver code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``int` `[]arr = { ``1``, ``0``, ``2``, ``3``, ``0``, ``4``, ``5``, ``0` `}; ` `    ``int` `[]ans = duplicateZeros(arr); ` ` `  `    ``for``(``int` `i = ``0``; i < ans.length; i++) ` `       ``System.out.print(ans[i] + ``" "``); ` `} ` `} ` ` `  `// This code is contributed by Amit Katiyar `

## Python3

 `# Python3 implementation to update each entry of zero  ` `# with two zero entries adjacent to each other  ` ` `  `# Function to update each entry of zero  ` `# with two zero entries adjacent to each other  ` `def` `duplicateZeros(arr):  ` ` `  `    ``N ``=` `len``(arr)  ` ` `  `    ``# Find the count of total number of zeros  ` `    ``cnt ``=` `arr.count(``0``) ` ` `  `    ``# Variable to store index where elements  ` `    ``# will be written in the final array  ` `    ``write_idx ``=` `N ``+` `cnt ``-` `1` ` `  `    ``# Variable to point the current index  ` `    ``curr ``=` `N ``-` `1` ` `  `    ``while` `(curr >``=` `0` `and` `write_idx >``=` `0``):  ` `         `  `        ``# Keep the current element to its correct  ` `        ``# position, if that is within the size N  ` `        ``if` `(write_idx < N):  ` `            ``arr[write_idx] ``=` `arr[curr]  ` ` `  `        ``write_idx ``-``=` `1` ` `  `        ``# Check if the current element is also  ` `        ``# zero then again write its duplicate  ` `        ``if` `(arr[curr] ``=``=` `0``):  ` `            ``if` `(write_idx < N):  ` `                ``arr[write_idx] ``=` `0` ` `  `            ``write_idx ``-``=` `1` ` `  `        ``curr ``-``=` `1` ` `  `    ``# Return the final result  ` `    ``return` `arr  ` ` `  `# Driver Code  ` `arr ``=` `[ ``1``, ``0``, ``2``, ``3``, ``0``, ``4``, ``5``, ``0` `] ` ` `  `ans ``=` `duplicateZeros(arr)  ` `for` `i ``in` `range``(``len``(ans)): ` `    ``print``(ans[i], end ``=` `" "``)  ` `     `  `# This code is contributed by divyamohan123  `

## C#

 `// C# implementation to update  ` `// each entry of zero with two zero  ` `// entries adjacent to each other ` `using` `System; ` ` `  `class` `GFG{ ` ` `  `// Function to update each  ` `// entry of zero with two zero  ` `// entries adjacent to each other ` `static` `int``[] duplicateZeros(``int` `[]arr) ` `{ ` `    ``int` `N = arr.Length; ` `     `  `    ``// Find the count of ` `    ``// total number of zeros ` `    ``int` `cnt = count(arr, 0); ` `     `  `    ``// Variable to store index  ` `    ``// where elements will be  ` `    ``// written in the readonly array ` `    ``int` `write_idx = N + cnt - 1; ` `     `  `    ``// Variable to point the  ` `    ``// current index ` `    ``int` `curr = N - 1; ` `     `  `    ``while` `(curr >= 0 && write_idx >= 0) ` `    ``{ ` `         `  `        ``// Keep the current element  ` `        ``// to its correctposition, if  ` `        ``// that is within teh size N ` `        ``if` `(write_idx < N) ` `            ``arr[write_idx] = arr[curr]; ` `     `  `        ``write_idx -= 1; ` `     `  `        ``// Check if the current element is also ` `        ``// zero then again write its duplicate ` `        ``if` `(arr[curr] == 0) ` `        ``{ ` `            ``if` `(write_idx < N) ` `                ``arr[write_idx] = 0; ` `                 `  `            ``write_idx -= 1; ` `        ``} ` `        ``--curr; ` `    ``} ` `     `  `    ``// Return the readonly result ` `    ``return` `arr; ` `} ` ` `  `static` `int` `count(``int` `[]arr, ``int` `num) ` `{ ` `    ``int` `ans = 0; ` `    ``foreach``(``int` `i ``in` `arr) ` `    ``{ ` `        ``if``(i == num) ` `           ``ans++; ` `    ``} ` `    ``return` `ans; ` `} ` ` `  `// Driver code ` `public` `static` `void` `Main(String[] args) ` `{ ` `    ``int` `[]arr = { 1, 0, 2, 3, 0, 4, 5, 0 }; ` `    ``int` `[]ans = duplicateZeros(arr); ` ` `  `    ``for``(``int` `i = 0; i < ans.Length; i++) ` `       ``Console.Write(ans[i] + ``" "``); ` `} ` `} ` ` `  `// This code is contributed by Amit Katiyar `

Output:

```1 0 0 2 3 0 0 4
```

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up I am currently pursuing B Tech (Hons) in Computer Science I love technology and explore new things I want to become a very good programmer I love to travel and meet new peoples

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.