Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Searching in an array where adjacent differ by at most k
Next article icon

Searching in an array where adjacent differ by at most k

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

A step array is an array of integers where each element has a difference of at most k with its neighbor. Given a key x, we need to find the index value of x if multiple-element exist to return the first occurrence of the key.
Examples: 
 

Input : arr[] = {4, 5, 6, 7, 6}             k = 1             x = 6  Output : 2  The first index of 6 is 2.    Input : arr[] = {20, 40, 50, 70, 70, 60}              k = 20            x = 60  Output : 5  The index of 60 is 5


 

Recommended Practice
Searching in an array where adjacent differ by at most k
Try It!


This problem is mainly an extension of Search an element in an array where difference between adjacent elements is 1.
A Simple Approach is to traverse the given array one by one and compare every element with the given element 'x'. If matches, then return index.
The above solution can be Optimized using the fact that the difference between all adjacent elements is at most k. The idea is to start comparing from the leftmost element and find the difference between the current array element and x. Let this difference be 'diff'. From the given property of the array, we always know that x must be at least 'diff/k' away, so instead of searching one by one, we jump 'diff/k'. 
Below is the implementation of the above idea.
 

C++
// C++ program to search an element in an array  // where difference between adjacent elements is atmost k #include<bits/stdc++.h> using namespace std;  // x is the element to be searched in arr[0..n-1] // such that all elements differ by at-most k. int search(int arr[], int n, int x, int k) {     // Traverse the given array starting from     // leftmost element     int i = 0;     while (i < n)     {         // If x is found at index i         if (arr[i] == x)             return i;          // Jump the difference between current         // array element and x divided by k         // We use max here to make sure that i         // moves at-least one step ahead.         i = i + max(1, abs(arr[i]-x)/k);     }      cout << "number is not present!";     return -1; }  // Driver program to test above function int main() {     int arr[] = {2, 4, 5, 7, 7, 6};     int x = 6;     int k = 2;     int n = sizeof(arr)/sizeof(arr[0]);     cout << "Element " << x  << " is present at index "          << search(arr, n, x, k);     return 0; } 
Java
// Java program to search an element in  // an array where difference between adjacent elements is atmost k  import java.io.*;  class GFG {          // x is the element to be searched      // in arr[0..n-1] such that all      // elements differ by at-most k.     static int search(int arr[], int n,                              int x, int k)     {                  // Traverse the given array starting         // from leftmost element         int i = 0;                  while (i < n) {                          // If x is found at index i             if (arr[i] == x)                 return i;              // Jump the difference between              // current array element and x             // divided by k We use max here             // to make sure that i moves              // at-least one step ahead.             i = i + Math.max(1, Math.abs(arr[i]                                        - x) / k);         }          System.out.println("number is " +                                  "not present!");         return -1;     }      // Driver program to test above function     public static void main(String[] args)     {                  int arr[] = { 2, 4, 5, 7, 7, 6 };         int x = 6;         int k = 2;         int n = arr.length;                  System.out.println("Element " + x +                         " is present at index "                         + search(arr, n, x, k));     } }  // This code is contributed by vt_m 
Python3
# Python 3 program to search an element in an array  # where difference between adjacent elements is atmost k  # x is the element to be searched in arr[0..n-1] # such that all elements differ by at-most k. def search(arr, n, x, k):      # Traverse the given array starting from     # leftmost element     i = 0     while (i < n):              # If x is found at index i         if (arr[i] == x):             return i          # Jump the difference between current         # array element and x divided by k         # We use max here to make sure that i         # moves at-least one step ahead.         i = i + max(1, int(abs(arr[i] - x) / k))           print("number is not present!")     return -1   # Driver program to test above function arr = [2, 4, 5, 7, 7, 6] x = 6 k = 2 n = len(arr) print("Element", x, "is present at index",search(arr, n, x, k))  # This code is contributed # by Smitha Dinesh Semwal 
C#
// C# program to search an element in  // an array where difference between //adjacent elements is atmost k  class GFG {          // x is the element to be searched      // in arr[0..n-1] such that all      // elements differ by at-most k.     static int search(int []arr, int n,                            int x, int k)     {                  // Traverse the given array starting         // from leftmost element         int i = 0;                  while (i < n)          {                          // If x is found at index i             if (arr[i] == x)                 return i;              // Jump the difference between              // current array element and x             // divided by k We use max here             // to make sure that i moves              // at-least one step ahead.             i = i + Math.Max(1, Math.Abs(arr[i]                                      - x) / k);         }          Console.Write("number is " +                        "not present!");         return -1;     }      // Driver Code     public static void Main()     {                  int []arr = { 2, 4, 5, 7, 7, 6 };         int x = 6;         int k = 2;         int n = arr.Length;                  Console.Write("Element " + x +                        " is present at index " +                          search(arr, n, x, k));     } }  // This code is contributed by Nitin Mittal. 
PHP
<?php // PHP program to search an // element in an array   //where difference between    //adjacent elements is atmost k  // x is the element to be  // searched in arr[0..n-1] // such that all elements  // differ by at-most k. function search($arr, $n, $x, $k) {          // Traverse the given array     // starting from leftmost element     $i = 0;     while ($i < $n)     {         // If x is found at index i         if ($arr[$i] == $x)             return $i;          // Jump the difference between current         // array element and x divided by k         // We use max here to make sure that i         // moves at-least one step ahead.         $i = $i + max(1, abs($arr[$i] - $x) / $k);     }      echo "number is not present!";     return -1; }  // Driver Code {     $arr = array(2, 4, 5, 7, 7, 6);     $x = 6;     $k = 2;     $n = sizeof($arr)/sizeof($arr[0]);     echo "Element $x is present".                       "at index ",         search($arr, $n, $x, $k);     return 0; }  // This code is contributed by nitin mittal. ?> 
JavaScript
<script>   // Javascript program to search an element in an array  // where difference between adjacent elements is atmost k  // x is the element to be searched in arr[0..n-1] // such that all elements differ by at-most k. function search(arr, n, x, k) {     // Traverse the given array starting from     // leftmost element     var i = 0;     while (i < n)     {         // If x is found at index i         if (arr[i] == x)             return i;          // Jump the difference between current         // array element and x divided by k         // We use max here to make sure that i         // moves at-least one step ahead.         i = i + Math.max(1, Math.abs(arr[i]-x)/k);     }      document.write( "number is not present!");     return -1; }  // Driver program to test above function var arr = [2, 4, 5, 7, 7, 6]; var x = 6; var k = 2; var n = arr.length; document.write( "Element " + x  + " is present at index "      + search(arr, n, x, k));   </script> 

Output: 
Element 6 is present at index 5

 

Time Complexity: O(n)

Auxiliary Space: O(1)


Next Article
Searching in an array where adjacent differ by at most k

S

Shahnawaz_Ali
Improve
Article Tags :
  • Misc
  • Searching
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Misc
  • Searching

Similar Reads

    Count pairs in an array whose absolute difference is divisible by K | Using Map
    Given an array, arr[] of N elements and an integer K, the task is to find the number of pairs (i, j) such that the absolute value of (arr[i] - arr[j]) is a multiple of K. Examples: Input: N = 4, K = 2, arr[] = {1, 2, 3, 4}Output: 2Explanation: Total 2 pairs exists in the array with absolute differen
    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
    Min and max length subarray having adjacent element difference atmost K
    Given an array arr[] and an integer K, the task is to find the maximum and minimum length subarray such that the difference between adjacent elements is at most K.Examples: Input: arr[] = {2, 4, 6}, K = 2 Output: 3, 3 Explanation: Minimum and Maximum length subarray such that difference between adja
    9 min read
    Count all disjoint pairs having absolute difference at least K from a given array
    Given an array arr[] consisting of N integers, the task is to count all disjoint pairs having absolute difference of at least K. Note: The pair (arr[i], arr[j]) and (arr[j], arr[i]) are considered as the same pair. Examples: Input: arr[] = {1, 3, 3, 5}, K = 2Output: 2Explanation:The following two pa
    13 min read
    Check if Array can be reordered such that adjacent difference of a pair is K times of the other
    Given an array arr[] of size N and a positive integer K, the task is to check if the array can be reordered such that each pair of consecutive differences differ by a factor of K i.e., arr[i] − arr[i − 1] = K*(arr[i + 1] − arr[i]), orarr[i + 1] − arr[i] = K*(arr[i] − arr[i − 1]) Note: Different cond
    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