Find position of an element in a sorted array of infinite numbers
Last Updated :
20 May, 2025
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;
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);
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 (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);
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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem