Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
K’th Smallest Element in Unsorted Array
Next article icon

kth smallest/largest in a small range unsorted array

Last Updated : 07 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Find kth smallest or largest element in an unsorted array, where k<=size of array. It is given that elements of array are in small range.

Examples: 

Input : arr[] = {3, 2, 9, 5, 7, 11, 13}         k = 5 Output: 9  Input : arr[] = {16, 8, 9, 21, 43}         k = 3 Output: 16  Input : arr[] = {50, 50, 40}         k = 2 Output: 50

As the given array elements are in a small range, we can direct the index table to do something similar to counting sort. We store counts of elements, then we traverse the count array and print k-th element.

Implementation: Following is the implementation of the above algorithm 

C++
// C++ program of kth smallest/largest in  // a small range unsorted array #include <bits/stdc++.h> using namespace std; #define maxs 1000001  int kthSmallestLargest(int* arr, int n, int k) {     int max_val = *max_element(arr, arr+n);     int hash[max_val+1] = { 0 };      // Storing counts of elements     for (int i = 0; i < n; i++)          hash[arr[i]]++;              // Traverse hash array build above until     // we reach k-th smallest element.     int count = 0;     for (int i=0; i <= max_val; i++)     {         while (hash[i] > 0)         {            count++;            if (count == k)               return i;            hash[i]--;         }     }          return -1; }  int main() {     int arr[] = { 11, 6, 2, 9, 4, 3, 16 };     int n = sizeof(arr) / sizeof(arr[0]), k = 3;     cout << "kth smallest number is: "          << kthSmallestLargest(arr, n, k) << endl;     return 0; } 
Java
// Java program of kth smallest/largest in  // a small range unsorted array  import java.util.Arrays;  class GFG  {      static int maxs = 1000001;      static int kthSmallestLargest(int[] arr, int n, int k)      {         int max_val = Arrays.stream(arr).max().getAsInt();         int hash[] = new int[max_val + 1];          // Storing counts of elements         for (int i = 0; i < n; i++)          {             hash[arr[i]]++;         }          // Traverse hash array build above until         // we reach k-th smallest element.         int count = 0;         for (int i = 0; i <= max_val; i++)         {             while (hash[i] > 0)              {                 count++;                 if (count == k)                  {                     return i;                 }                 hash[i]--;             }         }          return -1;     }      // Driver code     public static void main(String[] args)     {         int arr[] = {11, 6, 2, 9, 4, 3, 16};         int n = arr.length, k = 3;         System.out.println("kth smallest number is: "                 + kthSmallestLargest(arr, n, k));     } }  // This code has been contributed by 29AjayKumar 
Python3
# Python 3 program of kth smallest/largest  # in a small range unsorted array  def kthSmallestLargest(arr, n, k):     max_val = arr[0]     for i in range(len(arr)):         if (arr[i] > max_val):             max_val = arr[i]     hash = [0 for i in range(max_val + 1)]       # Storing counts of elements     for i in range(n):         hash[arr[i]] += 1          # Traverse hash array build above until     # we reach k-th smallest element.     count = 0     for i in range(max_val + 1):         while (hash[i] > 0):             count += 1             if (count == k):                 return i             hash[i] -= 1              return -1  # Driver Code if __name__ == '__main__':     arr = [11, 6, 2, 9, 4, 3, 16]     n = len(arr)     k = 3     print("kth smallest number is:",            kthSmallestLargest(arr, n, k))      # This code is contributed by # Surendra_Gangwar 
C#
// C# program of kth smallest/largest in  // a small range unsorted array  using System; using System.Linq;  class GFG  {       static int maxs = 1000001;       static int kthSmallestLargest(int[] arr, int n, int k)      {          int max_val = arr.Max();          int []hash = new int[max_val + 1];           // Storing counts of elements          for (int i = 0; i < n; i++)          {              hash[arr[i]]++;          }           // Traverse hash array build above until          // we reach k-th smallest element.          int count = 0;          for (int i = 0; i <= max_val; i++)          {              while (hash[i] > 0)              {                  count++;                  if (count == k)                  {                      return i;                  }                  hash[i]--;              }          }          return -1;      }       // Driver code      public static void Main()      {          int []arr = {11, 6, 2, 9, 4, 3, 16};          int n = arr.Length, k = 3;          Console.WriteLine("kth smallest number is: "                 + kthSmallestLargest(arr, n, k));      }  }   /* This code contributed by PrinciRaj1992 */ 
PHP
<?php // PHP program of kth smallest/largest in  // a small range unsorted array $maxs = 1000001;   function kthSmallestLargest(&$arr, $n, $k) {     global $maxs;     $max_val = max($arr);     $hash = array_fill(0,$max_val+1, NULL);       // Storing counts of elements     for ($i = 0; $i < $n; $i++)          $hash[$arr[$i]]++;               // Traverse hash array build above until     // we reach k-th smallest element.     $count = 0;     for ($i=0; $i <= $max_val; $i++)     {         while ($hash[$i] > 0)         {            $count++;            if ($count == $k)               return $i;            $hash[$i]--;         }     }           return -1; }        $arr = array ( 11, 6, 2, 9, 4, 3, 16 );     $n = sizeof($arr) / sizeof($arr[0]);     $k = 3;     echo "kth smallest number is: "          . kthSmallestLargest($arr, $n, $k)."\n";     return 0; ?> 
JavaScript
<script> // Javascript program of kth smallest/largest in  // a small range unsorted array           let maxs = 1000001;     function kthSmallestLargest(arr,n,k)     {         let max_val = Math.max(...arr);         let hash = new Array(max_val + 1);         for(let i=0;i<hash.length;i++)         {             hash[i]=0;         }            // Storing counts of elements         for (let i = 0; i < n; i++)          {             hash[arr[i]]++;         }            // Traverse hash array build above until         // we reach k-th smallest element.         let count = 0;         for (let i = 0; i <= max_val; i++)         {             while (hash[i] > 0)              {                 count++;                 if (count == k)                  {                     return i;                 }                 hash[i]--;             }         }            return -1;     }          // Driver code     let arr=[11, 6, 2, 9, 4, 3, 16];     let n = arr.length, k = 3;     document.write("kth smallest number is: "                 + kthSmallestLargest(arr, n, k));       // This code is contributed by avanitrachhadiya2155 </script> 

Output
kth smallest number is: 4

Complexity Analysis:

  • Time Complexity: O(n + max_val)
  • Auxiliary Space: O(n) for hash array.

Next Article
K’th Smallest Element in Unsorted Array

D

Dhirendra121
Improve
Article Tags :
  • Searching
  • DSA
Practice Tags :
  • Searching

Similar Reads

  • Rearrange an array in order - smallest, largest, 2nd smallest, 2nd largest, ..
    Given an array of integers, the task is to print the array in the order - smallest number, the Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number, and so on..... Examples: Input : arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6] Output :arr[] = {1, 9, 2, 8, 3, 7, 4,
    7 min read
  • K’th Smallest/Largest Element in Unsorted Array | Expected Linear Time
    Given an array of distinct integers and an integer k, where k is smaller than the array's size, the task is to find the k'th smallest element in the array. Examples: Input: arr = [7, 10, 4, 3, 20, 15], k = 3Output: 7Explanation: The sorted array is [3, 4, 7, 10, 15, 20], so the 3rd smallest element
    10 min read
  • K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
    Given an array and a number k where k is smaller than the size of the array, we need to find the k’th largest element in the given array. It is given that all array elements are distinct. We recommend reading the following post as a prerequisite to this post. K’th Smallest/Largest Element in Unsorte
    9 min read
  • K’th Smallest/Largest Element in Unsorted Array | Worst case Linear Time
    Given an array of distinct integers arr[] and an integer k. The task is to find the k-th smallest element in the array. For better understanding, k refers to the element that would appear in the k-th position if the array were sorted in ascending order. Note: k will always be less than the size of t
    15 min read
  • K’th Smallest Element in Unsorted Array
    Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content [Naive
    15+ min read
  • How to get largest and smallest number in an Array?
    Given an array arr[] of length N, The task is to find the maximum and the minimum number in the array. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: Maximum is: 5Minimum is: 1Explanation: The maximum of the array is 5 and the minimum of the array is 1. Input: arr[] = {5, 3, 7, 4, 2}Output: Maximum
    15 min read
  • Kth largest element in an N-array Tree
    Given an N-array Tree consisting of N nodes and an integer K, the task is to find the Kth largest element in the given N-ary Tree. Examples: Input: K = 3 Output: 77 Explanation:The 3rd largest element in the given N-array tree is 77. Input: K = 4 Output: 3 Approach: The given problem can be solved b
    9 min read
  • Sudo Placement[1.5] | Second Smallest in Range
    Given an array of N integers and Q queries. Every query consists of L and R. The task is to print the second smallest element in range L-R. Print -1 if no second smallest element exists. Examples: Input: a[] = {1, 2, 2, 4} Queries= 2 L = 1, R = 2 L = 0, R = 1Output: -1 2 Approach: Process every quer
    6 min read
  • Smallest Range with Elements from k Sorted Lists
    Given a 2d integer array arr[][] of order k * n, where each row is sorted in ascending order. Your task is to find the smallest range that includes at least one element from each of the K lists. If more than one such ranges are found, return the first one. Examples: Input: arr[][] = [[ 4, 7, 9, 12,
    15+ min read
  • Queries for k-th smallest in given ranges
    Given n ranges of the form [l, r] and an integer q denoting the number of queries. The task is to return the kth smallest element for each query (assume k>1) after combining all the ranges. In case the kth smallest element doesn't exist, return -1. Examples : Input: n = 2, q = 3, range[] = {{1, 4
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences