Open In App

Find position of an element in a sorted array of infinite numbers

Last Updated : 15 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sorted array arr[] of infinite numbers. The task is to search for an element k in the array.

Examples:

Input: arr[] = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170], k = 10
Output: 4
Explanation: 10 is at index 4 in array.

Input: arr[] = [2, 5, 7, 9], k = 3
Output: -1
Explanation: 3 is not present in array.

Finding bound and then Binary Search – O(log(k)) Time and O(1) Space

Since the array is sorted, the first thing that comes to apply is binary search, but the problem here is that we don’t know the size of the array. If the array is infinite, we don’t have proper bounds to apply binary search.

So in order to find the position of the key, first we find bounds and then apply a binary search algorithm. Let the low be pointing to the 1st element and the high pointing to the 2nd element of the array, Now compare the key with the high index element.

  • if it is greater than the high index element then copy the high index in the low index and double the high index. 
  • if it is smaller, then apply binary search on high and low indices found.

low and high will follow following kind of pattern:

  • l = 0, h = 1
  • l = 1, h = 2
  • l = 2, h = 4
  • l = 4, h = 8

So we can observe that over range is doubling every turn so it will take at most log(k) time.

Note: While doubling the value of h, there is possibility that h crosses the size of array, but we are considering the array to be infinite, and it is not possible to take an infinite array as input. Thus we might get out of bound error (which is not possible for infinite array).

C++
// C++ program to demonstrate working of an algorithm that finds
// an element in an array of infinite size
#include <bits/stdc++.h>
using namespace std;

// Binary search function to find the element 
// in a given range
int binarySearch(vector<int> &arr, int l, int r, int x) {

    if (r >= l) {
        int mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);
        return binarySearch(arr, mid + 1, r, x);
    }
    return -1;
}

// Function to find the position of the key in the 
// infinite-size array (represented as a vector)
int findPos(vector<int> &arr, int key) {

    int l = 0, h = 1;
    int val = arr[0];

    // Find high to do binary search
    while (val < key) {

        // Store previous high
        l = h;

        // Double high index
        h = 2 * h;
        
        // Update new value
        val = arr[h];
    }
    

    // At this point, we have updated low and high
  	// indices, thus use binary search between them
    return binarySearch(arr, l, h, key);
}

int main() {

    vector<int> arr = {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170};
    int k = 170;
    int ans = findPos(arr, k);
    cout << ans;
    return 0;
}
Java
// Java program to demonstrate working of an algorithm that finds
// an element in an array of infinite size
import java.util.*;

class GfG {
  
    static int binarySearch(int[] arr, int l, int r, int x) {
      
        if (r >= l) {
            int mid = l + (r - l) / 2;
            if (arr[mid] == x)
                return mid;
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
            return binarySearch(arr, mid + 1, r, x);
        }
        return -1;
    }

    
  // function takes an infinite size array and a key to be
  // searched and returns its position if found else -1.
  // we don't know size of arr[] and we can assume size to be
  // infinite in this function.
  // note that this function assumes arr[] to be of infinite size
  // therefore, there is no index out of bound checking
    static int findPos(int[] arr, int key) {

        int l = 0, h = 1;
        int val = arr[0];

        // Find h to do binary search
        while (val < key) {

            // store previous high
            l = h;

            // double high index
            h = 2 * h;

            // update new val
            val = arr[h];
        }

        // at this point we have updated low and
        // high indices, Thus use binary search 
        // between them
        return binarySearch(arr, l, h, key);
    }

    public static void main(String[] args) {

        int[] arr = {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170};
        int k = 10;
        int ans = findPos(arr, k);
        System.out.println(ans);
    }
}
Python
# Python program to demonstrate working of an algorithm that finds
# an element in an array of infinite size

def binarySearch(arr, l, r, x):
    if r >= l:
        mid = l + (r - l) // 2
        if arr[mid] == x:
            return mid
        if arr[mid] > x:
            return binarySearch(arr, l, mid - 1, x)
        return binarySearch(arr, mid + 1, r, x)
    return -1

# function takes an infinite size array and a key to be
# searched and returns its position if found else -1.
# we don't know size of arr[] and we can assume size to be
# infinite in this function.
# note that this function assumes arr[] to be of infinite size
# therefore, there is no index out of bound checking
def findPos(arr, key):
  
    l = 0
    h = 1
    val = arr[0]

    # Find h to do binary search
    while val < key:

        # store previous high
        l = h

        # double high index
        h = 2 * h

        # update new val
        val = arr[h]

    # at this point we have updated low and
    # high indices, Thus use binary search 
    # between them
    return binarySearch(arr, l, h, key)

if __name__ == "__main__":
    arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]
    k = 10
    ans = findPos(arr, k)
    print(ans)
C#
// C# program to demonstrate working of an algorithm that finds
// an element in an array of infinite size
using System;

class GfG {
  
    static int binarySearch(int[] arr, int l, int r, int x) {
      
        if (r >= l) {
            int mid = l + (r - l) / 2;
            if (arr[mid] == x)
                return mid;
            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);
            return binarySearch(arr, mid + 1, r, x);
        }
        return -1;
    }

 
  // function takes an infinite size array and a key to be
  // searched and returns its position if found else -1.
  // we don't know size of arr[] and we can assume size to be
  // infinite in this function.
  // note that this function assumes arr[] to be of infinite size
  // therefore, there is no index out of bound checking
    static int findPos(int[] arr, int key) {
      
        int l = 0, h = 1;
        int val = arr[0];

        // Find h to do binary search
        while (val < key) {

            // store previous high
            l = h;

            // double high index
            h = 2 * h;

            // update new val
            val = arr[h];
        }

        // at this point we have updated low and
        // high indices, Thus use binary search 
        // between them
        return binarySearch(arr, l, h, key);
    }

    static void Main() {
      
        int[] arr = {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170};
        int k = 10;
        int ans = findPos(arr, k);
        Console.WriteLine(ans);
    }
}
JavaScript
// JavaScript program to demonstrate working of an algorithm that finds
// an element in an array of infinite size

function binarySearch(arr, l, r, x) {
    if (r >= l) {
        let mid = l + Math.floor((r - l) / 2);
        if (arr[mid] === x)
            return mid;
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);
        return binarySearch(arr, mid + 1, r, x);
    }
    return -1;
}

// function takes an infinite size array and a key to be
// searched and returns its position if found else -1.
// we don't know size of arr[] and we can assume size to be
// infinite in this function.
// note that this function assumes arr[] to be of infinite size
// therefore, there is no index out of bound checking
function findPos(arr, key) {

    let l = 0, h = 1;
    let val = arr[0];

    // Find h to do binary search
    while (val < key) {

        // store previous high
        l = h;

        // double high index
        h = 2 * h;

        // update new val
        val = arr[h];
    }

    // at this point we have updated low and
    // high indices, Thus use binary search 
    // between them
    return binarySearch(arr, l, h, key);
}

// Driver program
let arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170];
let k = 10;
let ans = findPos(arr, k);
console.log(ans);

Output
4

Alternate Approach – O(log(k)) Time and O(1) Space

Approach is fundamentally similar to previous one. Difference is only in the way how we find bound:

  • Since array is sorted we apply binary search but the length of array is infinite so that we take start = 0 and end = 1 .
  • After that check value of target is greater than the value at end index, if it is true then change newStart = end + 1  and newEnd = end + (end – start +1)*2 and apply binary search .
  • Otherwise , apply binary search in the old index values.

low and high will follow following kind of pattern:

  • l = 0, h = 1
  • l = 2, h = 5
  • l = 6, h = 13
  • l = 14, h = 29

So we can observe that over range is doubling every turn so it will take at most log(k) time.

Note: We can see that this series grows faster than the previous approach. So in some cases this might be more optimal. Also, there is possibility that end crosses the size of array, but we are considering the array to be infinite, and it is not possible to take an infinite array as input. Thus we might get out of bound error (which is not possible for infinite array).

C++
// C++ program to demonstrate working of an algorithm that finds
// an element in an array of infinite size
#include <bits/stdc++.h>
using namespace std;

int binarySearch(vector<int>& arr, int target, int start, int end) {
  
    // Perform binary search within the range [start, end]
    while (start <= end) {
      
        // Calculate the mid index
        int mid = start + (end - start) / 2;

        // If target is smaller, search the left half
        if (target < arr[mid]) {
            end = mid - 1;
        }
      
        // If target is larger, search the right half
        else if (target > arr[mid]) {
            start = mid + 1;
        }
      
        // If target is found, return the index
        else {
            return mid;
        }
    }
  
    // If the target is not found, return -1
    return -1;
}

int findPos(vector<int>& arr, int target) {
  
    // Initialize start and end for the search range
    int start = 0;
    int end = 1;

    // Keep doubling the search range until the target
  	// is within the range
    while (target > arr[end]) {
      
        // Temporarily store the current end
      	// as new start
        int temp = end + 1;

        // Double the box size and update the end index
        end = end + (end - start + 1) * 2;

        // Update start to the old end + 1
        start = temp;
    }

    // Perform binary search within the found range
    return binarySearch(arr, target, start, end);
}


int main() {
    vector<int> arr = {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170};

    int target = 10;
    int ans = findPos(arr, target);
    cout << ans << endl;

    return 0;
}
Java
// Java program to demonstrate working of an algorithm that
// finds an element in an array of infinite size

class GfG {
  
    static int binarySearch(int[] arr, int target,
                            int start, int end) {
      
        // Perform binary search within the range [start,
        // end]
        while (start <= end) {
          
            // Calculate the mid index
            int mid = start + (end - start) / 2;

            // If target is smaller, search the left half
            if (target < arr[mid]) {
                end = mid - 1;
            }
          
            // If target is larger, search the right half
            else if (target > arr[mid]) {
                start = mid + 1;
            }
          
            // If target is found, return the index
            else {
                return mid;
            }
        }
      
        // If the target is not found, return -1
        return -1;
    }

    // An algorithm that finds an element in an array of
    // infinite size
    static int findPos(int[] arr, int target) {
      
        // Initialize start and end for the search range
        int start = 0;
        int end = 1;

        while (target > arr[end]) {

            // Temporarily store the current end as new
            // start
            int temp = end + 1;

            // Double the box size and update the end index
            end = end + (end - start + 1) * 2;

            // Update start to the old end + 1
            start = temp;
        }

        // Perform binary search within the found range
        return binarySearch(arr, target, start, end);
    }

    public static void main(String[] args) {
      
        int[] arr = { 3, 5, 7, 9, 10, 90,
                      100, 130, 140, 160, 170 };

        int target = 10;
        int ans = findPos(arr, target);
        System.out.println(ans);
    }
}
Python
# Python program to demonstrate working of an algorithm that finds
# an element in an array of infinite size

def binarySearch(arr, target, start, end):
  
    # Perform binary search within the range [start, end]
    while start <= end:
      
        # Calculate the mid index
        mid = start + (end - start) // 2

        # If target is smaller, search the left half
        if target < arr[mid]:
            end = mid - 1
            
        # If target is larger, search the right half
        elif target > arr[mid]:
            start = mid + 1
            
        # If target is found, return the index
        else:
            return mid
          
    # If the target is not found, return -1
    return -1

# An algorithm that finds an element in
# an array of infinite size
def findPos(arr, target):
  
    # Initialize start and end for the search range
    start = 0
    end = 1

    while target > arr[end]:

        # Temporarily store the current end as new start
        temp = end + 1

        # Double the box size and update the end index
        end = end + (end - start + 1) * 2

        # Update start to the old end + 1
        start = temp

    # Perform binary search within the found range
    return binarySearch(arr, target, start, end)

if __name__ == "__main__":
  
    arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]
    target = 10
    ans = findPos(arr, target)
    print(ans)
C#
// C# program to demonstrate working of an algorithm that
// finds an element in an array of infinite size
using System;

class GfG {

    static int binarySearch(int[] arr, int target,
                            int start, int end) {
      
        // Perform binary search within the range [start,
        // end]
        while (start <= end) {
          
            // Calculate the mid index
            int mid = start + (end - start) / 2;

            // If target is smaller, search the left half
            if (target < arr[mid]) {
                end = mid - 1;
            }
          
            // If target is larger, search the right half
            else if (target > arr[mid]) {
                start = mid + 1;
            }
          
            // If target is found, return the index
            else {
                return mid;
            }
        }
      
        // If the target is not found, return -1
        return -1;
    }

    // An algorithm that finds an element in an array of
    // infinite size
    static int findPos(int[] arr, int target) {
      
        // Initialize start and end for the search range
        int start = 0;
        int end = 1;

        while (target > arr[end]) {

            // Temporarily store the current end as new
            // start
            int temp = end + 1;

            // Double the box size and update the end index
            end = end + (end - start + 1) * 2;

            // Update start to the old end + 1
            start = temp;
        }

        // Perform binary search within the found range
        return binarySearch(arr, target, start, end);
    }

    static void Main(string[] args) {
      
        int[] arr = { 3,   5,   7,   9,   10, 90,
                      100, 130, 140, 160, 170 };

        int target = 10;
        int ans = findPos(arr, target);
        Console.WriteLine(ans);
    }
}
JavaScript
// JavaScript program to demonstrate working of an algorithm
// that finds an element in an array of infinite size

function binarySearch(arr, target, start, end) {

    // Perform binary search within the range [start, end]
    while (start <= end) {
    
        // Calculate the mid index
        let mid = start + Math.floor((end - start) / 2);

        // If target is smaller, search the left half
        if (target < arr[mid]) {
            end = mid - 1;
        }
        
        // If target is larger, search the right half
        else if (target > arr[mid]) {
            start = mid + 1;
        }
        
        // If target is found, return the index
        else {
            return mid;
        }
    }
    
    // If the target is not found, return -1
    return -1;
}

// An algorithm that finds an element in an array of
// infinite size
function findPos(arr, target) {

    // Initialize start and end for the search range
    let start = 0;
    let end = 1;

    while (target > arr[end]) {

        // Temporarily store the current end as new start
        let temp = end + 1;

        // Double the box size and update the end index
        end = end + (end - start + 1) * 2;

        // Update start to the old end + 1
        start = temp;
    }

    // Perform binary search within the found range
    return binarySearch(arr, target, start, end);
}

let arr = [ 3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170 ];
let target = 10;
let ans = findPos(arr, target);
console.log(ans);

Output
4


Next Article
Article Tags :
Practice Tags :

Similar Reads