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:
Add elements of given arrays with given constraints
Next article icon

Forming smallest array with given constraints

Last Updated : 17 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given three integers x, y and z (can be negative). The task is to find the length of the smallest array that can be made such that absolute difference between adjacent elements is less than or equal to 1, the first element of the array is x, having one integer y and last element z.

Examples: 

Input : x = 5, y = 7, z = 11 
Output : 7 
The smallest starts with 5, having 7, ends 
with 11 and having absolute difference 1 
is { 5, 6, 7, 8, 9, 10, 11 }.

Input : x = 3, y = 1, z = 2 
Output : 4 
The array would become { 3, 2, 1, 2 }  

The idea is to consider the number line since the difference between adjacent elements is 1 so to move from X to Y all numbers between x and y have to be covered and to end the array with integer z, so move from element y to element z. 

So, the length of the smallest array that can be formed will be the number of points that will be covered from x to z i.e.  

1 + abs(x - y) + abs(y - z) (1 is added to count point x).

Implementation:

C++
// C++ program to find the length of  // smallest array begin with x, having y, // ends with z and having absolute difference  // between adjacent elements <= 1. #include <bits/stdc++.h> using namespace std;  // Return the size of smallest  // array with given constraint. int minimumLength(int x, int y, int z) {     return 1 + abs(x - y) + abs(y - z); }  // Drivers code int main() {     int x = 3, y = 1, z = 2;     cout << minimumLength(x, y, z);      return 0; } 
Java
// Java program to find the length  // of smallest array begin with x, // having y, ends with z and having // absolute difference between // adjacent elements <= 1. import java.io.*;  class GFG {          // Return the size of smallest      // array with given constraint.     static int minimumLength(int x,                       int y, int z)     {         return 1 + Math.abs(x - y)                  + Math.abs(y - z);     }          // Drivers code      public static void main(String[] args)     {         int x = 3, y = 1, z = 2;         System.out.println(                minimumLength(x, y, z));     } }  // This code is contributed by anuj_67. 
Python 3
# Python 3 program to find # the length of smallest  # array begin with x, having # y, ends with z and having # absolute difference between # adjacent elements <= 1.  # Return the size of smallest  # array with given constraint. def minimumLength(x, y, z):      return (1 + abs(x - y)                + abs(y - z))  # Drivers code x = 3 y = 1 z = 2 print(minimumLength(x, y, z))  # This code is contributed  # by Smitha 
C#
// C# program to find the length  // of smallest array begin with x, // having y, ends with z and having // absolute difference between // adjacent elements <= 1. using System; class GFG {          // Return the size of smallest      // array with given constraint.     static int minimumLength(int x,                              int y,                              int z)     {         return 1 + Math.Abs(x - y)                  + Math.Abs(y - z);     }          // Driver Code     public static void Main()     {         int x = 3, y = 1, z = 2;         Console.WriteLine(minimumLength(x, y, z));     } }  // This code is contributed by anuj_67. 
PHP
<?php // PHP program to find the length of  // smallest array begin with x, having y, // ends with z and having absolute difference  // between adjacent elements <= 1.  // Return the size of smallest  // array with given constraint. function minimumLength($x, $y,$z) {     return 1 + abs($x - $y) +                 abs($y - $z); }      // Driver Code     $x = 3;      $y = 1;      $z = 2;     echo minimumLength($x, $y, $z);  // This code is contributed by anuj_67. ?> 
JavaScript
<script>  // Javascript program to find the length of  // smallest array begin with x, having y, // ends with z and having absolute difference  // between adjacent elements <= 1.  // Return the size of smallest  // array with given constraint. function minimumLength(x, y, z) {     return 1 + Math.abs(x - y) + Math.abs(y - z); }  // Drivers code var x = 3, y = 1, z = 2; document.write( minimumLength(x, y, z));  // This code is contributed by noob2000. </script>  

Output
4

Complexity Analysis:

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

Next Article
Add elements of given arrays with given constraints
author
anuj0503
Improve
Article Tags :
  • Mathematical
  • DSA
  • Arrays
  • logical-thinking
Practice Tags :
  • Arrays
  • logical-thinking
  • Mathematical

Similar Reads

  • Counting Arrays with divisibility constraint
    Given two integers X and Y, the task is to find the number of different arrays that can be constructed of size largest possible size that follow the conditions below: Every element of the array should not be less than X and should not be greater than Y.Every element should occur at most once in the
    9 min read
  • Add elements of given arrays with given constraints
    Given two integer arrays, add their elements into third array by satisfying following constraints - Addition should be done starting from 0th index of both arrays. Split the sum if it is a not a single digit number and store the digits in adjacent locations in output array. Output array should accom
    15+ min read
  • Covering maximum array elements with given value
    Given total number of candies 'X', number of students 'N' and an array 'arr' which holds the value for the exact number of candies that must be given to a student to make the student happy where arr[i] is the exact amount of candies that make the student 'i' happy. The task is to distribute the cand
    7 min read
  • Counting pairs with condition in even Array halves
    Given an array arr[] of integers of size n where n is even, the task is to calculate the number of pairs (i, j) such that i lies in the first half of the array 0 ≤ i < n/2 and j lies in the second half of the array n/2 ≤ j < n and arr[i] ≥ 5*arr[j]. Note: 0-based indexing is used and n is even
    6 min read
  • Construct minimum length array with given conditions
    Given an array, A[] of N integers and 2 integers P and Q, the task is to construct an array of minimum possible length with given P and Q and absolute difference of consecutive elements equal to 1 such that: P is the sum of all the elements A[i] of the array such that A[i] > A[(i+1) % N] and A[i]
    6 min read
  • Find the Prefix-MEX Array for given Array
    Given an array A[] of N elements, the task is to create a Prefix-MEX array for this given array. Prefix-MEX array B[] of an array A[] is created such that MEX of A[0] till A[i] is B[i]. MEX of an array refers to the smallest missing non-negative integer of the array. Examples: Input: A[] = {1, 0, 2,
    13 min read
  • Find an array of size N that satisfies the given conditions
    Given three integers N, S, and K, the task is to create an array of N positive integers such that the bitwise OR of any two consecutive elements from the array is odd and there are exactly K subarrays with a sum equal to S where 1 ? K ? N / 2. Examples: Input: N = 4, K = 2, S = 6 Output: 6 7 6 7 Her
    8 min read
  • Maximum possible size of subset following the given constraints
    Given an array arr[] of size n, the task is to find the maximum possible size x of a subset such that there are exactly two subsets of the same size that should follow the below constraints: The first subset should consist of distinct elements (i.e., all elements in the first subset are unique) and
    10 min read
  • Count ways to fill Array with distinct elements with given limitation
    Given an array arr[] of size N and you need to fill another empty array of size N with positive integers. Each element in the given array denotes the maximum positive integer you can choose to fill the empty array. The task is to find the number of ways to fill the empty array such that all elements
    6 min read
  • Creating Array with Distinct Differences
    Given two positive integers, n and d (less than n), the task is to create an array result[] of n distinct positive integers that range from 1 to n, such that result = {a1, a2, a3, ..., an}, then the result = {|a1 - a2|, |a2 - a3|, |a3 - a4|, ..., |an-1 - an|} has exactly d distinct integers. If mult
    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