
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find k-th smallest element in given n ranges in C++
In this problem, we are given n ranges and an integer k. Our task is to find k-th smallest element in given n ranges.
We need to find the kth smallest elements from the array which is created after combining the ranges.
Let’s take an example to understand the problem,
Input: ranges = {{2, 5}, {7, 9}, {12, 15}}, k = 9
Output: 13
Explanation:
The array created is {2, 3, 4, 5, 7, 8, 9, 12, 13, 14, 15}
The smallest elements is 13
Solution Approach:
A simple solution to the problem is by creating the array from all ranges and as it is created from range it is also sorted in ascending order. Hence we just need to find the kth value of the array.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int main(){ int arr[][2] = {{2, 5}, {7, 9}, {12, 15}}; int n = sizeof(arr)/sizeof(arr[0]); int k = 9; int rangeArr[1000]; int size = 0; for(int i = 0; i < n; i++) for(int j = arr[i][0]; j <= arr[i][1]; j++) { rangeArr[size] = j; size++; } if(k < size) cout<<k<<"th smallest element of the ranged array is "<<rangeArr[k]<<endl; else cout<<"invalid Index"; return 0; }
Output
9th smallest element of the ranged array is 13
- Related Articles
- Find k-th smallest element in BST (Order Statistics in BST) in C++
- Find K-th Smallest Pair Distance in C++
- Find the k-th smallest divisor of a natural number N in C++
- K-th Smallest Prime Fraction in C++
- Find m-th smallest value in k sorted arrays in C++
- K-th Smallest in Lexicographical Order in C++
- Python program to find k'th smallest element in a 2D array
- K-th smallest element after removing some integers from natural numbers in C++
- Find the kth element in the series generated by the given N ranges in C++
- Find smallest number n such that n XOR n+1 equals to given k in C++
- Program to find out the k-th smallest difference between all element pairs in an array in C++
- Find smallest element greater than K in Python
- k-th missing element in sorted array in C++
- Find n-th element from Stern’s Diatomic Series in C++
- Find the k smallest numbers after deleting given elements in C++

Advertisements