Open In App

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

Last Updated : 28 Aug, 2025
Comments
Improve
Suggest changes
242 Likes
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.

[Expected Approach] Using Recursive Binary Search

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;

    // Find high to do binary search
    while (h < arr.size() && arr[h] < key) {

        // Store previous high
        l = h;

        // Double high index
        h = 2 * h;
    }

    // Clamp high if it goes out of array bounds
    if (h >= arr.size())
        h = arr.size() - 1;

    // 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
import java.util.ArrayList;
import java.util.List;

// Java program to demonstrate working of an algorithm that finds
// an element in an array of infinite size
public class GfG {

    // Binary search function to find the element 
    // in a given range
    public static int binarySearch(List<Integer> arr, int l, int r, int x) {
        if (r >= l) {
            int mid = l + (r - l) / 2;
            if (arr.get(mid) == x)
                return mid;
            if (arr.get(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 list)
    public static int findPos(List<Integer> arr, int key) {
        int l = 0, h = 1;

        // Find high to do binary search
        while (h < arr.size() && arr.get(h) < key) {
            // Store previous high
            l = h;
            // Double high index
            h = 2 * h;
        }

        // Clamp high if it goes out of array bounds
        if (h >= arr.size())
            h = arr.size() - 1;

        // 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) {
        List<Integer> arr = List.of(3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170);
        int k = 170;
        int ans = findPos(arr, k);
        System.out.println(ans);
    }
}
Python
# Binary search function to find the element 
# in a given range
def binary_search(arr, l, r, x):
    if r >= l:
        mid = l + (r - l) // 2
        if arr[mid] == x:
            return mid
        if arr[mid] > x:
            return binary_search(arr, l, mid - 1, x)
        return binary_search(arr, mid + 1, r, x)
    return -1

# Function to find the position of the key in the 
# infinite-size array (represented as a list)
def find_pos(arr, key):
    l = 0
    h = 1

    # Find high to do binary search
    while h < len(arr) and arr[h] < key:
        # Store previous high
        l = h
        # Double high index
        h = 2 * h

    # Clamp high if it goes out of array bounds
    if h >= len(arr):
        h = len(arr) - 1

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

if __name__ == '__main__':
    arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]
    k = 170
    ans = find_pos(arr, k)
    print(ans)
C#
using System;
using System.Collections.Generic;

// C# program to demonstrate working of an algorithm that finds
// an element in an array of infinite size
public class GfG {

    // Binary search function to find the element 
    // in a given range
    public static int BinarySearch(List<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 list)
    public static int FindPos(List<int> arr, int key) {
        int l = 0, h = 1;

        // Find high to do binary search
        while (h < arr.Count && arr[h] < key) {
            // Store previous high
            l = h;
            // Double high index
            h = 2 * h;
        }

        // Clamp high if it goes out of array bounds
        if (h >= arr.Count)
            h = arr.Count - 1;

        // 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() {
        List<int> arr = new List<int> { 3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170 };
        int k = 170;
        int ans = FindPos(arr, k);
        Console.WriteLine(ans);
    }
}
JavaScript
// Binary search function to find the element 
// in a given range
function binarySearch(arr, l, r, x) {
    if (r >= l) {
        let mid = Math.floor(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 an array)
function findPos(arr, key) {
    let l = 0, h = 1;

    // Find high to do binary search
    while (h < arr.length && arr[h] < key) {
        // Store previous high
        l = h;
        // Double high index
        h = 2 * h;
    }

    // Clamp high if it goes out of array bounds
    if (h >= arr.length)
        h = arr.length - 1;

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

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

Output
4

Time Complexity: O(log p), where p is the index of the target key. The algorithm first doubles the search range (O(log p)), then performs binary search in that range (O(log p)), giving an overall complexity of O(log p).
Auxiliary Space: O(log p), due to the recursive calls of the binary search.

[Alternate Approach] Using Iterative Binary Search

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 (end < arr.size() && 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;

        // Clamp end if it goes out of array bounds
        if (end >= arr.size())
            end = arr.size() - 1;

        // 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 = 170;
    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
import java.util.*;

public class GfG {
    public static int binarySearch(ArrayList<Integer> 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.get(mid)) {
                end = mid - 1;
            }
            // If target is larger, search the right half
            else if (target > arr.get(mid)) {
                start = mid + 1;
            }
            // If target is found, return the index
            else {
                return mid;
            }
        }
        // If the target is not found, return -1
        return -1;
    }

    public static int findPos(ArrayList<Integer> 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 (end < arr.size() && target > arr.get(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;

            // Clamp end if it goes out of array bounds
            if (end >= arr.size())
                end = arr.size() - 1;

            // 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) {
        ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170));

        int target = 170;
        int ans = findPos(arr, target);
        System.out.println(ans);
    }
}
Python
def binary_search(arr, target, start, end):
    """Perform binary search within the range [start, end]"""
    while start <= end:
        mid = start + (end - start) // 2
        if target < arr[mid]:
            end = mid - 1
        elif target > arr[mid]:
            start = mid + 1
        else:
            return mid
    return -1


def find_pos(arr, target):
    """Find the position of the target in an array of infinite size"""
    start = 0
    end = 1
    while end < len(arr) and target > arr[end]:
        temp = end + 1
        end = end + (end - start + 1) * 2
        if end >= len(arr):
            end = len(arr) - 1
        start = temp
    return binary_search(arr, target, start, end)


if __name__ == '__main__':
    arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]
    target = 170
    ans = find_pos(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;
using System.Collections.Generic;

public class GfG {
    public static int BinarySearch(List<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;
    }

    public static int FindPos(List<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 (end < arr.Count && 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;

            // Clamp end if it goes out of array bounds
            if (end >= arr.Count)
                end = arr.Count - 1;

            // 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() {
        List<int> arr = new List<int> {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170};

        int target = 170;
        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 = Math.floor(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;
}

function findPos(arr, target) {
    // Initialize start and end for the search range
    let start = 0;
    let end = 1;

    // Keep doubling the search range until the target
    // is within the range
    while (end < arr.length && 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;

        // Clamp end if it goes out of array bounds
        if (end >= arr.length)
            end = arr.length - 1;

        // 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 = 170;
let ans = findPos(arr, target);
console.log(ans);

Output
10

Time Complexity: O(log p), where p is the index of the target key. The algorithm first doubles the search range (O(log p)), then performs binary search in that range (O(log p)), giving an overall complexity of O(log p).
Auxiliary Space: O(1)


Article Tags :

Explore