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:
Sort an array according to absolute difference with given value using Functors
Next article icon

Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum

Last Updated : 19 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of some positive integers and missing occurrence of a specific integer represented by -1, the task is to find that missing number such that maximum absolute difference between adjacent elements is minimum.
Examples: 
 

Input: arr[] = {-1, 10, -1, 12, -1} 
Output: 11 
Explanation: 
Differences of Adjacent elements – 
=> a[0] – a[1] = 11 – 10 = 1 
=> a[2] – a[1] = 11 – 10 = 1 
=> a[3] – a[2] = 12 – 11 = 1 
=> a[3] – a[4] = 12 – 11 = 1 
Maximum absolute difference of adjacent elements – 2 
Input: arr[] = {1,-1, 7, 5, 2, -1, 5} 
Output: 4 
Explanation: 
Differences of Adjacent elements – 
=> a[1] – a[0] = 4 – 1 = 3 
=> a[2] – a[1] = 7 – 4 = 3 
=> a[2] – a[3] = 7 – 5 = 2 
=> a[3] – a[4] = 5 – 2 = 3 
=> a[5] – a[4] = 4 – 2 = 2 
=> a[6] – a[5] = 5 – 4 = 1 
Maximum absolute difference of adjacent elements – 3

Approach: The idea is to find the maximum and minimum adjacent element to the missing number and the missing number can be the average of these two values such that maximum absolute difference is minimum.
 

=> max = Maximum adjacent element => min = Minimum adjacent element  Missing number = (max + min)                 -------------                       2

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the missing
// number such that maximum absolute
// difference between adjacent element
// is minimum
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find the missing
// number such that maximum
// absolute difference is minimum
int missingnumber(int n, int arr[])
{
    int mn = INT_MAX, mx = INT_MIN;
    // Loop to find the maximum and
    // minimum adjacent element to
    // missing number
    for (int i = 0; i < n; i++) {
 
        if (i > 0 && arr[i] == -1 &&
                 arr[i - 1] != -1) {
            mn = min(mn, arr[i - 1]);
            mx = max(mx, arr[i - 1]);
        }
 
        if (i < (n - 1) && arr[i] == -1 &&
                       arr[i + 1] != -1) {
            mn = min(mn, arr[i + 1]);
            mx = max(mx, arr[i + 1]);
        }
    }
     
    long long int res = (mx + mn) / 2;
    return res;
}
 
// Driver Code
int main()
{
    int n = 5;
    int arr[5] = { -1, 10, -1,
                       12, -1 };
    int ans = 0;
     
    // Function Call
    int res = missingnumber(n, arr);
    cout << res;
 
    return 0;
}
 
 

Java




// Java implementation of the missing
// number such that maximum absolute
// difference between adjacent element
// is minimum
import java.util.*;
class GFG{
 
// Function to find the missing
// number such that maximum
// absolute difference is minimum
static int missingnumber(int n, int arr[])
{
    int mn = Integer.MAX_VALUE,
        mx = Integer.MIN_VALUE;
     
    // Loop to find the maximum and
    // minimum adjacent element to
    // missing number
    for (int i = 0; i < n; i++)
    {
        if (i > 0 && arr[i] == -1 &&
                     arr[i - 1] != -1)
        {
            mn = Math.min(mn, arr[i - 1]);
            mx = Math.max(mx, arr[i - 1]);
        }
 
        if (i < (n - 1) && arr[i] == -1 &&
                           arr[i + 1] != -1)
        {
            mn = Math.min(mn, arr[i + 1]);
            mx = Math.max(mx, arr[i + 1]);
        }
    }
     
    int res = (mx + mn) / 2;
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 5;
    int arr[] = { -1, 10, -1,
                    12, -1 };
 
    // Function Call
    int res = missingnumber(n, arr);
    System.out.print(res);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 implementation of the missing
# number such that maximum absolute
# difference between adjacent element
# is minimum
import sys
 
# Function to find the missing
# number such that maximum
# absolute difference is minimum
def missingnumber(n, arr) -> int:
     
    mn = sys.maxsize;
    mx = -sys.maxsize - 1;
 
    # Loop to find the maximum and
    # minimum adjacent element to
    # missing number
    for i in range(n):
        if (i > 0 and arr[i] == -1 and
                      arr[i - 1] != -1):
            mn = min(mn, arr[i - 1]);
            mx = max(mx, arr[i - 1]);
 
        if (i < (n - 1) and arr[i] == -1 and
                            arr[i + 1] != -1):
            mn = min(mn, arr[i + 1]);
            mx = max(mx, arr[i + 1]);
 
    res = (mx + mn) / 2;
     
    return res;
 
# Driver Code
if __name__ == '__main__':
     
    n = 5;
    arr = [ -1, 10, -1, 12, -1 ];
 
    # Function call
    res = missingnumber(n, arr);
    print(res);
 
# This code is contributed by amal kumar choubey
 
 

C#




// C# implementation of the missing
// number such that maximum absolute
// difference between adjacent element
// is minimum
using System;
class GFG{
 
// Function to find the missing
// number such that maximum
// absolute difference is minimum
static int missingnumber(int n, int []arr)
{
    int mn = Int32.MaxValue,
        mx = Int32.MinValue;
     
    // Loop to find the maximum and
    // minimum adjacent element to
    // missing number
    for (int i = 0; i < n; i++)
    {
        if (i > 0 && arr[i] == -1 &&
                     arr[i - 1] != -1)
        {
            mn = Math.Min(mn, arr[i - 1]);
            mx = Math.Max(mx, arr[i - 1]);
        }
 
        if (i < (n - 1) && arr[i] == -1 &&
                           arr[i + 1] != -1)
        {
            mn = Math.Min(mn, arr[i + 1]);
            mx = Math.Max(mx, arr[i + 1]);
        }
    }
     
    int res = (mx + mn) / 2;
    return res;
}
 
// Driver Code
public static void Main()
{
    int n = 5;
    int []arr = new int[]{ -1, 10, -1, 12, -1 };
 
    // Function Call
    int res = missingnumber(n, arr);
    Console.WriteLine(res);
}
}
 
// This code is contributed by Nidhi_biet
 
 

Javascript




<script>
 
// JavaScript implementation of the missing
// number such that maximum absolute
// difference between adjacent element
// is minimum
 
// Function to find the missing
// number such that maximum
// absolute difference is minimum
function missingnumber(n, arr)
{
    let mn = 10000;
    let mx = -10000;
 
    // Loop to find the maximum and
    // minimum adjacent element to
    // missing number
    for (let i = 0; i < n; i++)
    {
        if (i > 0 && arr[i] == -1 && arr[i - 1] != -1)
        {
            mn = Math.min(mn, arr[i - 1]);
            mx = Math.max(mx, arr[i - 1]);
        }
 
        if (i < (n - 1) && arr[i] == -1 &&
                        arr[i + 1] != -1)
        {
            mn = Math.min(mn, arr[i + 1]);
            mx = Math.max(mx, arr[i + 1]);
        }
    }
 
    let res = (mx + mn) / 2;
    return res;
}
 
// Driver Code
 
let n = 5;
let arr = [-1, 10, -1, 12, -1];
 
// Function Call
let res = missingnumber(n, arr);
 
document.write(res);
 
 
</script>
 
 
Output: 
11

 

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



Next Article
Sort an array according to absolute difference with given value using Functors

A

Adityasharma15
Improve
Article Tags :
  • Arrays
  • C++
  • C++ Programs
  • Competitive Programming
  • CS - Placements
  • DI - Placements
  • DSA
  • English - Placements
  • Greedy
  • Placements
  • QA - Placements
  • Reasoning - Placements
Practice Tags :
  • CPP
  • Arrays
  • Greedy

Similar Reads

  • Sort array such that absolute difference of adjacent elements is in increasing order
    Given an unsorted array of length N. The task is to sort the array, such that abs(a[i]-a[i+1]) < = abs(a[i+1]-a[i+2]) for all 0 < = i< N that is abs(a[0]-a[1]) < = abs(a[1]-a[2]) < = abs(a[2]-a[3]) and so on.Examples: Input: arr[] = {7, 4, 9, 9, -1, 9}Output: {9, 7, 9, 4, 9, -1}Explan
    7 min read
  • Maximum subsequence sum with adjacent elements having atleast K difference in index
    Given an array arr[] consisting of integers of length N and an integer K (1 ? k ? N), the task is to find the maximum subsequence sum in the array such that adjacent elements in that subsequence have at least a difference of K in their indices in the original array. Examples: Input: arr[] = {1, 2, -
    8 min read
  • Count pairs from an array with absolute difference not less than the minimum element in the pair
    Given an array arr[] consisting of N positive integers, the task is to find the number of pairs (arr[i], arr[j]) such that absolute difference between the two elements is at least equal to the minimum element in the pair. Examples: Input: arr[] = {1, 2, 2, 3}Output: 3Explanation:Following are the pa
    14 min read
  • Nth positive number whose absolute difference of adjacent digits is at most 1
    Given a number N, the task is to find the Nth number which has an absolute difference of 1 between every pair of its adjacent digits.Examples: Input : N = 5 Output : 5 Explanation: The first 5 such numbers are 1,2,3,4 and 5.Input : N = 15 Output : 23 Explanation: The first 15 such numbers are 1,2,3,
    7 min read
  • Sort an array according to absolute difference with given value using Functors
    Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., the element having a minimum difference comes first and so on. Note: If two or more elements are at equal distance arrange them in same sequence as in the given array. Exa
    6 min read
  • Maximum value of X such that difference between any array element and X does not exceed K
    Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the maximum possible integer X, such that the absolute difference between any array element and X is at most K. If no such value of X exists, then print "-1". Examples: Input: arr[] = {6, 4, 8, 5}, K
    11 min read
  • Partition a set into two subsets such that difference between max of one and min of other is minimized
    Given an array arr[] of N integers, the task is to split the array into two subsets such that the absolute difference between the maximum of first subset and minimum of second subset is minimum.Examples: Input: arr[] = {3, 1, 2, 6, 4} Output: 1 Explanation: Splitting the given array in two subsets,
    4 min read
  • Print distinct absolute differences of all possible pairs from a given array
    Given an array, arr[] of size N, the task is to find the distinct absolute differences of all possible pairs of the given array. Examples: Input: arr[] = { 1, 3, 6 } Output: 2 3 5 Explanation: abs(arr[0] - arr[1]) = 2 abs(arr[1] - arr[2]) = 3 abs(arr[0] - arr[2]) = 5 Input: arr[] = { 5, 6, 7, 8, 14,
    9 min read
  • Minimum elements inserted in a sorted array to form an Arithmetic progression
    Given a sorted array arr[], the task is to find minimum elements needed to be inserted in the array such that array forms an Arithmetic Progression.Examples: Input: arr[] = {1, 6, 8, 10, 14, 16} Output: 10 Explanation: Minimum elements required to form A.P. is 10. Transformed array after insertion o
    8 min read
  • Maximize distance between two elements of Array by at most X swaps
    Given an array arr[] of unique elements and three integers X, A, and B. The task is to print the maximum possible distance between elements A and B in atmost X swaps with the adjacent elements. Examples: Input: arr[] = {5, 1, 3, 2}, X = 1, A = 2, B = 3 Output: 2 Explanation: 3 is swapped with it's a
    11 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