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:
Count of elements whose absolute difference with the sum of all the other elements is greater than k
Next article icon

Count elements in first Array with absolute difference greater than K with an element in second Array

Last Updated : 15 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays arr1[] and arr2[] and an integer K, our task is to find the number elements in the first array, for an element x, in arr1[], there exists at least one element y, in arr2[] such that absolute difference of x and y is greater than the integer K.

Examples: 

Input: arr1 = {3, 1, 4}, arr2 = {5, 1, 2}, K = 2 
Output: 2 
Explanation: 
Such elements are 1 and 4. 
For 1, arr2[] has 5 and abs(1 – 5) = 4 which is greater than 2. 
For 4, arr2[] has 1 and abs(4 – 1) = 3 which again is greater than 2.

Input: arr1 = {1, 2}, arr2 = {4, 6}, K = 3 
Output: 2 
Explanation: 
Such elements are 1 and 2. 
For 1, arr2[] has 6 and abs(1 – 6) = 5 which is greater than 3. 
For 2, arr2[] has 6 and abs(2 – 6) = 4 which is greater than 3. 
 

Naive Approach: Iterate for each element in arr1[] and check whether or not there exists an element in arr2 such that their absolute difference is greater than the value K. 

Time complexity: O(N * M) where N and M are the sizes of the arrays 1 and 2 respectively.

Efficient Approach: To optimize the above method we have to observe that for each element in arr1[], we need only the smallest and largest element of arr2[] to check if it is distant or not. For each element x, in arr1, if the absolute difference of smallest or the largest value and x is greater than K then that element is distant.

Below is the implementation of the above approach:  

C++




// C++ program to count elements in first Array
// with absolute difference greater than K
// with an element in second Array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the such elements
void countDist(int arr1[], int n, int arr2[],
               int m, int k)
{
    // Store count of required elements in arr1
    int count = 0;
 
    // Initialise the smallest and the largest
    // value from the second array arr2[]
    int smallest = arr2[0];
    int largest = arr2[0];
 
    // Find the smallest and
    // the largest element in arr2
    for (int i = 0; i < m; i++) {
        smallest = max(smallest, arr2[i]);
        largest = min(largest, arr1[i]);
    }
    for (int i = 0; i < n; i++) {
 
        // Check if absolute difference of smallest
        // and arr1[i] or largest and arr1[i] is > K
        // then arr[i] is a required element
        if (abs(arr1[i] - smallest) > k
            || abs(arr1[i] - largest) > k)
            count++;
    }
 
    // Print the final result
    cout << count;
}
 
// Driver code
int main()
{
    int arr1[] = { 3, 1, 4 };
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int arr2[] = { 5, 1, 2 };
    int m = sizeof(arr2) / sizeof(arr2[0]);
    int k = 2;
 
    countDist(arr1, n, arr2, m, k);
 
    return 0;
}
 
 

Java




// Java program to count elements in first Array
// with absolute difference greater than K
// with an element in second Array
class GFG{
 
// Function to count the such elements
static void countDist(int arr1[], int n,
                      int arr2[], int m,
                      int k)
{
    // Store count of required elements in arr1
    int count = 0;
 
    // Initialise the smallest and the largest
    // value from the second array arr2[]
    int smallest = arr2[0];
    int largest = arr2[0];
 
    // Find the smallest and
    // the largest element in arr2
    for(int i = 0; i < m; i++)
    {
       smallest = Math.max(smallest, arr2[i]);
       largest = Math.min(largest, arr1[i]);
    }
    for(int i = 0; i < n; i++)
    {
 
       // Check if absolute difference
       // of smallest and arr1[i] or
       // largest and arr1[i] is > K
       // then arr[i] is a required element
       if (Math.abs(arr1[i] - smallest) > k ||
           Math.abs(arr1[i] - largest) > k)
           count++;
    }
 
    // Print the final result
    System.out.print(count);
}
 
// Driver code
public static void main(String[] args)
{
    int arr1[] = { 3, 1, 4 };
    int n = arr1.length;
    int arr2[] = { 5, 1, 2 };
    int m = arr2.length;
    int k = 2;
 
    countDist(arr1, n, arr2, m, k);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program to count elements in the first Array
# with an absolute difference greater than K
# with an element in the second Array
 
# Function to count the such elements
def countDist(arr1, n, arr2, m, k):
     
    # Store count of required elements in arr1
    count = 0
 
    # Initialise the smallest and the largest
    # value from the second array arr2[]
    smallest = arr2[0]
    largest = arr2[0]
 
    # Find the smallest and
    # the largest element in arr2
    for i in range(m):
        smallest = max(smallest, arr2[i])
        largest = min(largest, arr1[i])
 
    for i in range(n):
 
        # Check if absolute difference of smallest
        # and arr1[i] or largest and arr1[i] is > K
        # then arr[i] is a required element
        if (abs(arr1[i] - smallest) > k
            or abs(arr1[i] - largest) > k):
            count += 1
 
    # Print final result
    print(count)
 
 
# Driver code
if __name__ == '__main__':
     
    arr1= [ 3, 1, 4 ]
    n = len(arr1)
    arr2= [ 5, 1, 2 ]
    m = len(arr2)
    k = 2
 
    countDist(arr1, n, arr2, m, k)
     
# This code is contributed by mohit kumar 29
 
 

C#




// C# program to count elements in first array
// with absolute difference greater than K
// with an element in second Array
using System;
 
class GFG{
 
// Function to count the such elements
static void countDist(int []arr1, int n,
                      int []arr2, int m,
                      int k)
{
    // Store count of required elements in arr1
    int count = 0;
 
    // Initialise the smallest and the largest
    // value from the second array arr2[]
    int smallest = arr2[0];
    int largest = arr2[0];
 
    // Find the smallest and
    // the largest element in arr2
    for(int i = 0; i < m; i++)
    {
       smallest = Math.Max(smallest, arr2[i]);
       largest = Math.Min(largest, arr1[i]);
    }
    for(int i = 0; i < n; i++)
    {
        
       // Check if absolute difference
       // of smallest and arr1[i] or
       // largest and arr1[i] is > K
       // then arr[i] is a required element
       if (Math.Abs(arr1[i] - smallest) > k ||
           Math.Abs(arr1[i] - largest) > k)
           count++;
    }
 
    // Print the readonly result
    Console.Write(count);
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr1 = { 3, 1, 4 };
    int n = arr1.Length;
    int []arr2 = { 5, 1, 2 };
    int m = arr2.Length;
    int k = 2;
 
    countDist(arr1, n, arr2, m, k);
}
}
 
// This code is contributed by gauravrajput1
 
 

Javascript




<script>
 
// Javascript program to count elements in
// first Array with absolute difference
// greater than K with an element in
// second Array   
 
// Function to count the such elements
function countDist(arr1, n, arr2, m, k)
{
     
    // Store count of required elements in arr1
    var count = 0;
 
    // Initialise the smallest and the largest
    // value from the second array arr2
    var smallest = arr2[0];
    var largest = arr2[0];
 
    // Find the smallest and
    // the largest element in arr2
    for(i = 0; i < m; i++)
    {
        smallest = Math.max(smallest, arr2[i]);
        largest = Math.min(largest, arr1[i]);
    }
    for(i = 0; i < n; i++)
    {
         
        // Check if absolute difference
        // of smallest and arr1[i] or
        // largest and arr1[i] is > K
        // then arr[i] is a required element
        if (Math.abs(arr1[i] - smallest) > k ||
            Math.abs(arr1[i] - largest) > k)
            count++;
    }
 
    // Print the final result
    document.write(count);
}
 
// Driver code
var arr1 = [ 3, 1, 4 ];
var n = arr1.length;
var arr2 = [ 5, 1, 2 ];
var m = arr2.length;
var k = 2;
 
countDist(arr1, n, arr2, m, k);
 
// This code is contributed by umadevi9616
 
</script>
 
 
Output: 
2

 

Time Complexity: O(N + M), where N and M are the sizes of the given arrays.
Auxiliary Space: O(1).
 



Next Article
Count of elements whose absolute difference with the sum of all the other elements is greater than k

A

aqibmahboob1999
Improve
Article Tags :
  • Algorithms
  • Arrays
  • Competitive Programming
  • DSA
  • Greedy
Practice Tags :
  • Algorithms
  • Arrays
  • Greedy

Similar Reads

  • Count of elements in first Array greater than second Array with each element considered only once
    Given two sorted array of size N. The task is to find the maximum number of elements in the first array which are strictly greater than the elements of the second array such that an element can be considered only once. Examples: Input: arr1[] = { 20, 30, 50 }, arr2[] = { 25, 40, 60 } Output: 2 Expla
    5 min read
  • Count of elements whose absolute difference with the sum of all the other elements is greater than k
    Given an array arr[] of N integers and an integer K, the task is to find the number of anomalies in the array. An anomaly is a number for which the absolute difference between it and all the other numbers in the array is greater than K. Find the number of anomalies. Examples: Input: arr[] = {1, 3, 5
    5 min read
  • For each element in 1st array count elements less than or equal to it in 2nd array | Set 2
    Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[]. Examples: Input : arr1[] = [1, 2, 3, 4, 7, 9] arr2[] = [0, 1, 2, 1, 1, 4] Output : [4, 5, 5, 6, 6, 6] Explanation: There are 4 elements less t
    13 min read
  • Count of Array elements greater than all elements on its left and at least K elements on its right
    Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right. Examples: Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3 Output: 2 Explanation: The o
    15+ min read
  • Count of elements such that its sum/difference with X also exists in the Array
    Given an array arr[] and an integer X, the task is to count the elements of the array such that their exist a element [Tex]arr[i] - X [/Tex]or [Tex]arr[i] + X [/Tex]in the array.Examples: Input: arr[] = {3, 4, 2, 5}, X = 2 Output: 4 Explanation: In the above-given example, there are 4 such numbers -
    9 min read
  • Count of Array elements greater than all elements on its left and next K elements on its right
    Given an array arr[], the task is to print the number of elements which are greater than all the elements on its left as well as greater than the next K elements on its right. Examples: Input: arr[] = { 4, 2, 3, 6, 4, 3, 2}, K = 2 Output: 2 Explanation: arr[0](= 4): arr[0] is the 1st element in the
    14 min read
  • Count of pairs from arrays A and B such that element in A is greater than element in B at that index
    Given two arrays A[] and B[] of size N, the task is to count the maximum number of pairs, where each pair contains one from each array, such that A[i] > B[i]. Also the array A can be rearranged any number of times. Examples: Input: A[] = {20, 30, 50}, B[]= {60, 40, 25} Output: 2 Explanation: Init
    7 min read
  • Count pairs in an array such that the absolute difference between them is ≥ K
    Given an array arr[] and an integer K, the task is to find the count of pairs (arr[i], arr[j]) from the array such that |arr[i] - arr[j]| ? K. Note that (arr[i], arr[j]) and arr[j], arr[i] will be counted only once.Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 3 All valid pairs are (1, 3), (1
    6 min read
  • Count maximum elements of an array whose absolute difference does not exceed K
    Given an array A and positive integer K. The task is to find maximum number of elements for which the absolute difference of any of the pair does not exceed K.Examples: Input: A[] = {1, 26, 17, 12, 15, 2}, K = 5 Output: 3 There are maximum 3 values so that the absolute difference of each pair does n
    6 min read
  • Count elements that are divisible by at-least one element in another array
    Given two arrays arr1[] and arr2[]. The task is to find the count of such elements in the first array whose at-least one factor is present in the second array.Examples: Input : arr1[] = {10, 2, 13, 4, 15} ; arr2[] = {2, 4, 5, 6} Output : 4 There is no factor of 13 which is present in the second arra
    8 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