Open In App

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:

The task is to print the final sequence of integers obtained by performing the above operations

Examples:

Input: arr[] = {1, 2, 3, 2, 3}, K = 1
Output: [1, 4, 3, 2, 3]
Explanation:

Arrival : 1
Since 1 is the first element in the stream, simply insert it into the solution.
Therefore, b[] = [1]

Arrival: 2
Since 2 is not existing in the array, simply insert it into the solution.
Therefore, b[] = [1, 2]

Arrival: 3
Since 3 is not existing in the array, simply insert it into the solution.
Therefore, b[] = [1, 2, 3]

Arrival: 2
Since 2 already exists, increasing its first occurrence by K(=1)modifies the array b[] to [1, 3, 3, 2]

Arrival: 3
Since 3 already exists, increasing its first occurrence by K(=1)modifies the array b[] to [1, 4, 3, 2, 3]

Input: arr[] = {1, 4, 1, 1, 4}, K = 6
Output: [7, 10, 7, 1, 4]

Naive Approach: The simplest approach to solve the problem is to traverse the array, and for every array element arr[i], traverse in the range [0, i - 1] to check if arr[i] is already present in the array or not. If found to be true, increase the first occurrence of arr[i] by K.

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

Efficient Approach: The above approach can be optimized using Hashing. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

// C++ Program to implement
// the above approach

#include <bits/stdc++.h>
using namespace std;

// Print the required final sequence
void printSequence(vector<int>& A,
                   int n, int k)
{
    // Stores the array element-index pairs
    unordered_map<int, set<int> > mp;

    // Stores the required sequence
    vector<int> sol;

    // Insert all array elements
    for (int x : A)
        sol.push_back(x);

    for (int i = 0; i < n; i++) {
        // If current element has
        // not occurred previously
        if (mp.find(sol[i]) == mp.end()
            || mp[sol[i]].size() == 0) {
            mp[sol[i]].insert(i);
        }

        // Otherwise
        else {

            // Iterator to the first index
            // containing sol[i]
            auto idxx = mp[sol[i]].begin();

            int idx = *idxx;

            // Remove that occurrence
            mp[sol[i]].erase(idxx);

            // Increment by K
            sol[idx] += k;

            // Insert the incremented
            // element at that index
            mp[sol[idx]].insert(idx);
            mp[sol[i]].insert(i);
        }
    }

    // Print the final sequence
    for (int x : sol) {
        cout << x << " ";
    }
}

// Driver Code
int main()
{
    int N = 5;
    int K = 6;
    vector<int> A = { 1, 4, 1, 1, 4 };
    printSequence(A, N, K);
}
import java.util.*;

public class Main {

    // Print the required final sequence
    static void printSequence(int[] A, int n, int k) {
        // Stores the array element-index pairs
        Map<Integer, Set<Integer>> mp = new HashMap<>();

        // Stores the required sequence
        List<Integer> sol = new ArrayList<>();

        // Insert all array elements
        for (int x : A)
            sol.add(x);

        for (int i = 0; i < n; i++) {
            // If current element has not occurred previously
            if (!mp.containsKey(sol.get(i)) || mp.get(sol.get(i)).size() == 0) {
                mp.computeIfAbsent(sol.get(i), key -> new HashSet<>()).add(i);
            } else {
                // Iterator to the first index containing sol[i]
                Iterator<Integer> idxx = mp.get(sol.get(i)).iterator();

                int idx = idxx.next();

                // Remove that occurrence
                idxx.remove();

                // Increment by K
                sol.set(idx, sol.get(idx) + k);

                // Insert the incremented element at that index
                mp.computeIfAbsent(sol.get(idx), key -> new HashSet<>()).add(idx);
                mp.computeIfAbsent(sol.get(i), key -> new HashSet<>()).add(i);
            }
        }

        // Print the final sequence
        for (int x : sol) {
            System.out.print(x + " ");
        }
    }

    // Driver Code
    public static void main(String[] args) {
        int N = 5;
        int K = 6;
        int[] A = {1, 4, 1, 1, 4};
        printSequence(A, N, K);
    }
}
# Python3 Program to implement the above approach

import collections

def printSequence(A, n, k):
    # Stores the array element-index pairs
    mp = collections.defaultdict(set)

    # Stores the required sequence
    sol = []

    # Insert all array elements
    for x in A:
        sol.append(x)

    for i in range(n):
        # If current element has not occurred previously
        if sol[i] not in mp or len(mp[sol[i]]) == 0:
            mp[sol[i]].add(i)
        # Otherwise
        else:
            # Get the first index containing sol[i]
            idx = mp[sol[i]].pop()

            # Increment by K
            sol[idx] += k

            # Insert the incremented element at that index
            mp[sol[idx]].add(idx)
            mp[sol[i]].add(i)

    # Print the final sequence
    print(" ".join(map(str, sol)))

# Driver Code
N = 5
K = 6
A = [1, 4, 1, 1, 4]
printSequence(A, N, K)
using System;
using System.Collections.Generic;

class Program {
  static void Main(string[] args) {
    int N = 5;
    int K = 6;
    List<int> A = new List<int> { 1, 4, 1, 1, 4 };
    printSequence(A, N, K);
  }

  static void printSequence(List<int> A, int n, int k) {
    // Stores the array element-index pairs
    Dictionary<int, HashSet<int>> mp = new Dictionary<int, HashSet<int>>();

    // Stores the required sequence
    List<int> sol = new List<int>();

    // Insert all array elements
    foreach (int x in A)
      sol.Add(x);

    for (int i = 0; i < n; i++) {
      // If current element has not occurred previously
      if (!mp.ContainsKey(sol[i]) || mp[sol[i]].Count == 0) {
        mp[sol[i]] = new HashSet<int>();
        mp[sol[i]].Add(i);
      }

      // Otherwise
      else {
        // Iterator to the first index containing sol[i]
        var idxx = mp[sol[i]].GetEnumerator();
        idxx.MoveNext();
        int idx = idxx.Current;

        // Remove that occurrence
        mp[sol[i]].Remove(idx);

        // Increment by K
        sol[idx] += k;

        // Insert the incremented element at that index
        if (!mp.ContainsKey(sol[idx])) {
          mp[sol[idx]] = new HashSet<int>();
        }
        mp[sol[idx]].Add(idx);
        mp[sol[i]].Add(i);
      }
    }

    // Print the final sequence
    foreach (int x in sol) {
      Console.Write(x + " ");
    }
  }
}
<script>

// Javascript program to implement
// the above approach

// Print the required final sequence
function printSequence(A, n, k)
{
    
    // Stores the array element-index pairs
    var mp = new Map();

    // Stores the required sequence
    var sol = [];

    // Insert all array elements
    A.forEach(x => {
        sol.push(x);
    });

    for(var i = 0; i < n; i++) 
    {
        
        // If current element has
        // not occurred previously
        if (!mp.has(sol[i]) || 
             mp.get(sol[i]).size == 0) 
        {
            var tmp = new Set();
            tmp.add(i)
            mp.set(sol[i],tmp)
        }

        // Otherwise
        else
        {
            
            // Iterator to the first index
            // containing sol[i]
            var idxx = [...mp.get(sol[i])].sort(
                (a, b) => a - b)[0];

            var idx = idxx;

            // Remove that occurrence
            var x = mp.get(sol[i]);
            x.delete(idxx);
            mp.set(sol[i], x);

            // Increment by K
            sol[idx] += k;

            // Insert the incremented
            // element at that index
            if (!mp.has(sol[idx]))
                mp.set(sol[idx], new Set())
                
            x = mp.get(sol[idx]);
            x.add(idx);
            mp.set(sol[idx], x);

            x = mp.get(sol[i]);
            x.add(i);
            mp.set(sol[i], x);
        }
    }

    // Print the final sequence
    sol.forEach(x => {
        document.write(x + " ");
    });
}

// Driver Code
var N = 5;
var K = 6;
var A = [ 1, 4, 1, 1, 4 ];

printSequence(A, N, K);

// This code is contributed by importantly

</script> 

Output
7 10 7 1 4

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


 

Article Tags :