Open In App

Find just strictly greater element from first array for each element in second array

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given two arrays A[] and B[] containing N elements, the task is to find, for every element in the array B[], the element which is just strictly greater than that element which is present in the array A[]. If no value is present, then print ‘null’.

Note: The value from the array A[] can only be used once. 

Examples:  

Input: A[] = {0, 1, 2, 3, 4}, B[] = {0, 1, 1, 2, 3} 
Output: 1 2 3 4 null 
Explanation: 
On iterating every element in the array B[]: 
The value which is strictly greater than 0 and present in the array A[] is 1. 
Similarly, the value which is strictly greater than 1 and present in the array A[] is 2. 
Similarly, the value which is strictly greater than 1 and present in the array A[] is 3 because 2 has already been used for the previous 1. 
Similarly, the value which is strictly greater than 2 and present in the array A[] is 4. 
Now, there is no value in the array which is greater than 3 because 4 has already been used for the previous 2. So, null is printed. 

Input: A[] = {0, 1, 6, 4, 0, 2, 4, 2, 4, 7}, B[] = {0, 1, 6, 4, 0, 2, 4, 2, 4, 7} 
Output: 1 2 7 6 2 4 null 4 null null 

Approach: The idea is to use the Tree set Data structure. But since a tree set doesn’t support duplicate values, a hashmap is used to store the frequency of the elements.  

  • Iterate through the array A[].
  • Add the elements in the array A[] into the tree set.
  • Update their frequencies in the hashmap.
  • Now, for every element in the array B[], find the value which is strictly greater than the current value by using the higher() function of the tree set.
  • Now, reduce the frequency of this number in the hash map by 1.
  • Keep repeating the above two steps until the frequency of the numbers become 0. If it is 0, then all the occurrences of that number have been used up for the elements. So, remove that element from the tree set.

Below is the implementation of the above approach: 

C++




// C++ program to find the values
// strictly greater than the element
// and present in the array
#include<bits/stdc++.h>
using namespace std;
 
// Function to find the values
// strictly greater than the element
// and present in the array
void operations(int n, long long A[],
                       long long B[])
{
     
    // Treeset to store the
    // values of the array A
    set<long long>tree;
     
    // HashMap to store the frequencies
    // of the values in array A
    map<long long, int>freqMap;
 
    // Iterating through the array
    // and add values in the treeset
    for(int j = 0; j < n; j++)
    {
        long long x = A[j];
        tree.insert(x);
        freqMap[x]++;
    }
 
    // Finding the strictly greater value
    // in the array A[] using "higher()"
    // function and also reducing the
    // frequency of that value because it
    // has to be used only once
    for(int j = 0; j < n; j++)
    {
        long long  x = B[j];
 
        // If the higher value exists
        if (tree.upper_bound(x) != tree.end())
        {
            cout << *tree.upper_bound(x) << " ";
             
            // If the frequency value is 1
            // then remove it from treeset
            // because it has been used
            // and its frequency becomes 0
            if (freqMap[*tree.upper_bound(x)] == 1)
            {
                tree.erase(*tree.upper_bound(x));
            }
             
            // Else, reducing the frequency
            // by 1
            else
            {
                freqMap[*tree.upper_bound(x)]--;
            }
        }
 
        // If the value is not present
        // then print null
        else
        {
            cout << "null ";
        }
    }
}
 
// Driver code
int main()
{
    int n = 12;
    long long A[] = { 9, 5, 100, 4, 89, 2,
                      0, 2, 89, 77, 77, 77 };
    long long B[] = { 0, 18, 60, 34, 50, 29,
                      4, 20, 48, 77, 2, 8 };
     
    operations(n, A, B);
}
 
// This code is contributed by Stream_Cipher


Java




// Java program to find the values
// strictly greater than the element
// and present in the array
 
import java.io.*;
import java.util.*;
public class GFG {
 
    // Function to find the values
    // strictly greater than the element
    // and present in the array
    public static void operations(
        int n, long A[], long B[])
    {
 
        // Treeset to store the
        // values of the array A
        TreeSet<Long> tree
            = new TreeSet<Long>();
 
        // HashMap to store the frequencies
        // of the values in array A
        HashMap<Long, Integer> freqMap
            = new HashMap<Long, Integer>();
 
        // Iterating through the array
        // and add values in the treeset
        for (int j = 0; j < n; j++) {
            long x = A[j];
            tree.add(x);
 
            // Updating the frequencies
            if (freqMap.containsKey(x)) {
 
                freqMap.put(x, freqMap.get(x) + 1);
            }
            else {
 
                freqMap.put(x, 1);
            }
        }
 
        // Finding the strictly greater value
        // in the array A[] using "higher()"
        // function and also reducing the
        // frequency of that value because it
        // has to be used only once
        for (int j = 0; j < n; j++) {
            long x = B[j];
 
            // If the higher value exists
            if (tree.higher(x) != null) {
                System.out.print(tree.higher(x) + " ");
 
                // If the frequency value is 1
                // then remove it from treeset
                // because it has been used
                // and its frequency becomes 0
                if (freqMap.get(tree.higher(x)) == 1) {
                    tree.remove(tree.higher(x));
                }
 
                // Else, reducing the frequency
                // by 1
                else {
                    freqMap.put(
                        tree.higher(x),
                        freqMap.get(tree.higher(x))
                            - 1);
                }
            }
 
            // If the value is not present
            // then print null
            else {
                System.out.print("null ");
            }
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
 
        int n = 12;
        long A[] = new long[] { 9, 5, 100, 4,
                                89, 2, 0, 2,
                                89, 77, 77, 77 };
        long B[] = new long[] { 0, 18, 60, 34,
                                50, 29, 4, 20,
                                48, 77, 2, 8 };
 
        operations(n, A, B);
    }
}


Python3




# Python program to find the values
# strictly greater than the element
# and present in the array
from typing import List
from bisect import bisect_right
 
# Function to find the values
# strictly greater than the element
# and present in the array
def operations(n: int, A: List[int], B: List[int]) -> None:
 
    # Treeset to store the
    # values of the array A
    tree = set()
 
    # HashMap to store the frequencies
    # of the values in array A
    freqMap = dict()
 
    # Iterating through the array
    # and add values in the treeset
    for j in range(n):
        x = A[j]
        tree.add(x)
        if x not in freqMap:
            freqMap[x] = 0
        freqMap[x] += 1
 
    # Finding the strictly greater value
    # in the array A[] using "higher()"
    # function and also reducing the
    # frequency of that value because it
    # has to be used only once
    for j in range(n):
        x = B[j]
 
        # If the higher value exists
        sset = sorted(list(tree))
        index = bisect_right(sset, x)
        if index < len(tree):
            print(sset[index], end=" ")
 
            # If the frequency value is 1
            # then remove it from treeset
            # because it has been used
            # and its frequency becomes 0
            if (freqMap[sset[index]] == 1):
                tree.remove(sset[index])
 
            # Else, reducing the frequency
            # by 1
            else:
                freqMap[sset[index]] -= 1
 
        # If the value is not present
        # then print null
        else:
            print("null", end=" ")
 
# Driver code
if __name__ == "__main__":
 
    n = 12
    A = [9, 5, 100, 4, 89, 2, 0, 2, 89, 77, 77, 77]
    B = [0, 18, 60, 34, 50, 29, 4, 20, 48, 77, 2, 8]
 
    operations(n, A, B)
 
# This code is contributed by sanjeev2552


C#




// C# code for the above approach
using System;
using System.Collections.Generic;
 
namespace GFG
{
  class Program
  {
     
    // Function to find the values
    // strictly greater than the element
    // and present in the array
    static void operations(
      int n, long[] A, long[] B)
    {
       
      // Treeset to store the
      // values of the array A
      SortedSet<long> tree
        = new SortedSet<long>();
 
      // HashMap to store the frequencies
      // of the values in array A
      Dictionary<long, int> freqMap
        = new Dictionary<long, int>();
 
      // Iterating through the array
      // and add values in the treeset
      for (int j = 0; j < n; j++)
      {
        long x = A[j];
        tree.Add(x);
 
        // Updating the frequencies
        if (freqMap.ContainsKey(x))
        {
 
          freqMap[x] = freqMap[x] + 1;
        }
        else
        {
 
          freqMap[x] = 1;
        }
      }
 
      // Finding the strictly greater value
      // in the array A[] using "GetViewBetween()"
      // function and also reducing the
      // frequency of that value because it
      // has to be used only once
      for (int j = 0; j < n; j++)
      {
        long x = B[j];
 
        // If the higher value exists
        if (tree.GetViewBetween(x, long.MaxValue).Count > 0)
        {
          Console.Write(tree.GetViewBetween(x, long.MaxValue).Min + " ");
 
          // If the frequency value is 1
          // then remove it from treeset
          // because it has been used
          // and its frequency becomes 0
          if (freqMap[tree.GetViewBetween(x, long.MaxValue).Min] == 1)
          {
            tree.Remove(tree.GetViewBetween(x, long.MaxValue).Min);
          }
 
          // Else, reducing the frequency
          // by 1
          else
          {
            freqMap[tree.GetViewBetween(x, long.MaxValue).Min] =
              freqMap[tree.GetViewBetween(x, long.MaxValue).Min] - 1;
          }
        }
 
        // If the value is not present
        // then print null
        else
        {
          Console.Write("null ");
        }
      }
    }
 
    static void Main(string[] args)
    {
      int n = 12;
      long[] A = new long[] { 9, 5, 100, 4,
                             89, 2, 0, 2,
                             89, 77, 77, 77 };
      long[] B = new long[] { 0, 18, 60, 34,
                             50, 29, 4, 20,
                             48, 77, 2, 8 };
 
      operations(n, A, B);
    }
  }
}
 
// This code is contributed by Potta Lokesh


Javascript




// JavaScript program to find the values
// strictly greater than the element
// and present in the array
 
// Function to find the values
// strictly greater than the element
// and present in the array
function operations(n, A, B) {
 
     
    // Treeset to store the
    // values of the array A
    let tree = new Set();
     
    // HashMap to store the frequencies
    // of the values in array A
    let freqMap = new Map();
     
    // Iterating through the array
    // and add values in the treeset
    for (let j = 0; j < n; j++) {
        let x = A[j];
        tree.add(x);
        if (!freqMap.has(x)) {
            freqMap.set(x, 0);
        }
        freqMap.set(x, freqMap.get(x) + 1);
    }
     
    // Finding the strictly greater value
    // in the array A[] using "higher()"
    // function and also reducing the
    // frequency of that value because it
    // has to be used only once
    for (let j = 0; j < n; j++) {
        let x = B[j];
     
        // If the higher value exists
        let sset = Array.from(tree).sort((a, b) => a - b);
        let index = sset.findIndex(item => item > x);
        if (index >= 0) {
            process.stdout.write(sset[index] + " ");
     
            // If the frequency value is 1
            // then remove it from treeset
            // because it has been used
            // and its frequency becomes 0
            if (freqMap.get(sset[index]) === 1) {
                tree.delete(sset[index]);
            }
     
            // Else, reducing the frequency
            // by 1
            else {
                freqMap.set(sset[index], freqMap.get(sset[index]) - 1);
            }
        }
     
        // If the value is not present
        // then print null
        else {
            process.stdout.write("null ");
        }
    }
 
}
 
// Driver code
let n = 12;
let A = [9, 5, 100, 4, 89, 2, 0, 2, 89, 77, 77, 77];
let B = [0, 18, 60, 34, 50, 29, 4, 20, 48, 77, 2, 8];
 
operations(n, A, B);
 
// This code is contributed by phasing17


Output: 

2 77 77 77 89 89 5 100 null null 4 9

 

Time Complexity: O(N * log(N)) because the insertion of one element takes log(N) in a tree set.

Space Complexity: O(N) as set and map has been created to store elements.
 



Last Updated : 29 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads