Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Remove All Adjacent Duplicates in String II
Next article icon

Insert an adjacent duplicate for all occurrences of a given element

Last Updated : 07 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size n and an integer k, the task is to insert a duplicate of k adjacent to its every occurrence. Keep array’s original length same by removing the elements from the back.

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

Table of Content

  • [Naive Approach] – Using Built-In/Library Functions – O(n^2) Time and O(n) Space
  • [Expected Approach] – Using Two Pointer Technique- O(n) Time and O(1) Space

[Naive Approach] – One by One Insert and Truncate – O(n^2) Time and O(n) Space

This problem can be solved by using built-in or library functions to insert element or remove element from the back. The idea is to traverse the array and insert a duplicate of K right next to it and then pop the last element.

C++
#include <iostream> #include <vector> using namespace std;  vector<int> duplicateK(vector<int> arr, int k) {     int n = arr.size();     for(int i = 0; i < n; i++) {         if(arr[i] == k) {                          // Insert an adjacent k             arr.insert(arr.begin() + i + 1, k);             i++;                          // Pop the last element             arr.pop_back();         }     }     return arr; }  int main() {     vector<int> arr = { 1, 0, 2, 3, 0, 4, 5, 0 };     int k = 0;     vector<int> ans = duplicateK(arr, k);      for(int i = 0; i < ans.size(); i++)         cout << ans[i] << " ";     return 0; } 
Java
import java.util.Arrays;  public class GfG {     public static int[] duplicateK(int[] arr, int k) {         int n = arr.length;                  // Maximum size after duplication         int[] result = new int[n * 2];                   int index = 0;         for (int i = 0; i < n; i++) {             result[index++] = arr[i];             if (arr[i] == k) {                                  // Insert an adjacent k                 result[index++] = k;             }         }                  // Resize to the actual size         return Arrays.copyOf(result, index);     }      public static void main(String[] args) {         int[] arr = {1, 0, 2, 3, 0, 4, 5, 0};         int k = 0;         int[] ans = duplicateK(arr, k);          for (int i = 0; i < ans.length; i++)             System.out.print(ans[i] + " ");     } } 
Python
def duplicateK(arr, k):     n = len(arr)     for i in range(n):         if arr[i] == k:                          # Insert an adjacent k             arr.insert(i + 1, k)             i += 1                          # Pop the last element             arr.pop()     return arr  if __name__ == '__main__':     arr = [1, 0, 2, 3, 0, 4, 5, 0]     k = 0     ans = duplicateK(arr, k)      for i in ans:         print(i, end=' ') 
C#
using System; using System.Collections.Generic;  class GfG {     static void Main() {         int[] arr = { 1, 0, 2, 3, 0, 4, 5, 0 };         int k = 0;         int[] ans = DuplicateK(arr, k);          foreach (int i in ans) {             Console.Write(i + " ");         }     }      static int[] DuplicateK(int[] arr, int k) {         int n = arr.Length;         for (int i = 0; i < n; i++) {             if (arr[i] == k) {                 // Insert an adjacent k                 List<int> tempList = new List<int>(arr);                 tempList.Insert(i + 1, k);                 arr = tempList.ToArray();                 i++;                 // Pop the last element                 Array.Resize(ref arr, arr.Length - 1);             }         }         return arr;     } } 
JavaScript
function duplicateK(arr, k) {     let n = arr.length;     for (let i = 0; i < n; i++) {         if (arr[i] === k) {                          // Insert an adjacent k             arr.splice(i + 1, 0, k);             i++;                          // Pop the last element             arr.pop();         }     }     return arr; }  const arr = [1, 0, 2, 3, 0, 4, 5, 0]; const k = 0; const ans = duplicateK(arr, k);  for (let i of ans) {     process.stdout.write(i + ' '); } 

Output: 

1 0 0 2 3 0 0 4 

[Expected Approach] – Using Two Pointer Technique- O(n) Time and O(1) Space

This approach first counts how many times k appears and then create two pointers ( curr, write_idx) where the first one points to the last index of the current array and the second one points to the sum of last index and the count of k.

Then, starting from the last element, it copies each element to its new position and, if the element is k, places another k next to it. This avoids overwriting any elements that need to be preserved.

  • 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 to know the number of last elements to be removed.
  • 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 the current array, which is arr[n-1].
  • Iterate from the end and for each element we assume that we are copying the element to its current position, but copy only if the write_idx < N, and keep updating the write_idx each time. For an element with a value of zero, write it twice.
C++
#include <bits/stdc++.h> using namespace std;  vector<int> duplicateK(vector<int>& arr,int k) {     const int n = arr.size();      // Find the count of total number of k     int cnt = count(arr.begin(), arr.end(), k);      // 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 the size N         if (write_idx < N)             arr[write_idx] = arr[curr];          write_idx -= 1;          // Check if the current element is also         // k then again write its duplicate         if (arr[curr] == k) {             if (write_idx < n)                 arr[write_idx] = k;              write_idx -= 1;         }          --curr;     }     return arr; }  int main() {     vector<int> arr = { 1, 0, 2, 3, 0, 4, 5, 0 };     int k=0;     vector<int> ans = duplicateK(arr,k);      for (int i = 0; i < ans.size(); i++)         cout << ans[i] << " ";      return 0; } 
Java
class GfG{  static int[] duplicateK(int []arr,int k) {          int n = arr.length;          // Find the count of     // total number of k     int cnt = count(arr, k);          // 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 the size N         if (write_idx < n)             arr[write_idx] = arr[curr];              write_idx -= 1;              // Check if the current element is also         // k then again write its duplicate         if (arr[curr] == k)         {             if (write_idx < n)                 arr[write_idx] = k;                              write_idx -= 1;         }         --curr;     }     return arr; }  static int count(int []arr, int num) {     int ans = 0;     for(int i : arr)             if(i == num)           ans++;     return ans; }  public static void main(String[] args) {     int []arr = { 1, 0, 2, 3, 0, 4, 5, 0 };     int k=0;     int []ans = duplicateK(arr,k);      for(int i = 0; i < ans.length; i++)        System.out.print(ans[i] + " "); } } 
Python
def duplicate_k(arr, k):     n = len(arr)      # Find the count of total number of k     cnt = arr.count(k)      # 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         # k then again write its duplicate         if arr[curr] == k:             if write_idx < n:                 arr[write_idx] = k              write_idx -= 1          curr -= 1     return arr  if __name__ == '__main__':     arr = [1, 0, 2, 3, 0, 4, 5, 0]     k = 0     ans = duplicate_k(arr, k)      for i in ans:         print(i, end=' ') 
C#
using System;  class GfG {     static int[] DuplicateK(int[] arr, int k)     {         int n = arr.Length;                  // Find the count of total number of k         int cnt = Count(arr, k);                  // Variable to store index where elements          // will be written in the final array         int writeIdx = n + cnt - 1;                  // Variable to point the current index         int curr = n - 1;         while (curr >= 0 && writeIdx >= 0)         {             // Keep the current element to its correct              // position, if that is within the size N             if (writeIdx < n)                 arr[writeIdx] = arr[curr];             writeIdx -= 1;                          // Check if the current element is also              // k then again write its duplicate             if (arr[curr] == k)             {                 if (writeIdx < n)                     arr[writeIdx] = k;                 writeIdx -= 1;             }             --curr;         }         return arr;     }      static int Count(int[] arr, int num)     {         int ans = 0;         foreach (int i in arr)             if (i == num)                 ans++;         return ans;     }      public static void Main(string[] args)     {         int[] arr = { 1, 0, 2, 3, 0, 4, 5, 0 };         int k = 0;         int[] ans = DuplicateK(arr, k);         for (int i = 0; i < ans.Length; i++)             Console.Write(ans[i] + " ");     } } 
JavaScript
function duplicateK(arr, k) {     const n = arr.length;      // Find the count of total number of k     const cnt = arr.filter(x => x === k).length;      // Variable to store index where elements     // will be written in the final array     let write_idx = n + cnt - 1;      // Variable to point the current index     let curr = n - 1;      while (curr >= 0 && 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         // k then again write its duplicate         if (arr[curr] === k) {             if (write_idx < n) {                 arr[write_idx] = k;             }              write_idx -= 1;         }          curr--;     }     return arr; }  const arr = [1, 0, 2, 3, 0, 4, 5, 0]; const k = 0; const ans = duplicateK(arr, k); ans.forEach(num => console.log(num)); 

Output
1 0 0 2 3 0 0 4


Next Article
Remove All Adjacent Duplicates in String II
author
coder001
Improve
Article Tags :
  • Arrays
  • DSA
  • Write From Home
  • two-pointer-algorithm
Practice Tags :
  • Arrays
  • two-pointer-algorithm

Similar Reads

  • Modify a Linked List to contain last occurrences of every duplicate element
    Given an unsorted Singly Linked List consisting of N nodes that may contain duplicate elements, the task is to remove all but the last occurrence of duplicate elements from the Linked List. Examples: Input: 1 -> 2 -> 7 -> 3 -> 2 -> 5 -> 1Output: 7 -> 3 -> 2 -> 5 -> 1Exp
    10 min read
  • Check if all duplicate elements in the Array are adjacent or not
    Given an array arr[]. The task is to check whether duplicate elements in arr[] are contiguous or not. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: Yes Explanation: There is no duplicate element in arr[] so there is no need to check anything and answer is Yes. Input: arr[] = {1, 2, 2, 4} Outpu
    4 min read
  • Move all occurrences of an element to end in a linked list
    Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7
    15+ min read
  • Remove all occurrences of duplicates from a sorted Linked List
    Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list. Examples: Input : 23->28->28->35->49->49->53->53 Output : 23->35 Input : 11->11->11->11->75->75 Output : empt
    10 min read
  • Remove All Adjacent Duplicates in String II
    Given a string s and an integer k, the task is to repeatedly delete k adjacent duplicates till no deletions are possible and then return the final string. On deletion of k adjacent duplicates, the left and right sides of the deleted substring is concatenated together. Examples: Input: s = "abcd", k
    3 min read
  • Find duplicate elements in an array
    Given an array of n integers. The task is to find all elements that have more than one occurrences. The output should only be one occurrence of a number irrespective of the number of occurrences in the input array. Examples: Input: {2, 10, 10, 100, 2, 10, 11, 2, 11, 2}Output: {2, 10, 11} Input: {5,
    11 min read
  • Recursively remove all adjacent duplicates
    Given a string S, the task is to remove all its adjacent duplicate characters recursively. Examples: Input: S = "geeksforgeek"Output: "gksforgk"Explanation: g(ee)ksforg(ee)k -> gksforgk Input: S = "abccbccba"Output: ""Explanation: ab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->"" (empty
    13 min read
  • Find duplicates in constant array with elements 0 to N-1 in O(1) space
    Given a constant array of n elements which contains elements from 1 to n-1, with any of these numbers appearing any number of times. Find any one of these repeating numbers in O(n) and using only constant memory space. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 3} Output : 3 As the given array is
    12 min read
  • Print a closest string that does not contain adjacent duplicates
    Given a string S, change the smallest number of letters in S such that all adjacent characters are different. Print the resultant string. Examples : Input: S = "aab"Output: acbExplanation: Loop will start for i-th character, which is second ‘a’. It’s cannot be ‘b’ since it matches with third char. S
    9 min read
  • Modify given array by incrementing first occurrence of every element by K
    Given an array arr[] consisting of N integers, read every element of the array one by one and perform the following operations: If the current element arr[i] had previously occurred in the array, increase its first occurrence by K.Otherwise, insert arr[i] into the sequenceThe task is to print the fi
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences