Detect a valid probe sequence in a binary search tree
Last Updated :
28 Apr, 2025
Given one integer X and a possible probe sequence of N integers, the task is to detect if the given sequence of integers can be visited in the exact same order while searching for a given element X in a binary search tree. In other words, detect a valid probe sequence in a binary search tree. The output is "Yes" if the given probe sequence is possible to achieve, else "No".
Note: Probe sequence is the sequence of nodes visited while searching for a particular element in a binary search tree.
Examples:
Input: X = 43, N = 6, arr[] = {2, 3, 50, 40, 60, 43}
Output: No
Explanation: 60 cannot occur after 40 as we have previously encountered 50 which was greater than X (43), so everything after 50 should be less than 50.
Input: X = 43, N = 6, arr[] = {10, 65, 31, 48, 37, 43}
Output: Yes
Explanation: Since all elements less than 43 (10, 31, 37) are in increasing order, all elements greater than 43(65, 48) are in decreasing order and the last element is 43, therefore arr[] is a valid probe sequence
Approach: To solve the problem follow the below observations:
Observations:
Consider that we are searching for a given element X in a binary search tree, and we have encountered an element q while searching. Now according to the property of the binary search tree, we know that all the elements in the left subtree of q are less than q and all the elements in the right subtree of q are greater than q.
Case 1: X < q
- As we can see that q is greater than X that means we have to search among the elements that are less than q, in other words the left subtree of q. As we enter the left subtree of q, all the elements we encounter in the rest of the probe sequence must be less than q. So we can conclude that:
- Once we encounter an element q which is greater than X, all the other elements in the upcoming part of the probe sequence must be less than q, in other words, all the keys greater than the search key must be present in Descending order.

Case 2: X > q
- As we can see that q is less than X that means we have to search among the elements that are greater than q, in other words the right subtree of q. As we enter the right subtree of q, all the elements we encounter in the rest of the probe sequence must be greater than q. So we can conclude that:
- Once we encounter an element q which is less than X, all the other elements in the upcoming part of the probe sequence must be greater than q, in other words, all the keys less than the search key must be present in ascending order.

At last the probe sequence is valid if and only if we find our desired element X at the end of the search.
Conclusion from the above observations:
- All the keys greater than the search key must be present in Descending order.
- All the keys less than the search key must be present in Ascending order.
- The search key must be present at the last of the given sequence.
Follow the steps mentioned below to implement the above observation:
- Initialize two variables that keeps track of the following two information
- The last element visited that was greater than the search key, initialize this to INT_MAX as we are going to check a decreasing sequence.
- The last element visited that was less than the search key, initialize this to INT_MIN as we are going to check an increasing sequence.
- Traverse the given probe sequence from 0 to N-1.
- If the current element is less than X, check that it must be greater than the last element less than X we have already visited.
- If the above condition is satisfied, update the last smaller element visited to the current element and continue. Else it is not in increasing order, then return false.
- If the current element is greater than X, check that it must be less than the last element greater than X we have already visited.
- If the above condition is satisfied, update the last greater element visited to the current element and continue. Else it is not in decreasing order, then return false.
- The search key must be present at the last of the given sequence, put an if condition to check that.
Below is the implementation for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
bool probe_sequence_is_valid(int X, int N, int* arr)
{
// Variable to keep track of last element
// visited that was greater than
// the search key
int last_greater_element = INT_MAX;
// variable to keep track of last element
// visited that was less than the search key
int last_smaller_element = INT_MIN;
bool is_valid = true;
// Traverse the given probe sequence
for (int i = 0; i < N; i++) {
// If the current element is less than X
if (arr[i] < X) {
// It must be greater than the last
// smaller element we visited, because
// the elements less than X must be
// in increasing order
if (arr[i] <= last_smaller_element)
return false;
last_smaller_element = arr[i];
}
// If the current element is greater than X
else if (arr[i] > X) {
// It must be less than the last
// greater element we visited,
// because the elements greater than
// X must be in decreasing order
if (arr[i] >= last_greater_element)
return false;
last_greater_element = arr[i];
}
}
// The search key must be present at
// the last of the given sequence
return arr[N - 1] == X;
}
// Drivers code
int main()
{
int X = 43;
int N = 6;
// For probe sequence 1
int arr1[N] = { 10, 65, 31, 48, 37, 43 };
bool is_valid = probe_sequence_is_valid(X, N, arr1);
string output1 = (is_valid) ? "Yes" : "No";
cout << output1 << endl;
// For probe sequence 2
int arr2[N] = { 2, 3, 50, 40, 60, 43 };
is_valid = probe_sequence_is_valid(X, N, arr2);
string output2 = (is_valid) ? "Yes" : "No";
cout << output2 << endl;
return 0;
}
Java
// Java code for the above approach:
public class Main {
public static boolean probeSequenceIsValid(int X, int N, int[] arr) {
// Variable to keep track of the last element
// visited that was greater than
// the search key
int lastGreaterElement = Integer.MAX_VALUE;
// Variable to keep track of the last element
// visited that was less than the search key
int lastSmallerElement = Integer.MIN_VALUE;
boolean isValid = true;
// Traverse the given probe sequence
for (int i = 0; i < N; i++) {
// If the current element is less than X
if (arr[i] < X) {
// It must be greater than the last
// smaller element we visited, because
// the elements less than X must be
// in increasing order
if (arr[i] <= lastSmallerElement)
return false;
lastSmallerElement = arr[i];
}
// If the current element is greater than X
else if (arr[i] > X) {
// It must be less than the last
// greater element we visited,
// because the elements greater than
// X must be in decreasing order
if (arr[i] >= lastGreaterElement)
return false;
lastGreaterElement = arr[i];
}
}
// The search key must be present at
// the last of the given sequence
return arr[N - 1] == X;
}
public static void main(String[] args) {
int X = 43;
int N = 6;
// For probe sequence 1
int[] arr1 = { 10, 65, 31, 48, 37, 43 };
boolean isValid1 = probeSequenceIsValid(X, N, arr1);
String output1 = (isValid1) ? "Yes" : "No";
System.out.println(output1);
// For probe sequence 2
int[] arr2 = { 2, 3, 50, 40, 60, 43 };
boolean isValid2 = probeSequenceIsValid(X, N, arr2);
String output2 = (isValid2) ? "Yes" : "No";
System.out.println(output2);
}
}
// this is contributed by uttamdp_10
Python
def probe_sequence_is_valid(X, N, arr):
# Variable to keep track of last element
# visited that was greater than
# the search key
last_greater_element = float('inf')
# variable to keep track of last element
# visited that was less than the search key
last_smaller_element = float('-inf')
is_valid = True
# Traverse the given probe sequence
for i in range(N):
# If the current element is less than X
if arr[i] < X:
# It must be greater than the last
# smaller element we visited, because
# the elements less than X must be
# in increasing order
if arr[i] <= last_smaller_element:
return False
last_smaller_element = arr[i]
# If the current element is greater than X
else:
# It must be less than the last
# greater element we visited,
# because the elements greater than
# X must be in decreasing order
if arr[i] >= last_greater_element:
return False
last_greater_element = arr[i]
# The search key must be present at
# the last of the given sequence
return arr[N - 1] == X
# Driver code
if __name__ == '__main__':
X = 43
N = 6
# For probe sequence 1
arr1 = [10, 65, 31, 48, 37, 43]
is_valid = probe_sequence_is_valid(X, N, arr1)
output1 = "Yes" if is_valid else "No"
print(output1)
# For probe sequence 2
arr2 = [2, 3, 50, 40, 60, 43]
is_valid = probe_sequence_is_valid(X, N, arr2)
output2 = "Yes" if is_valid else "No"
print(output2)
#Code addition by flutterfly
C#
public class ProbeSequenceIsValid
{
public static bool IsValid(int X, int N, int[] arr)
{
// Variable to keep track of last element
// visited that was greater than
// the search key
int lastGreaterElement = int.MaxValue;
// variable to keep track of last element
// visited that was less than the search key
int lastSmallerElement = int.MinValue;
bool isValid = true;
// Traverse the given probe sequence
for (int i = 0; i < N; i++)
{ // If the current element is less than X
if (arr[i] < X)
{ // It must be greater than the last
// smaller element we visited, because
// the elements less than X must be
// in increasing order
if (arr[i] <= lastSmallerElement)
{
return false;
}
lastSmallerElement = arr[i];
}
// If the current element is greater than X
else if (arr[i] > X)
{ // It must be less than the last
// greater element we visited,
// because the elements greater than
// X must be in decreasing order
if (arr[i] >= lastGreaterElement)
{
return false;
}
lastGreaterElement = arr[i];
}
}
// The search key must be present at
// the last of the given sequence
return arr[N - 1] == X;
}
public static void Main(string[] args)
{
int X = 43;
int N = 6;
// For probe sequence 1
int[] arr1 = new int[] { 10, 65, 31, 48, 37, 43 };
bool isValid = IsValid(X, N, arr1);
string output1 = isValid ? "Yes" : "No";
Console.WriteLine(output1);
// For probe sequence 2
int[] arr2 = new int[] { 2, 3, 50, 40, 60, 43 };
isValid = IsValid(X, N, arr2);
string output2 = isValid ? "Yes" : "No";
Console.WriteLine(output2);
}
}
JavaScript
function probeSequenceIsValid(X, N, arr) {
// Variable to keep track of the last element
// visited that was greater than
// the search key
let lastGreaterElement = Number.MAX_VALUE;
// Variable to keep track of the last element
// visited that was less than the search key
let lastSmallerElement = Number.MIN_VALUE;
let isValid = true;
// Traverse the given probe sequence
for (let i = 0; i < N; i++) {
// If the current element is less
if (arr[i] < X) {
// It must be greater than the last
// smaller element we visited, because
// the elements less than X must be
// in increasing order// If the current element is less than X
if (arr[i] <= lastSmallerElement)
return false;
lastSmallerElement = arr[i];
}
// If the current element is greater than X
else if (arr[i] > X) {
// It must be less than the last
// greater element we visited,
// because the elements greater than
// X must be in decreasing order
if (arr[i] >= lastGreaterElement)
return false;
lastGreaterElement = arr[i];
}
}
// The search key must be present at
// the last of the given sequence
return arr[N - 1] === X;
}
const X = 43;
const N = 6;
// For probe sequence 1
const arr1 = [10, 65, 31, 48, 37, 43];
const isValid1 = probeSequenceIsValid(X, N, arr1);
const output1 = (isValid1) ? "Yes" : "No";
console.log(output1);
// For probe sequence 2
const arr2 = [2, 3, 50, 40, 60, 43];
const isValid2 = probeSequenceIsValid(X, N, arr2);
const output2 = (isValid2) ? "Yes" : "No";
console.log(output2);
// by phasing17
Time Complexity: O(N)
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